diff --git a/tests-integration/AGENTS.md b/tests-integration/AGENTS.md index 25531aeb1b9..2389508aac3 100644 --- a/tests-integration/AGENTS.md +++ b/tests-integration/AGENTS.md @@ -2,7 +2,11 @@ Integration test modules are registered in `tests/main.rs` (`autotests = false`). Shared instance and storage helpers live in `src/instance.rs` and -`src/test_util.rs`. See [README.md](README.md) for external-service setup. +`src/test_util.rs`. Cluster setup lives in `src/cluster.rs`, with datanode registration +checks in `src/cluster/registration.rs`. Datanode RPC serving, the duplex and TCP paths, +and `DoGet` accounting live in `src/cluster/transport.rs`. Shared migration and +partition scenarios live in `src/cluster/migration.rs` and `src/cluster/partition.rs`. +See [README.md](README.md) for external-service setup. ## Import/export portability diff --git a/tests-integration/Cargo.toml b/tests-integration/Cargo.toml index 2272ecc710a..dd80e9ab3f0 100644 --- a/tests-integration/Cargo.toml +++ b/tests-integration/Cargo.toml @@ -130,6 +130,7 @@ sqlx = { workspace = true, features = [ store-api.workspace = true temp-env.workspace = true time = "0.3" +tokio = { workspace = true, features = ["test-util"] } tokio-postgres = { workspace = true } tokio-util.workspace = true url = "2.3" diff --git a/tests-integration/src/cluster.rs b/tests-integration/src/cluster.rs index 8a04b839ead..ea9384a3aea 100644 --- a/tests-integration/src/cluster.rs +++ b/tests-integration/src/cluster.rs @@ -12,20 +12,20 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub mod migration; +pub mod partition; +mod registration; +mod transport; + use std::collections::{BTreeSet, HashMap}; use std::env; use std::future::Future; use std::net::TcpListener; -use std::ops::{Deref, DerefMut, RangeInclusive}; +use std::ops::RangeInclusive; use std::pin::Pin; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; -use std::task::{Context, Poll}; use std::time::Duration; -use api::v1::health_check_server::HealthCheckServer; -use api::v1::region::region_server::RegionServer; -use arrow_flight::flight_service_server::FlightServiceServer; use cache::{ build_datanode_layered_cache_registry, build_fundamental_cache_registry, with_default_composite_cache_registry, @@ -34,13 +34,12 @@ use catalog::information_extension::DistributedInformationExtension; use catalog::kvbackend::{ CachedKvBackendBuilder, KvBackendCatalogManagerBuilder, new_read_only_meta_kv_backend, }; -use client::Client; use client::client_manager::NodeClients; use cmd::frontend::create_heartbeat_task; use common_base::Plugins; use common_datasource::object_store::LocalFileAccess; use common_event_recorder::EventRecorderOptions; -use common_grpc::channel_manager::{ChannelConfig, ChannelManager}; +use common_grpc::channel_manager::ChannelConfig; use common_meta::DatanodeId; use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder}; use common_meta::kv_backend::KvBackendRef; @@ -48,10 +47,7 @@ use common_meta::kv_backend::chroot::ChrootKvBackend; use common_meta::kv_backend::etcd::EtcdStore; use common_meta::kv_backend::memory::MemoryKvBackend; use common_meta::peer::Peer; -use common_runtime::Builder as RuntimeBuilder; -use common_runtime::runtime::BuilderBuild; use common_test_util::temp_dir::create_temp_dir; -use common_time::util::DefaultSystemTimer; use common_wal::config::{DatanodeWalConfig, MetasrvWalConfig}; use datanode::config::DatanodeOptions; use datanode::datanode::{Datanode, DatanodeBuilder, ProcedureConfig}; @@ -61,10 +57,7 @@ use frontend::instance::builder::FrontendBuilder; use frontend::server::Services; use frontend::service_config::BatcherOptions; use futures::TryStreamExt; -use hyper_util::rt::TokioIo; use meta_client::client::MetaClientBuilder; -use meta_srv::cluster::MetaPeerClientRef; -use meta_srv::discovery; use meta_srv::gc::GcSchedulerOptions; use meta_srv::metasrv::{Metasrv, MetasrvOptions, SelectorRef}; use meta_srv::mocks::MockInfo; @@ -72,79 +65,41 @@ use mito2::gc::GcConfig; use mito2::region::MitoRegionRef; use object_store::config::ObjectStoreConfig; use rand::Rng; -use servers::grpc::flight::FlightCraftWrapper; -use servers::grpc::region_server::RegionServerRequestHandler; -use servers::grpc::{GrpcOptions, HealthCheckHandler}; +use servers::grpc::GrpcOptions; use servers::server::ServerHandlers; use store_api::storage::RegionId; use tempfile::TempDir; -use tokio::io::{AsyncRead, AsyncWrite}; -use tonic::codec::CompressionEncoding; -use tonic::transport::Server; -use tonic::transport::server::Connected; -use tower::{Layer, Service, service_fn}; use uuid::Uuid; +pub use self::registration::wait_for_datanode_registration; +pub use self::transport::DatanodeRpcStats; +use crate::cluster::transport::{ActiveDoGet, build_datanode_clients, create_datanode_client}; use crate::test_util::{ self, FileDirGuard, StorageType, TestGuard, create_datanode_opts, create_tmp_dir_and_datanode_opts, }; -/// Flight `DoGet` requests sent to a datanode over its network address (see -/// [`GreptimeDbClusterBuilder::with_real_datanode_grpc_addr`]). In-process duplex requests are not -/// counted. Request totals are per datanode; active and peak counts are shared by all datanode -/// listeners in the cluster. By default, the frontend uses duplex, but it can opt into TCP with -/// [`GreptimeDbClusterBuilder::with_frontend_real_datanode_grpc`]. -#[derive(Debug, Default)] -pub struct DatanodeRpcStats { - do_get_requests: AtomicUsize, - active: Arc>, -} - -#[derive(Debug, Default)] -struct ActiveDoGet { - current: usize, - peak: usize, -} - -impl DatanodeRpcStats { - /// The total number of Flight `DoGet` requests received over TCP. - pub fn requests(&self) -> usize { - self.do_get_requests.load(Ordering::Relaxed) - } - - /// The cluster-wide number of TCP `DoGet` calls with a pending response or live response body. - pub fn active(&self) -> usize { - self.active.lock().unwrap().current - } - - /// The cluster-wide peak number of concurrently active TCP `DoGet` calls since the last reset. - pub fn peak_active(&self) -> usize { - self.active.lock().unwrap().peak - } - - /// Reset the peak to the number of currently active calls. - pub fn reset_peak_active(&self) { - let mut active = self.active.lock().unwrap(); - active.peak = active.current; - } - - fn start(self: &Arc) -> DoGetGuard { - self.do_get_requests.fetch_add(1, Ordering::Relaxed); - let mut active = self.active.lock().unwrap(); - active.current += 1; - active.peak = active.peak.max(active.current); - DoGetGuard(self.clone()) - } -} - -/// Keeps a `DoGet` active until its response body is dropped, including cancellation and errors. -struct DoGetGuard(Arc); - -impl Drop for DoGetGuard { - fn drop(&mut self) { - self.0.active.lock().unwrap().current -= 1; +/// Awaits the metadata service, starts each datanode with `start_node`, then passes +/// the service and nodes to `connect`. +/// +/// `metadata` is boxed: the metasrv startup future is large enough to overflow the default +/// 2 MiB test stack when it shares a frame with the datanode and frontend startup. +pub async fn start_cluster( + metadata: Pin>>, + options: impl IntoIterator, + mut start_node: impl FnMut(&M, O) -> NodeFuture, + connect: impl FnOnce(M, Vec) -> ClusterFuture, +) -> C +where + NodeFuture: Future, + ClusterFuture: Future, +{ + let metadata = metadata.await; + let mut nodes = Vec::new(); + for options in options { + nodes.push(start_node(&metadata, options).await); } + connect(metadata, nodes).await } pub struct GreptimeDbCluster { @@ -177,18 +132,17 @@ impl GreptimeDbCluster { /// Number of active TCP `DoGet` calls across all datanodes in this cluster. pub fn network_do_get_active(&self) -> usize { - self.network_do_get.lock().unwrap().current + self.network_do_get.lock().unwrap().current() } /// Peak active TCP `DoGet` calls across all datanodes since the last reset. pub fn network_do_get_peak_active(&self) -> usize { - self.network_do_get.lock().unwrap().peak + self.network_do_get.lock().unwrap().peak() } /// Reset the cluster-wide peak to the number of currently active calls. pub fn reset_network_do_get_peak(&self) { - let mut active = self.network_do_get.lock().unwrap(); - active.peak = active.current; + self.network_do_get.lock().unwrap().reset_peak(); } /// List all SST files from all datanodes. @@ -259,6 +213,7 @@ pub struct GreptimeDbClusterBuilder { store_config: Option, store_providers: Option>, datanodes: Option, + datanode_registration_timeout: Duration, mito_config: Option, datanode_wal_config: DatanodeWalConfig, metasrv_wal_config: MetasrvWalConfig, @@ -303,6 +258,7 @@ impl GreptimeDbClusterBuilder { store_config: None, store_providers: None, datanodes: None, + datanode_registration_timeout: Duration::from_secs(10), mito_config: None, datanode_wal_config: DatanodeWalConfig::default(), metasrv_wal_config: MetasrvWalConfig::default(), @@ -341,6 +297,13 @@ impl GreptimeDbClusterBuilder { self } + /// Sets how long to wait for metasrv to observe all datanodes (default 10 seconds). + #[must_use] + pub fn with_datanode_registration_timeout(mut self, timeout: Duration) -> Self { + self.datanode_registration_timeout = timeout; + self + } + /// Overrides the Mito config of each datanode in the test cluster. pub fn with_mito_config(mut self, config: mito2::config::MitoConfig) -> Self { self.mito_config = Some(config); @@ -490,74 +453,85 @@ impl GreptimeDbClusterBuilder { test_util::prepare_another_catalog_and_schema_with_kv_backend(self.kv_backend.clone()) .await; - let metasrv = meta_srv::mocks::mock_with_plugins( + let metadata = Box::pin(meta_srv::mocks::mock_with_plugins( opt, self.kv_backend.clone(), self.meta_selector.clone(), Some(datanode_clients.clone()), None, self.plugins.clone(), + )); + start_cluster( + metadata, + datanode_options.clone(), + |meta, options: DatanodeOptions| { + let meta = meta.clone(); + async move { + let id = options.node_id.unwrap(); + (id, self.create_datanode(options, meta).await) + } + }, + move |metasrv: MockInfo, nodes| async move { + let datanode_instances = nodes.into_iter().collect(); + let network_do_get = Arc::new(Mutex::new(ActiveDoGet::default())); + let datanode_rpc_stats = if self.real_datanode_grpc_addr { + datanode_options + .iter() + .map(|opts| { + ( + opts.node_id.unwrap(), + Arc::new(DatanodeRpcStats::with_active(network_do_get.clone())), + ) + }) + .collect::>() + } else { + HashMap::new() + }; + + build_datanode_clients( + datanode_clients.clone(), + &datanode_instances, + &datanode_options, + &datanode_rpc_stats, + ) + .await; + + wait_for_datanode_registration( + metasrv.metasrv.meta_peer_client().as_ref(), + datanodes, + self.datanode_registration_timeout, + ) + .await; + + // Metasrv keeps its duplex clients; the frontend gets an empty cache so its misses + // construct TCP clients using the addresses registered by the datanodes. + let frontend_clients = + if self.real_datanode_grpc_addr && self.frontend_real_datanode_grpc { + Arc::new(NodeClients::new(channel_config)) + } else { + datanode_clients.clone() + }; + let mut frontend = self + .build_frontend(metasrv.clone(), frontend_clients, start_frontend_servers) + .await; + + frontend.start().await.unwrap(); + + GreptimeDbCluster { + datanode_options, + guards, + datanode_instances, + datanode_rpc_stats, + network_do_get, + kv_backend: self.kv_backend.clone(), + metasrv: metasrv.metasrv.clone(), + metasrv_connection: metasrv, + datanode_clients, + frontend: Arc::new(frontend), + } + }, ) - .await; - - let datanode_instances = self - .build_datanodes_with_options(&metasrv, &datanode_options) - .await; - - let network_do_get = Arc::new(Mutex::new(ActiveDoGet::default())); - let datanode_rpc_stats = if self.real_datanode_grpc_addr { - datanode_options - .iter() - .map(|opts| { - ( - opts.node_id.unwrap(), - Arc::new(DatanodeRpcStats { - active: network_do_get.clone(), - ..Default::default() - }), - ) - }) - .collect::>() - } else { - HashMap::new() - }; - - build_datanode_clients( - datanode_clients.clone(), - &datanode_instances, - &datanode_options, - &datanode_rpc_stats, - ) - .await; - - self.wait_datanodes_alive(metasrv.metasrv.meta_peer_client(), datanodes) - .await; - - // Metasrv keeps its duplex clients; the frontend gets an empty cache so its misses - // construct TCP clients using the addresses registered by the datanodes. - let frontend_clients = if self.real_datanode_grpc_addr && self.frontend_real_datanode_grpc { - Arc::new(NodeClients::new(channel_config)) - } else { - datanode_clients.clone() - }; - let mut frontend = self - .build_frontend(metasrv.clone(), frontend_clients, start_frontend_servers) - .await; - - frontend.start().await.unwrap(); - - GreptimeDbCluster { - datanode_options, - guards, - datanode_instances, - datanode_rpc_stats, - network_do_get, - kv_backend: self.kv_backend.clone(), - metasrv: metasrv.metasrv.clone(), - metasrv_connection: metasrv, - datanode_clients, - frontend: Arc::new(frontend), - } + .await } /// Creates a fresh plugin registry for each datanode start, including restarts. @@ -688,45 +662,6 @@ impl GreptimeDbClusterBuilder { format!("{}:{}", localhost, port) } - async fn build_datanodes_with_options( - &self, - metasrv: &MockInfo, - options: &[DatanodeOptions], - ) -> HashMap { - let mut instances = HashMap::with_capacity(options.len()); - - for opts in options { - let datanode = self.create_datanode(opts.clone(), metasrv.clone()).await; - let datanode_id = opts.node_id.unwrap(); - instances.insert(datanode_id, datanode); - } - - instances - } - - async fn wait_datanodes_alive( - &self, - meta_peer_client: &MetaPeerClientRef, - expected_datanodes: usize, - ) { - for _ in 0..100 { - let alive_datanodes = discovery::utils::alive_datanode_infos( - &DefaultSystemTimer, - meta_peer_client.as_ref(), - Duration::from_secs(u64::MAX), - None, - ) - .await - .unwrap() - .len(); - if alive_datanodes == expected_datanodes { - return; - } - tokio::time::sleep(Duration::from_micros(100)).await - } - panic!("Some Datanodes are not alive in 10 seconds!") - } - async fn create_datanode(&self, opts: DatanodeOptions, metasrv: MockInfo) -> Datanode { let mut meta_client = MetaClientBuilder::datanode_default_options(opts.node_id.unwrap()) .channel_manager(metasrv.channel_manager) @@ -891,204 +826,6 @@ impl GreptimeDbClusterBuilder { } } -async fn build_datanode_clients( - clients: Arc, - instances: &HashMap, - options: &[DatanodeOptions], - rpc_stats: &HashMap>, -) { - for opts in options { - let datanode_id = opts.node_id.unwrap(); - let instance = &instances[&datanode_id]; - let (addr, client) = create_datanode_client( - instance, - &opts.grpc.server_addr, - rpc_stats.get(&datanode_id).cloned(), - ) - .await; - clients - .insert_client(Peer::new(datanode_id, addr), client) - .await; - } -} - -/// Runs a gRPC server that serves the region server of `datanode` over `incoming` until the -/// cluster is dropped. -fn serve_datanode_region_server( - datanode: &Datanode, - incoming: I, - rpc_stats: Option>, -) where - I: futures::Stream> + Send + 'static, - IO: AsyncRead + AsyncWrite + Connected + Unpin + Send + 'static, -{ - let runtime = RuntimeBuilder::default() - .worker_threads(2) - .thread_name("grpc-handlers") - .build() - .unwrap(); - - let flight_handler = FlightCraftWrapper(datanode.region_server()); - let region_server_handler = - RegionServerRequestHandler::new(Arc::new(datanode.region_server()), runtime); - - tokio::spawn(async move { - Server::builder() - .layer(CountRequestsLayer { rpc_stats }) - .add_service( - FlightServiceServer::new(flight_handler) - .accept_compressed(CompressionEncoding::Gzip) - .accept_compressed(CompressionEncoding::Zstd) - .send_compressed(CompressionEncoding::Gzip) - .send_compressed(CompressionEncoding::Zstd), - ) - .add_service( - RegionServer::new(region_server_handler) - .accept_compressed(CompressionEncoding::Gzip) - .accept_compressed(CompressionEncoding::Zstd) - .send_compressed(CompressionEncoding::Gzip) - .send_compressed(CompressionEncoding::Zstd), - ) - .add_service(HealthCheckServer::new(HealthCheckHandler)) - .serve_with_incoming(incoming) - .await - }); -} - -/// Serves the region server of `datanode` and returns the address and the client of the address. -/// -/// The returned client is always an in-process duplex client, keeping its traffic out of -/// `rpc_stats`. The frontend can instead use separate TCP clients when opted in. -/// -/// [`test_util::PEER_PLACEHOLDER_ADDR`] is not a real address, so it cannot be served over the -/// network at all. Any other address is a real one: the region server is additionally served on -/// its local TCP port, and `rpc_stats` counts requests reaching that port. -async fn create_datanode_client( - datanode: &Datanode, - addr: &str, - rpc_stats: Option>, -) -> (String, Client) { - let (client, server) = tokio::io::duplex(1024); - serve_datanode_region_server( - datanode, - futures::stream::iter(vec![Ok::<_, std::io::Error>(server)]), - None, - ); - - if addr != test_util::PEER_PLACEHOLDER_ADDR { - let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); - let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener); - serve_datanode_region_server(datanode, incoming, rpc_stats); - } - - let mut client = Some(client); - let channel_manager = ChannelManager::new(); - channel_manager - .reset_with_connector( - addr, - service_fn(move |_| { - let client = client.take(); - - async move { - client - .map(TokioIo::new) - .ok_or_else(|| std::io::Error::other("Client already taken")) - } - }), - ) - .unwrap(); - - ( - addr.to_string(), - // The mock connector pool lives on this single manager, so both lanes - // intentionally share it (same semantics as the legacy constructor). - Client::with_query_and_control_managers(channel_manager.clone(), channel_manager, [addr]), - ) -} - -/// Counts Flight `DoGet` requests received by the wrapped server. -#[derive(Clone)] -struct CountRequests { - inner: S, - rpc_stats: Option>, -} - -impl Service> for CountRequests -where - S: Service, Response = http::Response>, - S::Future: Send + 'static, - S::Error: Send + 'static, -{ - type Response = http::Response; - type Error = S::Error; - type Future = Pin> + Send>>; - - fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { - self.inner.poll_ready(cx) - } - - fn call(&mut self, request: http::Request) -> Self::Future { - let guard = if request.uri().path() == "/arrow.flight.protocol.FlightService/DoGet" { - self.rpc_stats.as_ref().map(DatanodeRpcStats::start) - } else { - None - }; - let future = self.inner.call(request); - - Box::pin(async move { - let response = future.await?; - Ok(response.map(|body| match guard { - Some(guard) => { - // The pinned body delegates HTTP frames (including gRPC trailers) while the - // pointer owns the guard until the body is dropped. - tonic::body::Body::new(Pin::new(GuardedBody { - body: Box::new(body), - _guard: guard, - })) - } - None => body, - })) - }) - } -} - -// Dereferencing to the inner body lets tonic wrap it while keeping the guard alive until the -// streaming body is completed and dropped, or the caller cancels the response. -struct GuardedBody { - body: Box, - _guard: DoGetGuard, -} - -impl Deref for GuardedBody { - type Target = tonic::body::Body; - - fn deref(&self) -> &Self::Target { - &self.body - } -} - -impl DerefMut for GuardedBody { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.body - } -} - -#[derive(Clone)] -struct CountRequestsLayer { - rpc_stats: Option>, -} - -impl Layer for CountRequestsLayer { - type Service = CountRequests; - - fn layer(&self, inner: S) -> Self::Service { - CountRequests { - inner, - rpc_stats: self.rpc_stats.clone(), - } - } -} - // Mock connectors are registered on a shared channel manager. #[cfg(test)] #[allow(deprecated)] @@ -1096,6 +833,8 @@ mod tests { use std::sync::atomic::{AtomicBool, Ordering}; use api::v1::flow::FlowRequest; + use api::v1::health_check_server::HealthCheckServer; + use api::v1::region::region_server::RegionServer; use api::v1::region::{ ListMetadataRequest, RegionRequest, RegionRequestHeader, region_request, }; @@ -1103,14 +842,22 @@ mod tests { use client::Client; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; + use common_grpc::channel_manager::ChannelManager; use common_meta::ddl_manager::{DdlManager, DdlManagerConfigurator, DdlManagerConfiguratorRef}; use common_meta::key::TableMetadataManager; use common_meta::key::flow::FlowMetadataManager; use common_meta::kv_backend::memory::MemoryKvBackend; use common_meta::node_manager::{DatanodeManager, FlownodeManager}; use common_meta::peer::Peer; + use common_runtime::Builder as RuntimeBuilder; + use common_runtime::runtime::BuilderBuild; use flow::{FlownodeBuilder, FlownodeOptions, FlownodeServiceBuilder, FrontendClient}; + use hyper_util::rt::TokioIo; use meta_srv::metasrv::builder::DdlManagerConfigureContext; + use servers::grpc::HealthCheckHandler; + use servers::grpc::region_server::RegionServerRequestHandler; + use tonic::transport::Server; + use tower::service_fn; use super::*; @@ -1216,104 +963,6 @@ mod tests { assert_eq!(kv.range(lost_keys).await.unwrap().kvs, before); } - #[tokio::test] - async fn test_do_get_stats_follow_response_body_lifetime() { - let stats = Arc::new(DatanodeRpcStats::default()); - let mut service = CountRequests { - inner: service_fn(|_: http::Request<()>| async { - let stream = futures::stream::once(async { - Ok::<_, std::io::Error>(axum::body::Bytes::from_static(b"data")) - }); - let body = tonic::body::Body::new(axum::body::Body::from_stream(stream)); - Ok::<_, std::convert::Infallible>(http::Response::new(body)) - }), - rpc_stats: Some(stats.clone()), - }; - let request = || { - http::Request::builder() - .uri("/arrow.flight.protocol.FlightService/DoGet") - .body(()) - .unwrap() - }; - - let first = service.call(request()).await.unwrap(); - let other_stats = Arc::new(DatanodeRpcStats { - active: stats.active.clone(), - ..Default::default() - }); - service.rpc_stats = Some(other_stats.clone()); - let second = service.call(request()).await.unwrap(); - assert_eq!( - ( - stats.requests(), - other_stats.requests(), - stats.active(), - stats.peak_active() - ), - (1, 1, 2, 2) - ); - assert_eq!((other_stats.active(), other_stats.peak_active()), (2, 2)); - stats.reset_peak_active(); - assert_eq!(stats.peak_active(), 2); - - // Completing one body and dropping another both release their guards. - let body = axum::body::Body::new(first.into_body()); - assert_eq!( - axum::body::to_bytes(body, usize::MAX).await.unwrap(), - "data" - ); - assert_eq!(stats.active(), 1); - stats.reset_peak_active(); - assert_eq!(stats.peak_active(), 1); - drop(second); - assert_eq!(stats.active(), 0); - stats.reset_peak_active(); - assert_eq!(stats.peak_active(), 0); - - let other = http::Request::builder().uri("/other").body(()).unwrap(); - let other = service.call(other).await.unwrap(); - assert_eq!( - (stats.requests(), other_stats.requests(), stats.active()), - (1, 1, 0) - ); - drop(other); - } - - #[tokio::test] - async fn test_do_get_stats_release_on_future_cancel_or_error() { - let stats = Arc::new(DatanodeRpcStats::default()); - let request = || { - http::Request::builder() - .uri("/arrow.flight.protocol.FlightService/DoGet") - .body(()) - .unwrap() - }; - let mut pending = CountRequests { - inner: service_fn(|_: http::Request<()>| { - std::future::pending::< - Result, std::convert::Infallible>, - >() - }), - rpc_stats: Some(stats.clone()), - }; - let future = pending.call(request()); - assert_eq!(stats.active(), 1); - drop(future); - assert_eq!(stats.active(), 0); - - let mut failing = CountRequests { - inner: service_fn(|_: http::Request<()>| async { - Err::, _>(std::io::Error::other("failed")) - }), - rpc_stats: Some(stats.clone()), - }; - assert!(failing.call(request()).await.is_err()); - assert_eq!( - (stats.requests(), stats.active(), stats.peak_active()), - (2, 0, 1) - ); - } - #[cfg(feature = "enterprise")] #[tokio::test(flavor = "multi_thread")] async fn test_object_store_cluster_entry_and_restart() { diff --git a/tests-integration/src/cluster/migration.rs b/tests-integration/src/cluster/migration.rs new file mode 100644 index 00000000000..d3e34957d88 --- /dev/null +++ b/tests-integration/src/cluster/migration.rs @@ -0,0 +1,114 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; +use std::time::Duration; + +use client::{Database, OutputData}; +use common_meta::DatanodeId; +use common_meta::key::table_route::TableRouteManager; +use common_recordbatch::RecordBatches; +use datatypes::arrow::array::AsArray; +use frontend::instance::Instance; +use store_api::storage::RegionId; + +use crate::test_util::execute_sql; + +/// Triggers region migration through the authenticated public gRPC SQL endpoint. +pub async fn migrate_region( + database: &Database, + region_id: u64, + from_peer_id: u64, + to_peer_id: u64, +) -> String { + let output = database + .sql(format!( + "admin migrate_region({region_id}, {from_peer_id}, {to_peer_id})" + )) + .await + .unwrap(); + let recordbatches = match output.data { + OutputData::RecordBatches(recordbatches) => recordbatches, + OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(), + OutputData::AffectedRows(_) => unreachable!(), + }; + + let record_batch = &recordbatches.take()[0]; + record_batch + .column(0) + .as_string::() + .value(0) + .to_string() +} + +/// Polls `admin procedure_state` until the migration procedure reaches `Done`, and panics +/// with the last observed state on timeout. +pub async fn wait_for_migration(instance: &Arc, pid: &str, timeout: Duration) { + let mut state = String::new(); + tokio::time::timeout(timeout, async { + loop { + state = query_procedure_by_sql(instance, pid).await; + if state == r#"{"status":"Done"}"# { + break; + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("migration {pid} timed out, last state: {state}")); +} + +/// Returns the new leader of this region once the route has switched away from the source. +pub async fn wait_for_region_leader_change( + routes: &TableRouteManager, + region: RegionId, + source: DatanodeId, + timeout: Duration, +) -> DatanodeId { + tokio::time::timeout(timeout, async { + loop { + let (_, route) = routes + .get_physical_table_route(region.table_id()) + .await + .unwrap(); + if let Some(leader) = route + .region_routes + .iter() + .find(|r| r.region.id == region) + .and_then(|r| r.leader_peer.as_ref()) + && leader.id != source + { + return leader.id; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("region {region} did not move away from datanode {source}")) +} + +async fn query_procedure_by_sql(instance: &Arc, pid: &str) -> String { + let OutputData::RecordBatches(recordbatches) = + execute_sql(instance, &format!("admin procedure_state('{pid}')")) + .await + .data + else { + unreachable!(); + }; + + let record_batch = &recordbatches.take()[0]; + let column = record_batch.column(0); + let column = column.as_string::(); + column.value(0).to_string() +} diff --git a/tests-integration/src/cluster/partition.rs b/tests-integration/src/cluster/partition.rs new file mode 100644 index 00000000000..e113b7f8b2f --- /dev/null +++ b/tests-integration/src/cluster/partition.rs @@ -0,0 +1,184 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; + +use common_test_util::recordbatch::check_output_stream; +use frontend::instance::Instance; + +use crate::test_util::execute_sql; + +/// Returns the partition metadata query used by cluster integration tests. +pub fn query_partitions_sql(table_name: &str) -> String { + // We query information_schema.partitions to assert repartition results across engines, + // rather than relying on SHOW CREATE TABLE formatting differences. + format!( + "\ +SELECT table_catalog, table_schema, table_name, partition_name, partition_expression, \ +partition_description, greptime_partition_id, partition_ordinal_position \ +FROM information_schema.partitions \ +WHERE table_name = '{}' \ +ORDER BY partition_ordinal_position;", + table_name + ) +} + +/// Creates a Mito table with three partitions on `id`. +pub async fn create_on_columns_test_table(instance: &Arc, table_name: &str) { + let sql = format!( + r#" + CREATE TABLE `{table_name}`( + `id` INT, + `city` STRING, + `ts` TIMESTAMP TIME INDEX, + PRIMARY KEY(`id`, `city`) + ) PARTITION ON COLUMNS (`id`) ( + `id` < 10, + `id` >= 10 AND `id` < 20, + `id` >= 20 + ) ENGINE = mito; + "# + ); + execute_sql(instance, &sql).await; +} + +/// Runs a synchronous partition ALTER and verifies both existing rows and subsequent writes. +pub async fn check_partition_column_change( + instance: &Arc, + table_name: &str, + alter_sql: &str, +) { + create_on_columns_test_table(instance, table_name).await; + insert_on_columns_old_rows(instance, table_name).await; + execute_sql(instance, alter_sql).await; + + let result = execute_sql( + instance, + &format!("SELECT * FROM `{table_name}` ORDER BY `id`, `city`"), + ) + .await; + let expected = "\ ++----+----------+---------------------+ +| id | city | ts | ++----+----------+---------------------+ +| 1 | London | 2022-01-01T00:00:00 | +| 5 | New York | 2022-01-01T00:00:00 | +| 10 | Paris | 2022-01-01T00:00:00 | +| 15 | Tokyo | 2022-01-01T00:00:00 | +| 20 | Beijing | 2022-01-01T00:00:00 | ++----+----------+---------------------+"; + check_output_stream(result.data, expected).await; + + let sql = format!( + r#" + INSERT INTO `{table_name}` VALUES + (2, 'Amsterdam', '2022-01-02 00:00:00'), + (7, 'Zurich', '2022-01-02 00:00:00'), + (12, 'Berlin', '2022-01-02 00:00:00'); + "# + ); + execute_sql(instance, &sql).await; + + assert_partition_column_rows(instance, table_name).await; +} + +/// Checks every pre- and post-repartition row, including rows on the split boundary. +pub async fn assert_partition_column_rows(instance: &Arc, table_name: &str) { + assert_partition_expression(instance, table_name, "id, city").await; + let result = execute_sql( + instance, + &format!("SELECT * FROM `{table_name}` ORDER BY `id`, `city`"), + ) + .await; + let expected = "\ ++----+-----------+---------------------+ +| id | city | ts | ++----+-----------+---------------------+ +| 1 | London | 2022-01-01T00:00:00 | +| 2 | Amsterdam | 2022-01-02T00:00:00 | +| 5 | New York | 2022-01-01T00:00:00 | +| 7 | Zurich | 2022-01-02T00:00:00 | +| 10 | Paris | 2022-01-01T00:00:00 | +| 12 | Berlin | 2022-01-02T00:00:00 | +| 15 | Tokyo | 2022-01-01T00:00:00 | +| 20 | Beijing | 2022-01-01T00:00:00 | ++----+-----------+---------------------+"; + check_output_stream(result.data, expected).await; +} + +/// Builds a REPARTITION statement that splits the lowest ID range by city. +pub fn repartition_on_columns_sql(table_name: &str) -> String { + format!( + r#" + ALTER TABLE `{table_name}` REPARTITION ( + `id` < 10 + ) ON COLUMNS (`id`, `city`) INTO ( + `id` < 10 AND `city` < 'M', + `id` < 10 AND `city` >= 'M' + ); + "# + ) +} + +/// Builds a SPLIT PARTITION statement that splits the lowest ID range by city. +pub fn split_on_columns_sql(table_name: &str) -> String { + format!( + r#" + ALTER TABLE `{table_name}` SPLIT PARTITION ( + `id` < 10 + ) ON COLUMNS (`id`, `city`) INTO ( + `id` < 10 AND `city` < 'M', + `id` < 10 AND `city` >= 'M' + ); + "# + ) +} + +/// Checks the partition expression reported for every partition of the table. +pub async fn assert_partition_expression( + instance: &Arc, + table_name: &str, + expected_partition_expression: &str, +) { + let result = execute_sql( + instance, + &format!( + "SELECT DISTINCT partition_expression FROM information_schema.partitions WHERE table_name = '{table_name}' ORDER BY partition_expression" + ), + ) + .await; + let expected = format!( + "\ ++----------------------+ +| partition_expression | ++----------------------+ +| {expected_partition_expression:<20} | ++----------------------+" + ); + check_output_stream(result.data, &expected).await; +} + +async fn insert_on_columns_old_rows(instance: &Arc, table_name: &str) { + let sql = format!( + r#" + INSERT INTO `{table_name}` VALUES + (1, 'London', '2022-01-01 00:00:00'), + (5, 'New York', '2022-01-01 00:00:00'), + (10, 'Paris', '2022-01-01 00:00:00'), + (15, 'Tokyo', '2022-01-01 00:00:00'), + (20, 'Beijing', '2022-01-01 00:00:00'); + "# + ); + execute_sql(instance, &sql).await; +} diff --git a/tests-integration/src/cluster/registration.rs b/tests-integration/src/cluster/registration.rs new file mode 100644 index 00000000000..cf0c37ada59 --- /dev/null +++ b/tests-integration/src/cluster/registration.rs @@ -0,0 +1,119 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::time::Duration; + +use common_time::util::DefaultSystemTimer; +use meta_srv::discovery::node_info::NodeInfoAccessor; +use meta_srv::discovery::utils::alive_datanode_infos; + +/// Waits until metasrv reports the expected datanode count. The timeout includes discovery queries. +pub async fn wait_for_datanode_registration( + discovery: &impl NodeInfoAccessor, + expected: usize, + timeout: Duration, +) { + let mut last_ids = None; + let result = tokio::time::timeout(timeout, async { + loop { + let nodes = alive_datanode_infos( + &DefaultSystemTimer, + discovery, + Duration::from_secs(u64::MAX), + None, + ) + .await + .unwrap_or_else(|err| { + panic!("Failed to query metasrv while waiting for {expected} datanodes to register: {err}") + }); + if nodes.len() == expected { + return; + } + last_ids = Some(nodes.into_iter().map(|node| node.peer.id).collect::>()); + tokio::time::sleep(Duration::from_millis(100)).await; + } + }) + .await; + if result.is_err() { + let observation = match last_ids { + Some(mut ids) => { + ids.sort_unstable(); + format!("Last observed {} datanodes (IDs: {ids:?}).", ids.len()) + } + None => "No discovery query completed.".to_string(), + }; + panic!( + "Timed out after {timeout:?} waiting for {expected} datanodes to register with metasrv. {observation}" + ); + } +} + +#[cfg(test)] +mod tests { + use common_meta::cluster::NodeInfo; + use meta_srv::discovery::node_info::NodeInfoType; + use meta_srv::error::{Result, UnexpectedSnafu}; + + use super::*; + + enum Discovery { + Empty, + Slow, + Failed, + } + + #[async_trait::async_trait] + impl NodeInfoAccessor for Discovery { + async fn node_infos(&self, _: NodeInfoType) -> Result> { + match self { + Self::Empty => Ok(Vec::new()), + Self::Slow => { + tokio::time::sleep(Duration::from_secs(1)).await; + Ok(Vec::new()) + } + Self::Failed => UnexpectedSnafu { + violated: "discovery failed", + } + .fail(), + } + } + } + + #[tokio::test] + #[should_panic( + expected = "Timed out after 20ms waiting for 2 datanodes to register with metasrv. Last observed 0 datanodes (IDs: [])." + )] + async fn test_registration_timeout_reports_last_observation() { + wait_for_datanode_registration(&Discovery::Empty, 2, Duration::from_millis(20)).await; + } + + #[tokio::test(start_paused = true)] + async fn test_registration_allows_slow_query_within_timeout() { + wait_for_datanode_registration(&Discovery::Slow, 0, Duration::from_secs(2)).await; + } + + #[tokio::test(start_paused = true)] + #[should_panic(expected = "No discovery query completed.")] + async fn test_registration_timeout_includes_pending_query() { + wait_for_datanode_registration(&Discovery::Slow, 0, Duration::from_millis(20)).await; + } + + #[tokio::test] + #[should_panic( + expected = "Failed to query metasrv while waiting for 2 datanodes to register: Unexpected, violated: discovery failed" + )] + async fn test_registration_reports_query_error() { + wait_for_datanode_registration(&Discovery::Failed, 2, Duration::from_secs(10)).await; + } +} diff --git a/tests-integration/src/cluster/transport.rs b/tests-integration/src/cluster/transport.rs new file mode 100644 index 00000000000..617007fb2d5 --- /dev/null +++ b/tests-integration/src/cluster/transport.rs @@ -0,0 +1,423 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::HashMap; +use std::future::Future; +use std::ops::{Deref, DerefMut}; +use std::pin::Pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; + +use api::v1::health_check_server::HealthCheckServer; +use api::v1::region::region_server::RegionServer; +use arrow_flight::flight_service_server::FlightServiceServer; +use client::Client; +use client::client_manager::NodeClients; +use common_grpc::channel_manager::ChannelManager; +use common_meta::DatanodeId; +use common_meta::peer::Peer; +use common_runtime::Builder as RuntimeBuilder; +use common_runtime::runtime::BuilderBuild; +use datanode::config::DatanodeOptions; +use datanode::datanode::Datanode; +use hyper_util::rt::TokioIo; +use servers::grpc::HealthCheckHandler; +use servers::grpc::flight::FlightCraftWrapper; +use servers::grpc::region_server::RegionServerRequestHandler; +use tokio::io::{AsyncRead, AsyncWrite}; +use tonic::codec::CompressionEncoding; +use tonic::transport::Server; +use tonic::transport::server::Connected; +use tower::{Layer, Service, service_fn}; + +use crate::test_util; + +/// Flight `DoGet` requests sent to a datanode over its network address (see +/// [`crate::cluster::GreptimeDbClusterBuilder::with_real_datanode_grpc_addr`]). In-process duplex requests are not +/// counted. Request totals are per datanode; active and peak counts are shared by all datanode +/// listeners in the cluster. By default, the frontend uses duplex, but it can opt into TCP with +/// [`crate::cluster::GreptimeDbClusterBuilder::with_frontend_real_datanode_grpc`]. +#[derive(Debug, Default)] +pub struct DatanodeRpcStats { + do_get_requests: AtomicUsize, + active: Arc>, +} + +#[derive(Debug, Default)] +pub(crate) struct ActiveDoGet { + current: usize, + peak: usize, +} + +impl ActiveDoGet { + pub(crate) fn current(&self) -> usize { + self.current + } + + pub(crate) fn peak(&self) -> usize { + self.peak + } + + pub(crate) fn reset_peak(&mut self) { + self.peak = self.current; + } +} + +impl DatanodeRpcStats { + pub(crate) fn with_active(active: Arc>) -> Self { + Self { + active, + ..Default::default() + } + } + + /// The total number of Flight `DoGet` requests received over TCP. + pub fn requests(&self) -> usize { + self.do_get_requests.load(Ordering::Relaxed) + } + + /// The cluster-wide number of TCP `DoGet` calls with a pending response or live response body. + pub fn active(&self) -> usize { + self.active.lock().unwrap().current() + } + + /// The cluster-wide peak number of concurrently active TCP `DoGet` calls since the last reset. + pub fn peak_active(&self) -> usize { + self.active.lock().unwrap().peak() + } + + /// Reset the peak to the number of currently active calls. + pub fn reset_peak_active(&self) { + self.active.lock().unwrap().reset_peak(); + } + + fn start(self: &Arc) -> DoGetGuard { + self.do_get_requests.fetch_add(1, Ordering::Relaxed); + let mut active = self.active.lock().unwrap(); + active.current += 1; + active.peak = active.peak.max(active.current); + DoGetGuard(self.clone()) + } +} + +/// Keeps a `DoGet` active until its response body is dropped, including cancellation and errors. +struct DoGetGuard(Arc); + +impl Drop for DoGetGuard { + fn drop(&mut self) { + self.0.active.lock().unwrap().current -= 1; + } +} + +pub(crate) async fn build_datanode_clients( + clients: Arc, + instances: &HashMap, + options: &[DatanodeOptions], + rpc_stats: &HashMap>, +) { + for opts in options { + let datanode_id = opts.node_id.unwrap(); + let instance = &instances[&datanode_id]; + let (addr, client) = create_datanode_client( + instance, + &opts.grpc.server_addr, + rpc_stats.get(&datanode_id).cloned(), + ) + .await; + clients + .insert_client(Peer::new(datanode_id, addr), client) + .await; + } +} + +/// Runs a gRPC server that serves the region server of `datanode` over `incoming` until the +/// cluster is dropped. +fn serve_datanode_region_server( + datanode: &Datanode, + incoming: I, + rpc_stats: Option>, +) where + I: futures::Stream> + Send + 'static, + IO: AsyncRead + AsyncWrite + Connected + Unpin + Send + 'static, +{ + let runtime = RuntimeBuilder::default() + .worker_threads(2) + .thread_name("grpc-handlers") + .build() + .unwrap(); + + let flight_handler = FlightCraftWrapper(datanode.region_server()); + let region_server_handler = + RegionServerRequestHandler::new(Arc::new(datanode.region_server()), runtime); + + tokio::spawn(async move { + Server::builder() + .layer(CountRequestsLayer { rpc_stats }) + .add_service( + FlightServiceServer::new(flight_handler) + .accept_compressed(CompressionEncoding::Gzip) + .accept_compressed(CompressionEncoding::Zstd) + .send_compressed(CompressionEncoding::Gzip) + .send_compressed(CompressionEncoding::Zstd), + ) + .add_service( + RegionServer::new(region_server_handler) + .accept_compressed(CompressionEncoding::Gzip) + .accept_compressed(CompressionEncoding::Zstd) + .send_compressed(CompressionEncoding::Gzip) + .send_compressed(CompressionEncoding::Zstd), + ) + .add_service(HealthCheckServer::new(HealthCheckHandler)) + .serve_with_incoming(incoming) + .await + }); +} + +/// Serves the region server of `datanode` and returns the address and the client of the address. +/// +/// The returned client is always an in-process duplex client, keeping its traffic out of +/// `rpc_stats`. The frontend can instead use separate TCP clients when opted in. +/// +/// [`test_util::PEER_PLACEHOLDER_ADDR`] is not a real address, so it cannot be served over the +/// network at all. Any other address is a real one: the region server is additionally served on +/// its local TCP port, and `rpc_stats` counts requests reaching that port. +pub(crate) async fn create_datanode_client( + datanode: &Datanode, + addr: &str, + rpc_stats: Option>, +) -> (String, Client) { + let (client, server) = tokio::io::duplex(1024); + serve_datanode_region_server( + datanode, + futures::stream::iter(vec![Ok::<_, std::io::Error>(server)]), + None, + ); + + if addr != test_util::PEER_PLACEHOLDER_ADDR { + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener); + serve_datanode_region_server(datanode, incoming, rpc_stats); + } + + let mut client = Some(client); + let channel_manager = ChannelManager::new(); + channel_manager + .reset_with_connector( + addr, + service_fn(move |_| { + let client = client.take(); + + async move { + client + .map(TokioIo::new) + .ok_or_else(|| std::io::Error::other("Client already taken")) + } + }), + ) + .unwrap(); + + ( + addr.to_string(), + // The mock connector pool lives on this single manager, so both lanes + // intentionally share it (same semantics as the legacy constructor). + Client::with_query_and_control_managers(channel_manager.clone(), channel_manager, [addr]), + ) +} + +/// Counts Flight `DoGet` requests received by the wrapped server. +#[derive(Clone)] +struct CountRequests { + inner: S, + rpc_stats: Option>, +} + +impl Service> for CountRequests +where + S: Service, Response = http::Response>, + S::Future: Send + 'static, + S::Error: Send + 'static, +{ + type Response = http::Response; + type Error = S::Error; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, request: http::Request) -> Self::Future { + let guard = if request.uri().path() == "/arrow.flight.protocol.FlightService/DoGet" { + self.rpc_stats.as_ref().map(DatanodeRpcStats::start) + } else { + None + }; + let future = self.inner.call(request); + + Box::pin(async move { + let response = future.await?; + Ok(response.map(|body| match guard { + Some(guard) => { + // The pinned body delegates HTTP frames (including gRPC trailers) while the + // pointer owns the guard until the body is dropped. + tonic::body::Body::new(Pin::new(GuardedBody { + body: Box::new(body), + _guard: guard, + })) + } + None => body, + })) + }) + } +} + +// Dereferencing to the inner body lets tonic wrap it while keeping the guard alive until the +// streaming body is completed and dropped, or the caller cancels the response. +struct GuardedBody { + body: Box, + _guard: DoGetGuard, +} + +impl Deref for GuardedBody { + type Target = tonic::body::Body; + + fn deref(&self) -> &Self::Target { + &self.body + } +} + +impl DerefMut for GuardedBody { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.body + } +} + +#[derive(Clone)] +struct CountRequestsLayer { + rpc_stats: Option>, +} + +impl Layer for CountRequestsLayer { + type Service = CountRequests; + + fn layer(&self, inner: S) -> Self::Service { + CountRequests { + inner, + rpc_stats: self.rpc_stats.clone(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_do_get_stats_follow_response_body_lifetime() { + let stats = Arc::new(DatanodeRpcStats::default()); + let mut service = CountRequests { + inner: service_fn(|_: http::Request<()>| async { + let stream = futures::stream::once(async { + Ok::<_, std::io::Error>(axum::body::Bytes::from_static(b"data")) + }); + let body = tonic::body::Body::new(axum::body::Body::from_stream(stream)); + Ok::<_, std::convert::Infallible>(http::Response::new(body)) + }), + rpc_stats: Some(stats.clone()), + }; + let request = || { + http::Request::builder() + .uri("/arrow.flight.protocol.FlightService/DoGet") + .body(()) + .unwrap() + }; + + let first = service.call(request()).await.unwrap(); + let other_stats = Arc::new(DatanodeRpcStats { + active: stats.active.clone(), + ..Default::default() + }); + service.rpc_stats = Some(other_stats.clone()); + let second = service.call(request()).await.unwrap(); + assert_eq!( + ( + stats.requests(), + other_stats.requests(), + stats.active(), + stats.peak_active() + ), + (1, 1, 2, 2) + ); + assert_eq!((other_stats.active(), other_stats.peak_active()), (2, 2)); + stats.reset_peak_active(); + assert_eq!(stats.peak_active(), 2); + + // Completing one body and dropping another both release their guards. + let body = axum::body::Body::new(first.into_body()); + assert_eq!( + axum::body::to_bytes(body, usize::MAX).await.unwrap(), + "data" + ); + assert_eq!(stats.active(), 1); + stats.reset_peak_active(); + assert_eq!(stats.peak_active(), 1); + drop(second); + assert_eq!(stats.active(), 0); + stats.reset_peak_active(); + assert_eq!(stats.peak_active(), 0); + + let other = http::Request::builder().uri("/other").body(()).unwrap(); + let other = service.call(other).await.unwrap(); + assert_eq!( + (stats.requests(), other_stats.requests(), stats.active()), + (1, 1, 0) + ); + drop(other); + } + + #[tokio::test] + async fn test_do_get_stats_release_on_future_cancel_or_error() { + let stats = Arc::new(DatanodeRpcStats::default()); + let request = || { + http::Request::builder() + .uri("/arrow.flight.protocol.FlightService/DoGet") + .body(()) + .unwrap() + }; + let mut pending = CountRequests { + inner: service_fn(|_: http::Request<()>| { + std::future::pending::< + Result, std::convert::Infallible>, + >() + }), + rpc_stats: Some(stats.clone()), + }; + let future = pending.call(request()); + assert_eq!(stats.active(), 1); + drop(future); + assert_eq!(stats.active(), 0); + + let mut failing = CountRequests { + inner: service_fn(|_: http::Request<()>| async { + Err::, _>(std::io::Error::other("failed")) + }), + rpc_stats: Some(stats.clone()), + }; + assert!(failing.call(request()).await.is_err()); + assert_eq!( + (stats.requests(), stats.active(), stats.peak_active()), + (2, 0, 1) + ); + } +} diff --git a/tests-integration/src/test_util.rs b/tests-integration/src/test_util.rs index 1f427c2689a..94958116659 100644 --- a/tests-integration/src/test_util.rs +++ b/tests-integration/src/test_util.rs @@ -656,20 +656,6 @@ async fn setup_standalone_instance_with_plugins( .await } -async fn setup_standalone_instance_with_plugins_and_slow_query_threshold( - test_name: &str, - store_type: StorageType, - plugins: Plugins, - slow_query_threshold: std::time::Duration, -) -> GreptimeDbStandalone { - GreptimeDbStandaloneBuilder::new(test_name) - .with_default_store_type(store_type) - .with_plugin(plugins) - .with_slow_query_threshold(slow_query_threshold) - .build() - .await -} - pub async fn setup_test_http_app(store_type: StorageType, name: &str) -> (Router, TestGuard) { let instance = setup_standalone_instance(name, store_type).await; @@ -1091,48 +1077,11 @@ pub async fn setup_mysql_server_with_slow_query_threshold( name: &str, slow_query_threshold: std::time::Duration, ) -> (TestGuard, Arc>) { - let plugins = Plugins::new(); - let instance = setup_standalone_instance_with_plugins_and_slow_query_threshold( - name, - store_type, - plugins, - slow_query_threshold, - ) - .await; - - let runtime = RuntimeBuilder::default() - .worker_threads(2) - .thread_name("mysql-runtime") - .build() - .unwrap(); - - let fe_mysql_addr = format!("127.0.0.1:{}", ports::get_port()); - - let fe_instance_ref = instance.fe_instance().clone(); - let opts = MysqlOptions { - addr: fe_mysql_addr.clone(), - ..Default::default() - }; - let mut mysql_server = MysqlServer::create_server( - runtime, - Arc::new(MysqlSpawnRef::new(fe_instance_ref, None)), - Arc::new(MysqlSpawnConfig::new( - false, - Arc::new( - ReloadableTlsServerConfig::try_new(opts.tls.clone()) - .expect("Failed to load certificates and keys"), - ), - 0, - opts.reject_no_database.unwrap_or(false), - opts.prepared_stmt_cache_size, - )), - None, - ); - - mysql_server - .start(fe_mysql_addr.parse::().unwrap()) - .await - .unwrap(); + let instance = + setup_standalone_instance_with_slow_query_threshold(name, store_type, slow_query_threshold) + .await; + let mysql_server = + setup_mysql_server_for_frontend_instance(instance.fe_instance().clone(), None).await; (instance.guard, Arc::new(mysql_server)) } @@ -1212,51 +1161,8 @@ pub async fn setup_pg_server_with_slow_query_threshold( let instance = setup_standalone_instance_with_slow_query_threshold(name, store_type, slow_query_threshold) .await; - - let runtime = RuntimeBuilder::default() - .worker_threads(2) - .thread_name("pg-runtime") - .build() - .unwrap(); - - let fe_pg_addr = format!("127.0.0.1:{}", ports::get_port()); - - let fe_instance_ref = instance.fe_instance().clone(); - let opts = PostgresOptions { - addr: fe_pg_addr.clone(), - ..Default::default() - }; - let tls_server_config = Arc::new( - ReloadableTlsServerConfig::try_new(opts.tls.clone()) - .expect("Failed to load certificates and keys"), - ); - - let mut pg_server = Box::new( - PostgresServer::new( - fe_instance_ref.clone(), - fe_instance_ref.clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - None, - None, - ) - .with_influxdb_handler(fe_instance_ref.clone()) - .with_otlp_handler(fe_instance_ref.clone(), true) - .with_prom_remote_write( - fe_instance_ref.clone(), - Some(fe_instance_ref.clone()), - true, - Default::default(), - None, - ), - ); - - pg_server - .start(fe_pg_addr.parse::().unwrap()) - .await - .unwrap(); + let pg_server = + setup_pg_server_for_frontend_instance(instance.fe_instance().clone(), None).await; (instance.guard, Arc::new(pg_server)) } @@ -1370,49 +1276,8 @@ pub async fn setup_pg_server_with_prom_native_histogram( .build(); let app = http_server.build(http_server.make_app()).unwrap(); - // Postgres server on the same instance. - let runtime = RuntimeBuilder::default() - .worker_threads(2) - .thread_name("pg-runtime") - .build() - .unwrap(); - - let fe_pg_addr = format!("127.0.0.1:{}", ports::get_port()); - let opts = PostgresOptions { - addr: fe_pg_addr.clone(), - ..Default::default() - }; - let tls_server_config = Arc::new( - ReloadableTlsServerConfig::try_new(opts.tls.clone()) - .expect("Failed to load certificates and keys"), - ); - - let mut pg_server = Box::new( - PostgresServer::new( - instance.fe_instance().clone(), - instance.fe_instance().clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - None, - None, - ) - .with_influxdb_handler(instance.fe_instance().clone()) - .with_otlp_handler(instance.fe_instance().clone(), true) - .with_prom_remote_write( - instance.fe_instance().clone(), - Some(instance.fe_instance().clone()), - true, - Default::default(), - None, - ), - ); - - pg_server - .start(fe_pg_addr.parse::().unwrap()) - .await - .unwrap(); + let pg_server = + setup_pg_server_for_frontend_instance(instance.fe_instance().clone(), None).await; (instance.guard, app, Arc::new(pg_server)) } diff --git a/tests-integration/src/tests/gc.rs b/tests-integration/src/tests/gc.rs index 20242223422..4f047fb107e 100644 --- a/tests-integration/src/tests/gc.rs +++ b/tests-integration/src/tests/gc.rs @@ -22,6 +22,7 @@ use common_telemetry::info; use common_test_util::recordbatch::check_output_stream; use common_test_util::temp_dir::create_temp_dir; use common_wal::config::DatanodeWalConfig; +use frontend::instance::Instance; use futures::TryStreamExt as _; use itertools::Itertools; use meta_srv::gc::{BatchGcProcedure, GcSchedulerOptions, Region2Peers}; @@ -132,43 +133,8 @@ async fn test_gc_basic(store_type: &StorageType) { let instance = test_context.frontend(); let metasrv = test_context.metasrv(); - // Step 1: Create table with append_mode to easily generate multiple files - let create_table_sql = r#" - CREATE TABLE test_gc_table ( - ts TIMESTAMP TIME INDEX, - val DOUBLE, - host STRING - ) WITH (append_mode = 'true') - "#; - execute_sql(&instance, create_table_sql).await; + create_table_with_gc_garbage(&test_context, "test_gc_table").await; - // Step 2: Generate SST files by inserting data and flushing multiple times - for i in 0..4 { - let insert_sql = format!( - r#" - INSERT INTO test_gc_table (ts, val, host) VALUES - ('2023-01-0{} 10:00:00', {}, 'host{}'), - ('2023-01-0{} 11:00:00', {}, 'host{}'), - ('2023-01-0{} 12:00:00', {}, 'host{}') - "#, - i + 1, - 10.0 + i as f64, - i, - i + 1, - 20.0 + i as f64, - i, - i + 1, - 30.0 + i as f64, - i - ); - execute_sql(&instance, &insert_sql).await; - - // Flush the table to create SST files - let flush_sql = "ADMIN FLUSH_TABLE('test_gc_table')"; - execute_sql(&instance, flush_sql).await; - } - - // Step 3: Get table information let table = instance .catalog_manager() .table("greptime", "public", "test_gc_table", None) @@ -177,34 +143,9 @@ async fn test_gc_basic(store_type: &StorageType) { .unwrap(); let table_id = table.table_info().table_id(); - // List SST files before compaction (for verification) - let sst_files_before_compaction = list_sst_files(&test_context).await; - info!( - "SST files before compaction: {:?}", - sst_files_before_compaction - ); - assert_eq!(sst_files_before_compaction.len(), 4); // 4 files from 4 flushes - - // Step 4: Trigger compaction to create garbage SST files - let compact_sql = "ADMIN COMPACT_TABLE('test_gc_table')"; - execute_sql(&instance, compact_sql).await; - - // Wait for compaction to complete - tokio::time::sleep(Duration::from_secs(2)).await; - - // List SST files after compaction (should have both old and new files) - let sst_files_after_compaction = list_sst_files(&test_context).await; - info!( - "SST files after compaction: {:?}", - sst_files_after_compaction - ); - assert_eq!(sst_files_after_compaction.len(), 5); // 4 old + 1 new - - // Step 5: Get table route information for GC procedure let (_region_routes, regions) = get_table_route(metasrv.table_metadata_manager(), table_id).await; - // Step 6: Create and execute BatchGcProcedure let procedure = BatchGcProcedure::new( metasrv.mailbox().clone(), metasrv.table_metadata_manager().clone(), @@ -229,14 +170,26 @@ async fn test_gc_basic(store_type: &StorageType) { // Wait for the procedure to complete wait_procedure(metasrv.procedure_manager(), procedure_id).await; - // Step 7: Verify GC results - let sst_files_after_gc = list_sst_files(&test_context).await; - info!("SST files after GC: {:?}", sst_files_after_gc); - assert_eq!(sst_files_after_gc.len(), 1); // Only the compacted file should remain after gc + assert_gc_kept_compacted_rows(&test_context, "test_gc_table").await; +} - // Verify that data is still accessible - let count_sql = "SELECT COUNT(*) FROM test_gc_table"; - let count_output = execute_sql(&instance, count_sql).await; +/// Creates `table` with four flushed SSTs and compacts them, leaving those four as garbage. +pub(crate) async fn create_table_with_gc_garbage(test_context: &TestContext, table: &str) { + let instance = test_context.frontend(); + create_append_table(&instance, table, None).await; + insert_and_flush(&instance, table, 4).await; + assert_eq!(list_sst_files(test_context).await.len(), 4); + + execute_sql(&instance, &format!("ADMIN COMPACT_TABLE('{table}')")).await; + assert_eq!(list_sst_files(test_context).await.len(), 5); +} + +/// Asserts that GC kept only the compacted SST of [create_table_with_gc_garbage] and its rows. +pub(crate) async fn assert_gc_kept_compacted_rows(test_context: &TestContext, table: &str) { + assert_eq!(list_sst_files(test_context).await.len(), 1); + + let instance = test_context.frontend(); + let output = execute_sql(&instance, &format!("SELECT COUNT(*) FROM {table}")).await; let expected = r#" +----------+ | count(*) | @@ -244,10 +197,9 @@ async fn test_gc_basic(store_type: &StorageType) { | 12 | +----------+"# .trim(); - check_output_stream(count_output.data, expected).await; + check_output_stream(output.data, expected).await; - let select_sql = "SELECT * FROM test_gc_table ORDER BY ts"; - let select_output = execute_sql(&instance, select_sql).await; + let output = execute_sql(&instance, &format!("SELECT * FROM {table} ORDER BY ts")).await; let expected = r#" +---------------------+------+-------+ | ts | val | host | @@ -266,9 +218,48 @@ async fn test_gc_basic(store_type: &StorageType) { | 2023-01-04T12:00:00 | 33.0 | host3 | +---------------------+------+-------+"# .trim(); - check_output_stream(select_output.data, expected).await; + check_output_stream(output.data, expected).await; +} - // TODO: Add more specific assertions once we have proper file system access - // For now, the test passes if the procedure executes without errors - info!("GC test completed successfully"); +pub(crate) async fn create_append_table( + instance: &Arc, + table_name: &str, + partition_clause: Option<&str>, +) { + let partition_clause = partition_clause.unwrap_or(""); + let create_table_sql = format!( + "\ + CREATE TABLE {table_name} (\ + ts TIMESTAMP TIME INDEX,\ + val DOUBLE,\ + host STRING\ + ) {partition_clause} WITH (append_mode = 'true')\ + " + ); + execute_sql(instance, &create_table_sql).await; +} + +pub(crate) async fn insert_and_flush(instance: &Arc, table_name: &str, rounds: usize) { + for i in 0..rounds { + let insert_sql = format!( + "\ + INSERT INTO {table_name} (ts, val, host) VALUES\ + ('2023-01-0{} 10:00:00', {}, 'host{}'),\ + ('2023-01-0{} 11:00:00', {}, 'host{}'),\ + ('2023-01-0{} 12:00:00', {}, 'host{}')\ + ", + i + 1, + 10.0 + i as f64, + i, + i + 1, + 20.0 + i as f64, + i, + i + 1, + 30.0 + i as f64, + i + ); + execute_sql(instance, &insert_sql).await; + let flush_sql = format!("ADMIN FLUSH_TABLE('{table_name}')"); + execute_sql(instance, &flush_sql).await; + } } diff --git a/tests-integration/src/tests/gc/admin.rs b/tests-integration/src/tests/gc/admin.rs index b9e08392f50..34f5c6a40bb 100644 --- a/tests-integration/src/tests/gc/admin.rs +++ b/tests-integration/src/tests/gc/admin.rs @@ -18,12 +18,14 @@ use client::OutputData; use common_meta::key::table_repart::TableRepartValue; use common_recordbatch::RecordBatches; use common_telemetry::info; -use common_test_util::recordbatch::check_output_stream; use datatypes::arrow::array::{Array, AsArray}; use datatypes::arrow::datatypes::UInt64Type; use store_api::storage::RegionId; -use super::{distributed_with_gc, list_sst_files}; +use super::{ + assert_gc_kept_compacted_rows, create_append_table, create_table_with_gc_garbage, + distributed_with_gc, insert_and_flush, list_sst_files, +}; use crate::test_util::{StorageType, execute_sql, try_execute_sql}; #[tokio::test] @@ -43,105 +45,13 @@ async fn test_admin_gc_table(store_type: &StorageType) { let (test_context, _guard) = distributed_with_gc(store_type).await; let instance = test_context.frontend(); - // Step 1: Create table with append_mode to easily generate multiple files - let create_table_sql = r#" - CREATE TABLE test_admin_gc_table ( - ts TIMESTAMP TIME INDEX, - val DOUBLE, - host STRING - ) WITH (append_mode = 'true') - "#; - execute_sql(&instance, create_table_sql).await; + create_table_with_gc_garbage(&test_context, "test_admin_gc_table").await; - // Step 2: Generate SST files by inserting data and flushing multiple times - for i in 0..4 { - let insert_sql = format!( - r#" - INSERT INTO test_admin_gc_table (ts, val, host) VALUES - ('2023-01-0{} 10:00:00', {}, 'host{}'), - ('2023-01-0{} 11:00:00', {}, 'host{}'), - ('2023-01-0{} 12:00:00', {}, 'host{}') - "#, - i + 1, - 10.0 + i as f64, - i, - i + 1, - 20.0 + i as f64, - i, - i + 1, - 30.0 + i as f64, - i - ); - execute_sql(&instance, &insert_sql).await; - - // Flush the table to create SST files - let flush_sql = "ADMIN FLUSH_TABLE('test_admin_gc_table')"; - execute_sql(&instance, flush_sql).await; - } - - // List SST files before compaction (for verification) - let sst_files_before_compaction = list_sst_files(&test_context).await; - info!( - "SST files before compaction: {:?}", - sst_files_before_compaction - ); - assert_eq!(sst_files_before_compaction.len(), 4); // 4 files from 4 flushes - - // Step 3: Trigger compaction to create garbage SST files - let compact_sql = "ADMIN COMPACT_TABLE('test_admin_gc_table')"; - execute_sql(&instance, compact_sql).await; - - // List SST files after compaction (should have both old and new files) - let sst_files_after_compaction = list_sst_files(&test_context).await; - info!( - "SST files after compaction: {:?}", - sst_files_after_compaction - ); - assert_eq!(sst_files_after_compaction.len(), 5); // 4 old + 1 new - - // Step 4: Use ADMIN GC_TABLE to clean up garbage files let gc_table_sql = "ADMIN GC_TABLE('test_admin_gc_table')"; let gc_output = execute_sql(&instance, gc_table_sql).await; info!("GC_TABLE output: {:?}", gc_output); - // Step 5: Verify GC results - let sst_files_after_gc = list_sst_files(&test_context).await; - info!("SST files after GC: {:?}", sst_files_after_gc); - assert_eq!(sst_files_after_gc.len(), 1); // Only the compacted file should remain after gc - - // Verify that data is still accessible - let count_sql = "SELECT COUNT(*) FROM test_admin_gc_table"; - let count_output = execute_sql(&instance, count_sql).await; - let expected = r#" -+----------+ -| count(*) | -+----------+ -| 12 | -+----------+"# - .trim(); - check_output_stream(count_output.data, expected).await; - - let select_sql = "SELECT * FROM test_admin_gc_table ORDER BY ts"; - let select_output = execute_sql(&instance, select_sql).await; - let expected = r#" -+---------------------+------+-------+ -| ts | val | host | -+---------------------+------+-------+ -| 2023-01-01T10:00:00 | 10.0 | host0 | -| 2023-01-01T11:00:00 | 20.0 | host0 | -| 2023-01-01T12:00:00 | 30.0 | host0 | -| 2023-01-02T10:00:00 | 11.0 | host1 | -| 2023-01-02T11:00:00 | 21.0 | host1 | -| 2023-01-02T12:00:00 | 31.0 | host1 | -| 2023-01-03T10:00:00 | 12.0 | host2 | -| 2023-01-03T11:00:00 | 22.0 | host2 | -| 2023-01-03T12:00:00 | 32.0 | host2 | -| 2023-01-04T10:00:00 | 13.0 | host3 | -| 2023-01-04T11:00:00 | 23.0 | host3 | -| 2023-01-04T12:00:00 | 33.0 | host3 | -+---------------------+------+-------+"# - .trim(); - check_output_stream(select_output.data, expected).await; + assert_gc_kept_compacted_rows(&test_context, "test_admin_gc_table").await; info!("ADMIN GC_TABLE test completed successfully"); } @@ -163,123 +73,15 @@ async fn test_admin_gc_regions(store_type: &StorageType) { let (test_context, _guard) = distributed_with_gc(store_type).await; let instance = test_context.frontend(); - // Step 1: Create table with append_mode to easily generate multiple files - let create_table_sql = r#" - CREATE TABLE test_admin_gc_regions ( - ts TIMESTAMP TIME INDEX, - val DOUBLE, - host STRING - ) WITH (append_mode = 'true') - "#; - execute_sql(&instance, create_table_sql).await; + create_table_with_gc_garbage(&test_context, "test_admin_gc_regions").await; - // Step 2: Generate SST files by inserting data and flushing multiple times - for i in 0..4 { - let insert_sql = format!( - r#" - INSERT INTO test_admin_gc_regions (ts, val, host) VALUES - ('2023-01-0{} 10:00:00', {}, 'host{}'), - ('2023-01-0{} 11:00:00', {}, 'host{}'), - ('2023-01-0{} 12:00:00', {}, 'host{}') - "#, - i + 1, - 10.0 + i as f64, - i, - i + 1, - 20.0 + i as f64, - i, - i + 1, - 30.0 + i as f64, - i - ); - execute_sql(&instance, &insert_sql).await; + let region_id = fetch_region_ids(&instance, "test_admin_gc_regions").await[0]; - // Flush the table to create SST files - let flush_sql = "ADMIN FLUSH_TABLE('test_admin_gc_regions')"; - execute_sql(&instance, flush_sql).await; - } - - // List SST files before compaction (for verification) - let sst_files_before_compaction = list_sst_files(&test_context).await; - info!( - "SST files before compaction: {:?}", - sst_files_before_compaction - ); - assert_eq!(sst_files_before_compaction.len(), 4); // 4 files from 4 flushes - - // Step 3: Trigger compaction to create garbage SST files - let compact_sql = "ADMIN COMPACT_TABLE('test_admin_gc_regions')"; - execute_sql(&instance, compact_sql).await; - - // List SST files after compaction (should have both old and new files) - let sst_files_after_compaction = list_sst_files(&test_context).await; - info!( - "SST files after compaction: {:?}", - sst_files_after_compaction - ); - assert_eq!(sst_files_after_compaction.len(), 5); // 4 old + 1 new - - // Step 4: Get region id from information_schema - let region_id_sql = "SELECT greptime_partition_id FROM information_schema.partitions WHERE table_name = 'test_admin_gc_regions' ORDER BY greptime_partition_id LIMIT 1"; - let region_output = execute_sql(&instance, region_id_sql).await; - info!("Region ID output: {:?}", region_output); - let OutputData::Stream(region_stream) = region_output.data else { - panic!("Expected stream output for region id query"); - }; - - // Extract the region id from the result - let region_id = { - let batches = RecordBatches::try_collect(region_stream).await.unwrap(); - let batch = &batches.iter().next().unwrap(); - let column = batch.column(0); - let array = column.as_primitive::(); - array.value(0) - }; - info!("Extracted region_id: {}", region_id); - - // Step 5: Use ADMIN GC_REGIONS to clean up garbage files for the specific region let gc_regions_sql = format!("ADMIN GC_REGIONS({})", region_id); let gc_output = execute_sql(&instance, &gc_regions_sql).await; info!("GC_REGIONS output: {:?}", gc_output); - // Step 6: Verify GC results - let sst_files_after_gc = list_sst_files(&test_context).await; - info!("SST files after GC: {:?}", sst_files_after_gc); - assert_eq!(sst_files_after_gc.len(), 1); // Only the compacted file should remain after gc - - // Verify that data is still accessible - let count_sql = "SELECT COUNT(*) FROM test_admin_gc_regions"; - let count_output = execute_sql(&instance, count_sql).await; - let expected = r#" -+----------+ -| count(*) | -+----------+ -| 12 | -+----------+"# - .trim(); - check_output_stream(count_output.data, expected).await; - - let select_sql = "SELECT * FROM test_admin_gc_regions ORDER BY ts"; - let select_output = execute_sql(&instance, select_sql).await; - let expected = r#" -+---------------------+------+-------+ -| ts | val | host | -+---------------------+------+-------+ -| 2023-01-01T10:00:00 | 10.0 | host0 | -| 2023-01-01T11:00:00 | 20.0 | host0 | -| 2023-01-01T12:00:00 | 30.0 | host0 | -| 2023-01-02T10:00:00 | 11.0 | host1 | -| 2023-01-02T11:00:00 | 21.0 | host1 | -| 2023-01-02T12:00:00 | 31.0 | host1 | -| 2023-01-03T10:00:00 | 12.0 | host2 | -| 2023-01-03T11:00:00 | 22.0 | host2 | -| 2023-01-03T12:00:00 | 32.0 | host2 | -| 2023-01-04T10:00:00 | 13.0 | host3 | -| 2023-01-04T11:00:00 | 23.0 | host3 | -| 2023-01-04T12:00:00 | 33.0 | host3 | -+---------------------+------+-------+"# - .trim(); - check_output_stream(select_output.data, expected).await; + assert_gc_kept_compacted_rows(&test_context, "test_admin_gc_regions").await; info!("ADMIN GC_REGIONS test completed successfully"); } @@ -321,25 +123,13 @@ async fn test_admin_gc_missing_cases(store_type: &StorageType) { let invalid_region = RegionId::new(table_id, base_region.region_number().saturating_add(100)); let invalid_region_sql = format!("ADMIN GC_REGIONS({})", invalid_region.as_u64()); let sst_before_invalid_region = list_sst_files(&test_context).await; - let invalid_region_result = try_execute_sql(&instance, &invalid_region_sql).await; - match invalid_region_result { - Ok(output) => { - let processed_regions = extract_u64_output(output.data).await; - assert_eq!(processed_regions, 0); - let sst_after_invalid_region = list_sst_files(&test_context).await; - assert_eq!( - sst_before_invalid_region.len(), - sst_after_invalid_region.len() - ); - } - Err(_) => { - let sst_after_invalid_region = list_sst_files(&test_context).await; - assert_eq!( - sst_before_invalid_region.len(), - sst_after_invalid_region.len() - ); - } + if let Ok(output) = try_execute_sql(&instance, &invalid_region_sql).await { + assert_eq!(extract_u64_output(output.data).await, 0); } + assert_eq!( + sst_before_invalid_region.len(), + list_sst_files(&test_context).await.len() + ); // Case 3: No garbage to collect (idempotent) let no_garbage_table = "test_admin_gc_no_garbage"; @@ -419,53 +209,6 @@ async fn test_admin_gc_missing_cases(store_type: &StorageType) { assert_eq!(processed_regions, 1); } -async fn create_append_table( - instance: &std::sync::Arc, - table_name: &str, - partition_clause: Option<&str>, -) { - let partition_clause = partition_clause.unwrap_or(""); - let create_table_sql = format!( - "\ - CREATE TABLE {table_name} (\ - ts TIMESTAMP TIME INDEX,\ - val DOUBLE,\ - host STRING\ - ) {partition_clause} WITH (append_mode = 'true')\ - " - ); - execute_sql(instance, &create_table_sql).await; -} - -async fn insert_and_flush( - instance: &std::sync::Arc, - table_name: &str, - rounds: usize, -) { - for i in 0..rounds { - let insert_sql = format!( - "\ - INSERT INTO {table_name} (ts, val, host) VALUES\ - ('2023-01-0{} 10:00:00', {}, 'host{}'),\ - ('2023-01-0{} 11:00:00', {}, 'host{}'),\ - ('2023-01-0{} 12:00:00', {}, 'host{}')\ - ", - i + 1, - 10.0 + i as f64, - i, - i + 1, - 20.0 + i as f64, - i, - i + 1, - 30.0 + i as f64, - i - ); - execute_sql(instance, &insert_sql).await; - let flush_sql = format!("ADMIN FLUSH_TABLE('{table_name}')"); - execute_sql(instance, &flush_sql).await; - } -} - async fn fetch_region_ids( instance: &std::sync::Arc, table_name: &str, diff --git a/tests-integration/src/tests/instance_test.rs b/tests-integration/src/tests/instance_test.rs index 8041c54e7ad..81f6c848394 100644 --- a/tests-integration/src/tests/instance_test.rs +++ b/tests-integration/src/tests/instance_test.rs @@ -1714,7 +1714,6 @@ async fn assert_query_result(instance: &Arc, sql: &str, ts: i64, host: match query_output { OutputData::Stream(s) => { let batches = util::collect(s).await.unwrap(); - // let columns = batches[0].df_recordbatch.columns(); assert_eq!(2, batches[0].num_columns()); let expected = vec![ Arc::new(StringArray::from_iter_values(vec![host])) as ArrayRef, @@ -1726,137 +1725,6 @@ async fn assert_query_result(instance: &Arc, sql: &str, ts: i64, host: } } -#[apply(both_instances_cases)] -async fn test_execute_insert(instance: Arc) { - let instance = instance.frontend(); - - // create table - assert!(matches!( - execute_sql( - &instance, - "create table demo(host string, cpu double, memory double, ts timestamp time index);", - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let output = execute_sql( - &instance, - r#"insert into demo(host, cpu, memory, ts) values - ('host1', 66.6, 1024, 1655276557000), - ('host2', 88.8, 333.3, 1655276558000) - "#, - ) - .await - .data; - assert!(matches!(output, OutputData::AffectedRows(2))); -} - -#[apply(both_instances_cases)] -async fn test_execute_insert_by_select(instance: Arc) { - let instance = instance.frontend(); - - // create table - assert!(matches!( - execute_sql( - &instance, - "create table demo1(host string, cpu double, memory double, ts timestamp time index);", - ) - .await - .data, - OutputData::AffectedRows(0) - )); - assert!(matches!( - execute_sql( - &instance, - "create table demo2(host string, cpu double, memory double, ts timestamp time index);", - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let output = execute_sql( - &instance, - r#"insert into demo1(host, cpu, memory, ts) values - ('host1', 66.6, 1024, 1655276557000), - ('host2', 88.8, 333.3, 1655276558000) - "#, - ) - .await - .data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let err = try_execute_sql(&instance, "insert into demo2(host) select * from demo1") - .await - .unwrap_err(); - assert!(matches!( - unwrap_frontend_error(&err), - Error::TableOperation { - source: OperatorError::PlanStatement { .. }, - .. - } - )); - - let err = try_execute_sql(&instance, "insert into demo2 select cpu,memory from demo1") - .await - .unwrap_err(); - assert!(matches!( - unwrap_frontend_error(&err), - Error::TableOperation { - source: OperatorError::PlanStatement { .. }, - .. - } - )); - assert!(matches!( - try_execute_sql(&instance, "insert into demo2(ts) select memory from demo1") - .await - .unwrap() - .data, - OutputData::AffectedRows(2), - )); - - let output = execute_sql(&instance, "insert into demo2 select * from demo1") - .await - .data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let output = execute_sql(&instance, "select * from demo2 order by ts") - .await - .data; - let expected = "\ -+-------+------+--------+-------------------------+ -| host | cpu | memory | ts | -+-------+------+--------+-------------------------+ -| | | | 1970-01-01T00:00:00.333 | -| | | | 1970-01-01T00:00:01.024 | -| host1 | 66.6 | 1024.0 | 2022-06-15T07:02:37 | -| host2 | 88.8 | 333.3 | 2022-06-15T07:02:38 | -+-------+------+--------+-------------------------+"; - check_output_stream(output, expected).await; -} - -#[apply(both_instances_cases)] -async fn test_execute_query(instance: Arc) { - let instance = instance.frontend(); - - let output = execute_sql(&instance, "select sum(number) from numbers limit 20") - .await - .data; - match output { - OutputData::Stream(recordbatch) => { - let numbers = util::collect(recordbatch).await.unwrap(); - assert_eq!(1, numbers[0].num_columns()); - assert_eq!(numbers[0].column(0).len(), 1); - - let expected = Arc::new(UInt64Array::from_iter_values(vec![4950_u64])) as ArrayRef; - assert_eq!(numbers[0].column(0), &expected); - } - _ => unreachable!(), - } -} - #[apply(both_instances_cases)] async fn test_execute_show_databases_tables(instance: Arc) { let instance = instance.frontend(); @@ -1946,26 +1814,6 @@ async fn test_execute_show_databases_tables(instance: Arc) { check_unordered_output_stream(output, expected).await; } -#[apply(both_instances_cases)] -async fn test_execute_create(instance: Arc) { - let instance = instance.frontend(); - - let output = execute_sql( - &instance, - r#"create table test_table( - host string, - ts timestamp, - cpu double default 0, - memory double, - TIME INDEX (ts), - PRIMARY KEY(host) - ) engine=mito;"#, - ) - .await - .data; - assert!(matches!(output, OutputData::AffectedRows(0))); -} - #[tokio::test(flavor = "multi_thread")] async fn test_distributed_local_file_access_disabled() { let instance = distributed().await.frontend(); @@ -2131,16 +1979,24 @@ async fn test_execute_external_create_with_invalid_ts(instance: Arc) { +async fn test_execute_query_external_table_parquet_csv( + instance: Arc, + #[values( + ("parquet", "/tests/data/parquet/various_type.parquet"), + ("csv", "/tests/data/csv/various_type.csv") + )] + source: (&str, &str), +) { unsafe { std::env::set_var("TZ", "UTC"); } let instance = instance.frontend(); - let format = "parquet"; - let location = find_testing_resource("/tests/data/parquet/various_type.parquet"); - let table_name = "various_type_parquet"; + let (format, path) = source; + let location = find_testing_resource(path); + let table_name = format!("various_type_{format}"); let output = execute_sql( &instance, @@ -2349,61 +2205,6 @@ async fn test_execute_query_external_table_orc_with_schema(instance: Arc) { - unsafe { - std::env::set_var("TZ", "UTC"); - } - - let instance = instance.frontend(); - let format = "csv"; - let location = find_testing_resource("/tests/data/csv/various_type.csv"); - let table_name = "various_type_csv"; - - let output = execute_sql( - &instance, - &format!( - r#"create external table {table_name} with (location='{location}', format='{format}');"#, - ), - ) - .await.data; - assert!(matches!(output, OutputData::AffectedRows(0))); - - let output = execute_sql(&instance, &format!("desc table {table_name};")) - .await - .data; - let expect = "\ -+--------------------+----------------------+-----+------+--------------------------+---------------+ -| Column | Type | Key | Null | Default | Semantic Type | -+--------------------+----------------------+-----+------+--------------------------+---------------+ -| c_int | Int64 | | YES | | FIELD | -| c_float | Float64 | | YES | | FIELD | -| c_string | Float64 | | YES | | FIELD | -| c_bool | Boolean | | YES | | FIELD | -| c_date | Date | | YES | | FIELD | -| c_datetime | TimestampSecond | | YES | | FIELD | -| greptime_timestamp | TimestampMillisecond | PRI | NO | 1970-01-01 00:00:00+0000 | TIMESTAMP | -+--------------------+----------------------+-----+------+--------------------------+---------------+"; - check_output_stream(output, expect).await; - - let output = execute_sql(&instance, &format!("select * from {table_name};")) - .await - .data; - let expect = "\ -+-------+-----------+----------+--------+------------+---------------------+---------------------+ -| c_int | c_float | c_string | c_bool | c_date | c_datetime | greptime_timestamp | -+-------+-----------+----------+--------+------------+---------------------+---------------------+ -| 1 | 1.1 | 1.11 | true | 1970-01-01 | 1970-01-01T00:00:00 | 1970-01-01T00:00:00 | -| 2 | 2.2 | 2.22 | true | 2020-11-08 | 2020-11-08T01:00:00 | 1970-01-01T00:00:00 | -| 3 | | 3.33 | true | 1969-12-31 | 1969-11-08T02:00:00 | 1970-01-01T00:00:00 | -| 4 | 4.4 | | false | | | 1970-01-01T00:00:00 | -| 5 | 6.6 | | false | 1990-01-01 | 1990-01-01T03:00:00 | 1970-01-01T00:00:00 | -| 4 | 4000000.0 | | false | | | 1970-01-01T00:00:00 | -| 4 | 4e-6 | | false | | | 1970-01-01T00:00:00 | -+-------+-----------+----------+--------+------------+---------------------+---------------------+"; - check_output_stream(output, expect).await; -} - #[tokio::test(flavor = "multi_thread")] async fn test_copy_from_inherits_skip_wal() { use crate::test_util::{MockInstanceImpl, assert_wal_delta}; @@ -3376,334 +3177,60 @@ async fn test_delete(instance: Arc) { #[apply(both_instances_cases)] async fn test_execute_copy_from_s3(instance: Arc) { - common_telemetry::init_default_ut_logging(); if let Ok(bucket) = env::var("GT_S3_BUCKET") && !bucket.is_empty() { - let instance = instance.frontend(); - - // setups - assert!(matches!(execute_sql( - &instance, - "create table demo(host string, cpu double, memory double, ts timestamp time index);", - ) - .await.data, OutputData::AffectedRows(0))); - - let output = execute_sql( - &instance, - r#"insert into demo(host, cpu, memory, ts) values - ('host1', 66.6, 1024, 1655276557000), - ('host2', 88.8, 333.3, 1655276558000) - "#, - ) - .await - .data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - // export - let root = uuid::Uuid::new_v4().to_string(); - let key_id = env::var("GT_S3_ACCESS_KEY_ID").unwrap(); - let key = env::var("GT_S3_ACCESS_KEY").unwrap(); - let region = env::var("GT_S3_REGION").unwrap(); - let mut connection = format!( "ACCESS_KEY_ID='{}',SECRET_ACCESS_KEY='{}',REGION='{}'", - key_id, key, region + env::var("GT_S3_ACCESS_KEY_ID").unwrap(), + env::var("GT_S3_ACCESS_KEY").unwrap(), + env::var("GT_S3_REGION").unwrap() ); // Honors an S3-compatible endpoint (MinIO in CI) so the test does not // fall back to resolving the bucket against real AWS. if let Ok(endpoint) = env::var("GT_S3_ENDPOINT_URL") && !endpoint.is_empty() { - connection = format!("{},ENDPOINT='{}'", connection, endpoint); - } - - let copy_to_stmt = format!( - "Copy demo TO 's3://{}/{}/export/demo.parquet' CONNECTION ({})", - bucket, root, connection - ); - - let output = execute_sql(&instance, ©_to_stmt).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - struct Test<'a> { - sql: &'a str, - table_name: &'a str, - } - let tests = [ - Test { - sql: &format!( - "Copy with_filename FROM 's3://{}/{}/export/demo.parquet'", - bucket, root - ), - table_name: "with_filename", - }, - Test { - sql: &format!("Copy with_path FROM 's3://{}/{}/export/'", bucket, root), - table_name: "with_path", - }, - Test { - sql: &format!( - "Copy with_pattern FROM 's3://{}/{}/export/' WITH (PATTERN = 'demo.*')", - bucket, root - ), - table_name: "with_pattern", - }, - ]; - - for test in tests { - // import - assert!(matches!( - execute_sql( - &instance, - &format!( - "create table {}(host string, cpu double, memory double, ts timestamp time index);", - test.table_name - ), - ) - .await - .data, - OutputData::AffectedRows(0) - )); - let sql = format!("{} CONNECTION ({})", test.sql, connection); - let output = execute_sql(&instance, &sql).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let output = execute_sql( - &instance, - &format!("select * from {} order by ts", test.table_name), - ) - .await - .data; - let expected = "\ -+-------+------+--------+---------------------+ -| host | cpu | memory | ts | -+-------+------+--------+---------------------+ -| host1 | 66.6 | 1024.0 | 2022-06-15T07:02:37 | -| host2 | 88.8 | 333.3 | 2022-06-15T07:02:38 | -+-------+------+--------+---------------------+"; - check_output_stream(output, expected).await; + connection = format!("{connection},ENDPOINT='{endpoint}'"); } + check_copy_from_object_store(instance, &format!("s3://{bucket}"), &connection).await; } } #[apply(both_instances_cases)] async fn test_execute_copy_from_oss(instance: Arc) { - common_telemetry::init_default_ut_logging(); if let Ok(bucket) = env::var("GT_OSS_BUCKET") && !bucket.is_empty() { - let instance = instance.frontend(); - - assert!(matches!( - execute_sql( - &instance, - "create table demo(host string, cpu double, memory double, ts timestamp time index);", - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let output = execute_sql( - &instance, - r#"insert into demo(host, cpu, memory, ts) values - ('host1', 66.6, 1024, 1655276557000), - ('host2', 88.8, 333.3, 1655276558000) - "#, - ) - .await - .data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let root = uuid::Uuid::new_v4().to_string(); - let key_id = env::var("GT_OSS_ACCESS_KEY_ID").unwrap(); - let key = env::var("GT_OSS_ACCESS_KEY").unwrap(); - let endpoint = env::var("GT_OSS_ENDPOINT").unwrap(); - - let copy_to_stmt = format!( - "Copy demo TO 'oss://{}/{}/export/demo.parquet' CONNECTION (ACCESS_KEY_ID='{}',ACCESS_KEY_SECRET='{}',ENDPOINT='{}')", - bucket, root, key_id, key, endpoint + let connection = format!( + "ACCESS_KEY_ID='{}',ACCESS_KEY_SECRET='{}',ENDPOINT='{}'", + env::var("GT_OSS_ACCESS_KEY_ID").unwrap(), + env::var("GT_OSS_ACCESS_KEY").unwrap(), + env::var("GT_OSS_ENDPOINT").unwrap() ); - - let output = execute_sql(&instance, ©_to_stmt).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - struct Test<'a> { - sql: &'a str, - table_name: &'a str, - } - let tests = [ - Test { - sql: &format!( - "Copy with_filename FROM 'oss://{}/{}/export/demo.parquet'", - bucket, root - ), - table_name: "with_filename", - }, - Test { - sql: &format!("Copy with_path FROM 'oss://{}/{}/export/'", bucket, root), - table_name: "with_path", - }, - Test { - sql: &format!( - "Copy with_pattern FROM 'oss://{}/{}/export/' WITH (PATTERN = 'demo.*')", - bucket, root - ), - table_name: "with_pattern", - }, - ]; - - for test in tests { - assert!(matches!( - execute_sql( - &instance, - &format!( - "create table {}(host string, cpu double, memory double, ts timestamp time index);", - test.table_name - ), - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let sql = format!( - "{} CONNECTION (ACCESS_KEY_ID='{}',ACCESS_KEY_SECRET='{}',ENDPOINT='{}')", - test.sql, key_id, key, endpoint, - ); - let output = execute_sql(&instance, &sql).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let output = execute_sql( - &instance, - &format!("select * from {} order by ts", test.table_name), - ) - .await - .data; - let expected = "\ -+-------+------+--------+---------------------+ -| host | cpu | memory | ts | -+-------+------+--------+---------------------+ -| host1 | 66.6 | 1024.0 | 2022-06-15T07:02:37 | -| host2 | 88.8 | 333.3 | 2022-06-15T07:02:38 | -+-------+------+--------+---------------------+"; - check_output_stream(output, expected).await; - } + check_copy_from_object_store(instance, &format!("oss://{bucket}"), &connection).await; } } #[apply(both_instances_cases)] async fn test_execute_copy_from_gcs(instance: Arc) { - common_telemetry::init_default_ut_logging(); if let (Ok(bucket), Ok(scope), Ok(credential)) = ( env::var("GT_GCS_BUCKET"), env::var("GT_GCS_SCOPE"), env::var("GT_GCS_CREDENTIAL"), ) && !bucket.is_empty() { + let mut connection = format!("SCOPE='{scope}',CREDENTIAL='{credential}'"); let endpoint = env::var("GT_GCS_ENDPOINT").unwrap_or_default(); - let instance = instance.frontend(); - - assert!(matches!( - execute_sql( - &instance, - "create table demo(host string, cpu double, memory double, ts timestamp time index);", - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let output = execute_sql( - &instance, - r#"insert into demo(host, cpu, memory, ts) values - ('host1', 66.6, 1024, 1655276557000), - ('host2', 88.8, 333.3, 1655276558000) - "#, - ) - .await - .data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let root = uuid::Uuid::new_v4().to_string(); - let mut connection = format!("SCOPE='{}',CREDENTIAL='{}'", scope, credential); if !endpoint.is_empty() { - connection = format!("{},ENDPOINT='{}'", connection, endpoint); - } - - let copy_to_stmt = format!( - "Copy demo TO 'gcs://{}/{}/export/demo.parquet' CONNECTION ({})", - bucket, root, connection - ); - - let output = execute_sql(&instance, ©_to_stmt).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - struct Test<'a> { - sql: &'a str, - table_name: &'a str, - } - let tests = [ - Test { - sql: &format!( - "Copy with_filename FROM 'gcs://{}/{}/export/demo.parquet'", - bucket, root - ), - table_name: "with_filename", - }, - Test { - sql: &format!("Copy with_path FROM 'gcs://{}/{}/export/'", bucket, root), - table_name: "with_path", - }, - Test { - sql: &format!( - "Copy with_pattern FROM 'gcs://{}/{}/export/' WITH (PATTERN = 'demo.*')", - bucket, root - ), - table_name: "with_pattern", - }, - ]; - - for test in tests { - assert!(matches!( - execute_sql( - &instance, - &format!( - "create table {}(host string, cpu double, memory double, ts timestamp time index);", - test.table_name - ), - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let sql = format!("{} CONNECTION ({})", test.sql, connection); - let output = execute_sql(&instance, &sql).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let output = execute_sql( - &instance, - &format!("select * from {} order by ts", test.table_name), - ) - .await - .data; - let expected = "\ -+-------+------+--------+---------------------+ -| host | cpu | memory | ts | -+-------+------+--------+---------------------+ -| host1 | 66.6 | 1024.0 | 2022-06-15T07:02:37 | -| host2 | 88.8 | 333.3 | 2022-06-15T07:02:38 | -+-------+------+--------+---------------------+"; - check_output_stream(output, expected).await; + connection = format!("{connection},ENDPOINT='{endpoint}'"); } + check_copy_from_object_store(instance, &format!("gcs://{bucket}"), &connection).await; } } #[apply(both_instances_cases)] async fn test_execute_copy_from_azblob(instance: Arc) { - common_telemetry::init_default_ut_logging(); if let (Ok(container), Ok(account_name), Ok(account_key), Ok(endpoint)) = ( env::var("GT_AZBLOB_CONTAINER"), env::var("GT_AZBLOB_ACCOUNT_NAME"), @@ -3711,103 +3238,78 @@ async fn test_execute_copy_from_azblob(instance: Arc) { env::var("GT_AZBLOB_ENDPOINT"), ) && !container.is_empty() { - let instance = instance.frontend(); + let connection = format!( + "ACCOUNT_NAME='{account_name}',ACCOUNT_KEY='{account_key}',ENDPOINT='{endpoint}'" + ); + check_copy_from_object_store(instance, &format!("azblob://{container}"), &connection).await; + } +} - assert!(matches!( - execute_sql( - &instance, - "create table demo(host string, cpu double, memory double, ts timestamp time index);", - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let output = execute_sql( - &instance, - r#"insert into demo(host, cpu, memory, ts) values +/// Exports a table to `{bucket_url}//export/demo.parquet`, then imports it back by +/// file name, by directory and by pattern. +async fn check_copy_from_object_store( + instance: Arc, + bucket_url: &str, + connection: &str, +) { + common_telemetry::init_default_ut_logging(); + let instance = instance.frontend(); + let create_table = |name: &str| { + format!( + "create table {name}(host string, cpu double, memory double, ts timestamp time index);" + ) + }; + assert!(matches!( + execute_sql(&instance, &create_table("demo")).await.data, + OutputData::AffectedRows(0) + )); + let output = execute_sql( + &instance, + r#"insert into demo(host, cpu, memory, ts) values ('host1', 66.6, 1024, 1655276557000), ('host2', 88.8, 333.3, 1655276558000) "#, + ) + .await + .data; + assert!(matches!(output, OutputData::AffectedRows(2))); + + let export_dir = format!("{bucket_url}/{}/export", uuid::Uuid::new_v4()); + let copy_to_stmt = + format!("Copy demo TO '{export_dir}/demo.parquet' CONNECTION ({connection})"); + let output = execute_sql(&instance, ©_to_stmt).await.data; + assert!(matches!(output, OutputData::AffectedRows(2))); + + for (table_name, source) in [ + ("with_filename", format!("'{export_dir}/demo.parquet'")), + ("with_path", format!("'{export_dir}/'")), + ( + "with_pattern", + format!("'{export_dir}/' WITH (PATTERN = 'demo.*')"), + ), + ] { + assert!(matches!( + execute_sql(&instance, &create_table(table_name)).await.data, + OutputData::AffectedRows(0) + )); + let sql = format!("Copy {table_name} FROM {source} CONNECTION ({connection})"); + let output = execute_sql(&instance, &sql).await.data; + assert!(matches!(output, OutputData::AffectedRows(2))); + + let output = execute_sql( + &instance, + &format!("select * from {table_name} order by ts"), ) .await .data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let root = uuid::Uuid::new_v4().to_string(); - - let copy_to_stmt = format!( - "Copy demo TO 'azblob://{}/{}/export/demo.parquet' CONNECTION (ACCOUNT_NAME='{}',ACCOUNT_KEY='{}',ENDPOINT='{}')", - container, root, account_name, account_key, endpoint - ); - - let output = execute_sql(&instance, ©_to_stmt).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - struct Test<'a> { - sql: &'a str, - table_name: &'a str, - } - let tests = [ - Test { - sql: &format!( - "Copy with_filename FROM 'azblob://{}/{}/export/demo.parquet'", - container, root - ), - table_name: "with_filename", - }, - Test { - sql: &format!( - "Copy with_path FROM 'azblob://{}/{}/export/'", - container, root - ), - table_name: "with_path", - }, - Test { - sql: &format!( - "Copy with_pattern FROM 'azblob://{}/{}/export/' WITH (PATTERN = 'demo.*')", - container, root - ), - table_name: "with_pattern", - }, - ]; - - for test in tests { - assert!(matches!( - execute_sql( - &instance, - &format!( - "create table {}(host string, cpu double, memory double, ts timestamp time index);", - test.table_name - ), - ) - .await - .data, - OutputData::AffectedRows(0) - )); - - let sql = format!( - "{} CONNECTION (ACCOUNT_NAME='{}',ACCOUNT_KEY='{}',ENDPOINT='{}')", - test.sql, account_name, account_key, endpoint - ); - let output = execute_sql(&instance, &sql).await.data; - assert!(matches!(output, OutputData::AffectedRows(2))); - - let output = execute_sql( - &instance, - &format!("select * from {} order by ts", test.table_name), - ) - .await - .data; - let expected = "\ + let expected = "\ +-------+------+--------+---------------------+ | host | cpu | memory | ts | +-------+------+--------+---------------------+ | host1 | 66.6 | 1024.0 | 2022-06-15T07:02:37 | | host2 | 88.8 | 333.3 | 2022-06-15T07:02:38 | +-------+------+--------+---------------------+"; - check_output_stream(output, expected).await; - } + check_output_stream(output, expected).await; } } diff --git a/tests-integration/tests/event_recorder_test_util.rs b/tests-integration/tests/event_recorder_test_util.rs index 38bb18861b3..1ce94711e71 100644 --- a/tests-integration/tests/event_recorder_test_util.rs +++ b/tests-integration/tests/event_recorder_test_util.rs @@ -111,6 +111,45 @@ pub(crate) async fn find_eventually_string( panic!("timed out waiting for event query: {query}"); } +/// Returns the id of the latest submitted `event_type` procedure matching `predicate`. +pub(crate) async fn find_submitted_procedure_id( + instance: &Arc, + event_type: &str, + predicate: &str, +) -> String { + find_eventually_string( + instance, + &format!( + r#"SELECT procedure_id +FROM greptime_private.events +WHERE type = '{event_type}' + AND json_path_match(procedure_trigger, '$.type == "Submitted"') + AND {predicate} +ORDER BY timestamp DESC +LIMIT 1"# + ), + "procedure_id", + ) + .await +} + +/// Asserts that the submitted event records a manual procedure issued over gRPC. +pub(crate) async fn assert_grpc_event_context( + instance: &Arc, + event_type: &str, + procedure_id: &str, +) { + let actual = find_eventually_string( + instance, + &format!( + "SELECT json_to_string(event_context) AS event_context FROM greptime_private.events WHERE type = '{event_type}' AND procedure_id = '{procedure_id}' AND json_path_match(procedure_trigger, '$.type == \"Submitted\"')" + ), + "event_context", + ) + .await; + assert_eq!(r#"{"protocol":"grpc","reason":"manual"}"#, actual); +} + /// Returns the first non-null u32 from `column` once the query produces one. pub(crate) async fn find_eventually_u32( instance: &Arc, diff --git a/tests-integration/tests/flow_ddl_event.rs b/tests-integration/tests/flow_ddl_event.rs index 9d2884468d2..0653e243973 100644 --- a/tests-integration/tests/flow_ddl_event.rs +++ b/tests-integration/tests/flow_ddl_event.rs @@ -21,7 +21,8 @@ use tests_integration::test_util::{ use uuid::Uuid; use crate::event_recorder_test_util::{ - assert_procedure_actor, assert_single_event, find_eventually_string, + assert_grpc_event_context, assert_procedure_actor, assert_single_event, + find_submitted_procedure_id, }; const CREATE_FLOW_EVENT_TYPE: &str = "create_flow"; @@ -72,7 +73,12 @@ async fn test_standalone_flow_ddl_events() { } async fn assert_create_events(instance: &Arc, flow: &str) { - let procedure_id = find_submitted_procedure_id(instance, CREATE_FLOW_EVENT_TYPE, flow).await; + let procedure_id = find_submitted_procedure_id( + instance, + CREATE_FLOW_EVENT_TYPE, + &format!("flow_name = '{flow}'"), + ) + .await; assert_procedure_actor(instance, &procedure_id, Some(PROCEDURE_ACTOR)).await; assert_single_event( instance, @@ -94,7 +100,7 @@ WHERE type = '{CREATE_FLOW_EVENT_TYPE}' ), ) .await; - assert_event_context(instance, CREATE_FLOW_EVENT_TYPE, &procedure_id).await; + assert_grpc_event_context(instance, CREATE_FLOW_EVENT_TYPE, &procedure_id).await; assert_single_event( instance, &format!( @@ -113,24 +119,13 @@ WHERE type = '{CREATE_FLOW_EVENT_TYPE}' .await; } -async fn assert_event_context( - instance: &Arc, - event_type: &str, - procedure_id: &str, -) { - let actual = find_eventually_string( +async fn assert_drop_events(instance: &Arc, flow: &str) { + let procedure_id = find_submitted_procedure_id( instance, - &format!( - "SELECT json_to_string(event_context) AS event_context FROM greptime_private.events WHERE type = '{event_type}' AND procedure_id = '{procedure_id}' AND json_path_match(procedure_trigger, '$.type == \"Submitted\"')" - ), - "event_context", + DROP_FLOW_EVENT_TYPE, + &format!("flow_name = '{flow}'"), ) .await; - assert_eq!(r#"{"protocol":"grpc","reason":"manual"}"#, actual); -} - -async fn assert_drop_events(instance: &Arc, flow: &str) { - let procedure_id = find_submitted_procedure_id(instance, DROP_FLOW_EVENT_TYPE, flow).await; assert_procedure_actor(instance, &procedure_id, Some(PROCEDURE_ACTOR)).await; assert_single_event( instance, @@ -149,7 +144,7 @@ WHERE type = '{DROP_FLOW_EVENT_TYPE}' ), ) .await; - assert_event_context(instance, DROP_FLOW_EVENT_TYPE, &procedure_id).await; + assert_grpc_event_context(instance, DROP_FLOW_EVENT_TYPE, &procedure_id).await; assert_single_event( instance, &format!( @@ -167,24 +162,3 @@ WHERE type = '{DROP_FLOW_EVENT_TYPE}' ) .await; } - -async fn find_submitted_procedure_id( - instance: &Arc, - event_type: &str, - flow_name: &str, -) -> String { - find_eventually_string( - instance, - &format!( - r#"SELECT procedure_id -FROM greptime_private.events -WHERE type = '{event_type}' - AND flow_name = '{flow_name}' - AND json_path_match(procedure_trigger, '$.type == "Submitted"') -ORDER BY timestamp DESC -LIMIT 1"#, - ), - "procedure_id", - ) - .await -} diff --git a/tests-integration/tests/grpc.rs b/tests-integration/tests/grpc.rs index e134a5e808c..42d508b38dc 100644 --- a/tests-integration/tests/grpc.rs +++ b/tests-integration/tests/grpc.rs @@ -134,7 +134,6 @@ macro_rules! grpc_tests { test_otel_arrow_auth, test_otel_arrow_delta_histogram, test_otel_arrow_exponential_histogram, - test_otel_arrow_exemplars_without_metric_engine, test_insert_and_select, test_dbname, test_grpc_message_size_ok, @@ -971,39 +970,12 @@ fn serialize_arrow_record_batch(record_batch: &ArrowRecordBatch) -> Vec { } fn exponential_histogram_arrow_batch(batch_id: i64, scales: &[i32]) -> BatchArrowRecords { - let resource = StructArray::from(vec![( - Arc::new(Field::new(arrow_consts::ID, DataType::UInt16, true)), - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - )]); - let scope = StructArray::from(vec![( - Arc::new(Field::new(arrow_consts::ID, DataType::UInt16, true)), - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - )]); - let metrics = ArrowRecordBatch::try_from_iter(vec![ - ( - arrow_consts::ID, - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - ), - (arrow_consts::RESOURCE, Arc::new(resource) as ArrayRef), - (arrow_consts::SCOPE, Arc::new(scope) as ArrayRef), - ( - arrow_consts::METRIC_TYPE, - Arc::new(UInt8Array::from(vec![ - ArrowMetricType::ExponentialHistogram as u8, - ])) as ArrayRef, - ), - ( - arrow_consts::NAME, - Arc::new(StringArray::from(vec!["otel.arrow.exponential.latency"])) as ArrayRef, - ), - ( - arrow_consts::AGGREGATION_TEMPORALITY, - Arc::new(Int32Array::from(vec![ - AggregationTemporality::Cumulative as i32, - ])) as ArrayRef, - ), - ]) - .unwrap(); + let metrics = arrow_metrics_payload( + batch_id, + ArrowMetricType::ExponentialHistogram, + "otel.arrow.exponential.latency", + Some(AggregationTemporality::Cumulative), + ); let point_count = scales.len(); let mut positive_counts = ListBuilder::new(UInt64Builder::new()); @@ -1109,11 +1081,7 @@ fn exponential_histogram_arrow_batch(batch_id: i64, scales: &[i32]) -> BatchArro BatchArrowRecords { batch_id, arrow_payloads: vec![ - ArrowPayload { - schema_id: format!("metrics-{batch_id}"), - r#type: ArrowPayloadType::UnivariateMetrics as i32, - record: serialize_arrow_record_batch(&metrics), - }, + metrics, ArrowPayload { schema_id: format!("exp-histogram-{batch_id}"), r#type: ArrowPayloadType::ExpHistogramDataPoints as i32, @@ -1128,35 +1096,12 @@ fn delta_histogram_arrow_batch( batch_id: i64, points: &[(u64, &[u64], &[f64])], ) -> BatchArrowRecords { - let resource = StructArray::from(vec![( - Arc::new(Field::new(arrow_consts::ID, DataType::UInt16, true)), - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - )]); - let scope = StructArray::from(vec![( - Arc::new(Field::new(arrow_consts::ID, DataType::UInt16, true)), - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - )]); - let metrics = ArrowRecordBatch::try_from_iter(vec![ - ( - arrow_consts::ID, - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - ), - (arrow_consts::RESOURCE, Arc::new(resource) as ArrayRef), - (arrow_consts::SCOPE, Arc::new(scope) as ArrayRef), - ( - arrow_consts::METRIC_TYPE, - Arc::new(UInt8Array::from(vec![ArrowMetricType::Histogram as u8])) as ArrayRef, - ), - ( - arrow_consts::NAME, - Arc::new(StringArray::from(vec!["otel.arrow.delta.histogram"])) as ArrayRef, - ), - ( - arrow_consts::AGGREGATION_TEMPORALITY, - Arc::new(Int32Array::from(vec![AggregationTemporality::Delta as i32])) as ArrayRef, - ), - ]) - .unwrap(); + let metrics = arrow_metrics_payload( + batch_id, + ArrowMetricType::Histogram, + "otel.arrow.delta.histogram", + Some(AggregationTemporality::Delta), + ); let mut bucket_counts = ListBuilder::new(UInt64Builder::new()); let mut explicit_bounds = ListBuilder::new(Float64Builder::new()); @@ -1222,11 +1167,7 @@ fn delta_histogram_arrow_batch( BatchArrowRecords { batch_id, arrow_payloads: vec![ - ArrowPayload { - schema_id: format!("metrics-{batch_id}"), - r#type: ArrowPayloadType::UnivariateMetrics as i32, - record: serialize_arrow_record_batch(&metrics), - }, + metrics, ArrowPayload { schema_id: format!("histogram-{batch_id}"), r#type: ArrowPayloadType::HistogramDataPoints as i32, @@ -1238,31 +1179,7 @@ fn delta_histogram_arrow_batch( } fn gauge_arrow_batch(batch_id: i64, reserved_attr: bool) -> BatchArrowRecords { - let resource = StructArray::from(vec![( - Arc::new(Field::new(arrow_consts::ID, DataType::UInt16, true)), - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - )]); - let scope = StructArray::from(vec![( - Arc::new(Field::new(arrow_consts::ID, DataType::UInt16, true)), - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - )]); - let metrics = ArrowRecordBatch::try_from_iter(vec![ - ( - arrow_consts::ID, - Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, - ), - (arrow_consts::RESOURCE, Arc::new(resource) as ArrayRef), - (arrow_consts::SCOPE, Arc::new(scope) as ArrayRef), - ( - arrow_consts::METRIC_TYPE, - Arc::new(UInt8Array::from(vec![ArrowMetricType::Gauge as u8])) as ArrayRef, - ), - ( - arrow_consts::NAME, - Arc::new(StringArray::from(vec!["otel.arrow.gauge"])) as ArrayRef, - ), - ]) - .unwrap(); + let metrics = arrow_metrics_payload(batch_id, ArrowMetricType::Gauge, "otel.arrow.gauge", None); let data_points = ArrowRecordBatch::try_from_iter(vec![ ( arrow_consts::ID, @@ -1291,11 +1208,7 @@ fn gauge_arrow_batch(batch_id: i64, reserved_attr: bool) -> BatchArrowRecords { ]) .unwrap(); let mut arrow_payloads = vec![ - ArrowPayload { - schema_id: format!("metrics-{batch_id}"), - r#type: ArrowPayloadType::UnivariateMetrics as i32, - record: serialize_arrow_record_batch(&metrics), - }, + metrics, ArrowPayload { schema_id: format!("number-{batch_id}"), r#type: ArrowPayloadType::NumberDataPoints as i32, @@ -1335,6 +1248,47 @@ fn gauge_arrow_batch(batch_id: i64, reserved_attr: bool) -> BatchArrowRecords { } } +fn arrow_metrics_payload( + batch_id: i64, + metric_type: ArrowMetricType, + name: &str, + temporality: Option, +) -> ArrowPayload { + let id_struct = || { + Arc::new(StructArray::from(vec![( + Arc::new(Field::new(arrow_consts::ID, DataType::UInt16, true)), + Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, + )])) as ArrayRef + }; + let mut columns = vec![ + ( + arrow_consts::ID, + Arc::new(UInt16Array::from(vec![0_u16])) as ArrayRef, + ), + (arrow_consts::RESOURCE, id_struct()), + (arrow_consts::SCOPE, id_struct()), + ( + arrow_consts::METRIC_TYPE, + Arc::new(UInt8Array::from(vec![metric_type as u8])) as ArrayRef, + ), + ( + arrow_consts::NAME, + Arc::new(StringArray::from(vec![name])) as ArrayRef, + ), + ]; + if let Some(temporality) = temporality { + columns.push(( + arrow_consts::AGGREGATION_TEMPORALITY, + Arc::new(Int32Array::from(vec![temporality as i32])) as ArrayRef, + )); + } + ArrowPayload { + schema_id: format!("metrics-{batch_id}"), + r#type: ArrowPayloadType::UnivariateMetrics as i32, + record: serialize_arrow_record_batch(&ArrowRecordBatch::try_from_iter(columns).unwrap()), + } +} + #[apply(both_deployment_cases)] async fn test_skip_wal_otel_arrow_metrics(distributed: bool) { // OTEL Arrow metrics decode into ordinary metric inserts, unlike Flight DoPut bulk inserts. @@ -1424,103 +1378,6 @@ pub async fn test_otel_arrow_delta_histogram(store_type: StorageType) { let _ = server.shutdown().await; } -pub async fn test_otel_arrow_exemplars_without_metric_engine(store_type: StorageType) { - use datatypes::arrow::array::BinaryArray; - use otel_arrow_rust::Consumer; - use otel_arrow_rust::proto::opentelemetry::metrics::v1::metric; - - let (_instance, server) = setup_grpc_server( - store_type, - "test_otel_arrow_exemplars_without_metric_engine", - ) - .await; - let addr = server.bind_addr().unwrap().to_string(); - let db = Database::new_with_dbname( - format!("{DEFAULT_CATALOG_NAME}-{DEFAULT_SCHEMA_NAME}"), - Client::with_urls(vec![addr.clone()]), - ); - let mut client = ArrowMetricsServiceClient::connect(format!("http://{addr}")) - .await - .unwrap(); - let mut batch = gauge_arrow_batch(20, false); - let exemplars = ArrowRecordBatch::try_from_iter(vec![ - ( - arrow_consts::PARENT_ID, - Arc::new(UInt32Array::from(vec![0_u32])) as ArrayRef, - ), - ( - arrow_consts::TIME_UNIX_NANO, - Arc::new(TimestampNanosecondArray::from(vec![2_000_000_000])) as ArrayRef, - ), - ( - arrow_consts::DOUBLE_VALUE, - Arc::new(Float64Array::from(vec![0.5])) as ArrayRef, - ), - ( - arrow_consts::SPAN_ID, - Arc::new(BinaryArray::from_vec(vec![&[1_u8; 8]])) as ArrayRef, - ), - ( - arrow_consts::TRACE_ID, - Arc::new(BinaryArray::from_vec(vec![&[2_u8; 16]])) as ArrayRef, - ), - ]) - .unwrap(); - batch.arrow_payloads.push(ArrowPayload { - schema_id: "exemplars-20".into(), - r#type: ArrowPayloadType::NumberDpExemplars as i32, - record: serialize_arrow_record_batch(&exemplars), - }); - let decoded = Consumer::default() - .consume_metrics_batches(&mut batch.clone()) - .unwrap(); - let Some(metric::Data::Gauge(gauge)) = - &decoded.resource_metrics[0].scope_metrics[0].metrics[0].data - else { - panic!("expected a gauge") - }; - assert_eq!(gauge.data_points[0].exemplars.len(), 1); - - let request = Request::new(futures::stream::iter([ - batch, - delta_histogram_arrow_batch(21, &[(3, &[1, 2], &[1.0])]), - ])); - let mut response = client.arrow_metrics(request).await.unwrap().into_inner(); - for batch_id in [20, 21] { - let status = response.message().await.unwrap().unwrap(); - assert_eq!(status.batch_id, batch_id); - assert_eq!(status.status_code, ArrowStatusCode::Ok as i32); - assert!(status.status_message.is_empty()); - } - assert!(response.message().await.unwrap().is_none()); - for (sql, count) in [ - ("SELECT COUNT(*) AS c FROM otel_arrow_gauge", 1), - ( - "SELECT COUNT(*) AS c FROM otel_arrow_delta_histogram_bucket", - 2, - ), - ( - &format!( - "SELECT COUNT(*) AS c FROM information_schema.tables WHERE table_name='{METRICS_EXEMPLARS_TABLE}'" - ), - 0, - ), - ] { - let OutputData::Stream(stream) = db.sql(sql).await.unwrap().data else { - panic!("expected a stream") - }; - assert_eq!( - RecordBatches::try_collect(stream) - .await - .unwrap() - .pretty_print() - .unwrap(), - format!("+---+\n| c |\n+---+\n| {count} |\n+---+"), - ); - } - server.shutdown().await.unwrap(); -} - pub async fn test_otel_arrow_exponential_histogram(store_type: StorageType) { let (_instance, server) = setup_grpc_server(store_type, "test_otel_arrow_exponential_histogram").await; @@ -2913,6 +2770,8 @@ pub async fn test_grpc_memory_limit(store_type: StorageType) { #[apply(both_deployment_cases)] async fn test_exemplar_otel_arrow_skips_non_metric_source(distributed: bool) { use datatypes::arrow::array::BinaryArray; + use otel_arrow_rust::Consumer; + use otel_arrow_rust::proto::opentelemetry::metrics::v1::metric; use servers::query_handler::sql::SqlQueryHandler; use session::context::QueryContext; @@ -2952,26 +2811,47 @@ async fn test_exemplar_otel_arrow_skips_non_metric_source(distributed: bool) { r#type: ArrowPayloadType::NumberDpExemplars as i32, record: serialize_arrow_record_batch(&exemplars), }); - let mut response = client - .arrow_metrics(Request::new(futures::stream::iter([batch]))) - .await - .unwrap() - .into_inner(); - let status = response.message().await.unwrap().unwrap(); - assert_eq!(status.status_code, ArrowStatusCode::Ok as i32); - assert!(status.status_message.is_empty()); + // Guards against the exemplars being dropped by the decoder rather than by ingestion. + let decoded = Consumer::default() + .consume_metrics_batches(&mut batch.clone()) + .unwrap(); + let Some(metric::Data::Gauge(gauge)) = + &decoded.resource_metrics[0].scope_metrics[0].metrics[0].data + else { + panic!("expected a gauge") + }; + assert_eq!(gauge.data_points[0].exemplars.len(), 1); + + let request = Request::new(futures::stream::iter([ + batch, + delta_histogram_arrow_batch(2, &[(3, &[1, 2], &[1.0])]), + ])); + let mut response = client.arrow_metrics(request).await.unwrap().into_inner(); + for batch_id in [1, 2] { + let status = response.message().await.unwrap().unwrap(); + assert_eq!(status.batch_id, batch_id); + assert_eq!(status.status_code, ArrowStatusCode::Ok as i32); + assert!(status.status_message.is_empty()); + } assert!(response.message().await.unwrap().is_none()); // Arrow currently selects ordinary-engine ingestion; only exemplars are skipped. - let output = frontend - .do_query("SELECT COUNT(*) FROM otel_arrow_gauge", QueryContext::arc()) - .await - .remove(0) - .unwrap(); - common_test_util::recordbatch::check_output_stream( - output.data, - "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+", - ) - .await; + for (sql, expected) in [ + ( + "SELECT COUNT(*) FROM otel_arrow_gauge", + "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+", + ), + ( + "SELECT COUNT(*) FROM otel_arrow_delta_histogram_bucket", + "+----------+\n| count(*) |\n+----------+\n| 2 |\n+----------+", + ), + ] { + let output = frontend + .do_query(sql, QueryContext::arc()) + .await + .remove(0) + .unwrap(); + common_test_util::recordbatch::check_output_stream(output.data, expected).await; + } assert!( frontend .catalog_manager() diff --git a/tests-integration/tests/region_migration.rs b/tests-integration/tests/region_migration.rs index d50905637db..9a1dfc5cbda 100644 --- a/tests-integration/tests/region_migration.rs +++ b/tests-integration/tests/region_migration.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use std::time::Duration; -use client::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, Database, OutputData}; +use client::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, OutputData}; use common_catalog::consts::DEFAULT_PRIVATE_SCHEMA_NAME; use common_event_recorder::event_table::{ ACTOR_COLUMN, REGION_ID_COLUMN, REGION_MIGRATION_DST_NODE_ID_COLUMN, @@ -60,9 +60,11 @@ use servers::query_handler::sql::SqlQueryHandler; use session::context::{QueryContext, QueryContextRef}; use store_api::storage::RegionId; use table::metadata::TableId; +use tests_integration::cluster::migration; use tests_integration::cluster::{GreptimeDbCluster, GreptimeDbClusterBuilder}; use tests_integration::test_util::{ - PEER_PLACEHOLDER_ADDR, StorageType, get_test_store_config, setup_authenticated_grpc_database, + PEER_PLACEHOLDER_ADDR, StorageType, TempDirGuard, get_test_store_config, + setup_authenticated_grpc_database, }; use uuid::Uuid; @@ -118,48 +120,8 @@ macro_rules! region_migration_tests { /// A naive region migration test. pub async fn test_region_migration(store_type: StorageType, endpoints: Vec) { - let cluster_name = "test_region_migration"; - let peer_factory = |id| Peer { - id, - addr: PEER_PLACEHOLDER_ADDR.to_string(), - }; - - // Prepares test cluster. - let (store_config, _guard) = get_test_store_config(&store_type); - let home_dir = create_temp_dir("test_migration_data_home"); - let datanodes = 5u64; - let builder = GreptimeDbClusterBuilder::new(cluster_name).await; - let const_selector = Arc::new(ConstNodeSelector::new(vec![ - peer_factory(1), - peer_factory(2), - peer_factory(3), - ])); - let cluster = builder - .with_datanodes(datanodes as u32) - .with_store_config(store_config) - .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints.clone(), - ..Default::default() - }, - ..Default::default() - })) - .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints, - ..Default::default() - }, - kafka_topic: KafkaTopicConfig { - num_topics: 3, - topic_name_prefix: Uuid::new_v4().to_string(), - ..Default::default() - }, - ..Default::default() - })) - .with_shared_home_dir(Arc::new(home_dir)) - .with_meta_selector(const_selector.clone()) - .build(true) - .await; + let (cluster, _guard) = + build_kafka_cluster("test_region_migration", &store_type, endpoints, [1, 2, 3]).await; let mut logical_timer = 1685508715000; let table_metadata_manager = cluster.metasrv.table_metadata_manager().clone(); @@ -198,8 +160,8 @@ pub async fn test_region_migration(store_type: StorageType, endpoints: Vec, ) { - let cluster_name = "test_region_migration"; - let peer_factory = |id| Peer { - id, - addr: PEER_PLACEHOLDER_ADDR.to_string(), - }; - - // Prepares test cluster. - let (store_config, _guard) = get_test_store_config(&store_type); - let home_dir = create_temp_dir("test_migration_data_home"); - let datanodes = 5u64; - let builder = GreptimeDbClusterBuilder::new(cluster_name).await; - let const_selector = Arc::new(ConstNodeSelector::new(vec![ - peer_factory(1), - peer_factory(2), - peer_factory(3), - ])); - let cluster = builder - .with_datanodes(datanodes as u32) - .with_store_config(store_config) - .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints.clone(), - ..Default::default() - }, - ..Default::default() - })) - .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints, - ..Default::default() - }, - kafka_topic: KafkaTopicConfig { - num_topics: 3, - topic_name_prefix: Uuid::new_v4().to_string(), - ..Default::default() - }, - ..Default::default() - })) - .with_shared_home_dir(Arc::new(home_dir)) - .with_meta_selector(const_selector.clone()) - .build(true) - .await; + let (cluster, _guard) = + build_kafka_cluster("test_region_migration", &store_type, endpoints, [1, 2, 3]).await; // Prepares test metric tables. let table_id = prepare_testing_metric_table(&cluster).await; let query_ctx = QueryContext::arc(); @@ -361,22 +283,10 @@ pub async fn test_metric_table_region_migration_by_sql( info!("Started region procedure: {}!", procedure_id); // Waits condition by checking procedure state - let frontend = cluster.fe_instance().clone(); - let procedure_id_for_closure = procedure_id.clone(); - wait_condition( + migration::wait_for_migration( + cluster.fe_instance(), + &procedure_id, Duration::from_secs(10), - Box::pin(async move { - loop { - let state = query_procedure_by_sql(&frontend, &procedure_id_for_closure).await; - if state == "{\"status\":\"Done\"}" { - info!("Migration done: {state}"); - break; - } else { - info!("Migration not finished: {state}"); - tokio::time::sleep(Duration::from_millis(200)).await; - } - } - }), ) .await; @@ -441,48 +351,8 @@ async fn test_region_migration_by_sql_inner( endpoints: Vec, simulate_offline_source: bool, ) { - let cluster_name = "test_region_migration"; - let peer_factory = |id| Peer { - id, - addr: PEER_PLACEHOLDER_ADDR.to_string(), - }; - - // Prepares test cluster. - let (store_config, _guard) = get_test_store_config(&store_type); - let home_dir = create_temp_dir("test_migration_data_home"); - let datanodes = 5u64; - let builder = GreptimeDbClusterBuilder::new(cluster_name).await; - let const_selector = Arc::new(ConstNodeSelector::new(vec![ - peer_factory(1), - peer_factory(2), - peer_factory(3), - ])); - let mut cluster = builder - .with_datanodes(datanodes as u32) - .with_store_config(store_config) - .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints.clone(), - ..Default::default() - }, - ..Default::default() - })) - .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints, - ..Default::default() - }, - kafka_topic: KafkaTopicConfig { - num_topics: 3, - topic_name_prefix: Uuid::new_v4().to_string(), - ..Default::default() - }, - ..Default::default() - })) - .with_shared_home_dir(Arc::new(home_dir)) - .with_meta_selector(const_selector.clone()) - .build(true) - .await; + let (mut cluster, _guard) = + build_kafka_cluster("test_region_migration", &store_type, endpoints, [1, 2, 3]).await; let table_metadata_manager = cluster.metasrv.table_metadata_manager().clone(); let (actor_db, _actor_grpc_server) = setup_authenticated_grpc_database( cluster.fe_instance().clone(), @@ -523,27 +393,15 @@ async fn test_region_migration_by_sql_inner( let region_id = RegionId::new(table_id, from_regions.leader_regions[0]); // Trigger region migration. let procedure_id = - trigger_migration_by_grpc(&actor_db, region_id.as_u64(), from_peer_id, to_peer_id).await; + migration::migrate_region(&actor_db, region_id.as_u64(), from_peer_id, to_peer_id).await; info!("Started region procedure: {}!", procedure_id); // Waits condition by checking procedure state - let frontend = cluster.fe_instance().clone(); - let procedure_id_for_closure = procedure_id.clone(); - wait_condition( + migration::wait_for_migration( + cluster.fe_instance(), + &procedure_id, Duration::from_secs(10), - Box::pin(async move { - loop { - let state = query_procedure_by_sql(&frontend, &procedure_id_for_closure).await; - if state == "{\"status\":\"Done\"}" { - info!("Migration done: {state}"); - break; - } else { - info!("Migration not finished: {state}"); - tokio::time::sleep(Duration::from_millis(200)).await; - } - } - }), ) .await; @@ -610,21 +468,10 @@ async fn test_region_migration_by_sql_inner( from_peer_id, ) .await; - let frontend = cluster.fe_instance().clone(); - let procedure_id_for_closure = offline_procedure_id.clone(); - wait_condition( + migration::wait_for_migration( + cluster.fe_instance(), + &offline_procedure_id, default_distributed_time_constants().region_lease + Duration::from_secs(10), - Box::pin(async move { - loop { - let state = query_procedure_by_sql(&frontend, &procedure_id_for_closure).await; - if state == "{\"status\":\"Done\"}" { - info!("Offline-source migration done: {state}"); - break; - } - info!("Offline-source migration not finished: {state}"); - tokio::time::sleep(Duration::from_millis(200)).await; - } - }), ) .await; @@ -682,8 +529,8 @@ async fn test_region_migration_by_sql_inner( )), RegionMigrationProcedureTask::new( region_id, - peer_factory(from_peer_id), - peer_factory(to_peer_id), + peer(from_peer_id), + peer(to_peer_id), Duration::from_millis(1000), RegionMigrationTriggerReason::Manual, ), @@ -702,48 +549,13 @@ pub async fn test_region_migration_multiple_regions( store_type: StorageType, endpoints: Vec, ) { - let cluster_name = "test_region_migration_multiple_regions"; - let peer_factory = |id| Peer { - id, - addr: PEER_PLACEHOLDER_ADDR.to_string(), - }; - - // Prepares test cluster. - let (store_config, _guard) = get_test_store_config(&store_type); - let home_dir = create_temp_dir("test_region_migration_multiple_regions_data_home"); - let datanodes = 5u64; - let builder = GreptimeDbClusterBuilder::new(cluster_name).await; - let const_selector = Arc::new(ConstNodeSelector::new(vec![ - peer_factory(1), - peer_factory(2), - peer_factory(2), - ])); - let cluster = builder - .with_datanodes(datanodes as u32) - .with_store_config(store_config) - .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints.clone(), - ..Default::default() - }, - ..Default::default() - })) - .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints, - ..Default::default() - }, - kafka_topic: KafkaTopicConfig { - num_topics: 3, - topic_name_prefix: Uuid::new_v4().to_string(), - ..Default::default() - }, - ..Default::default() - })) - .with_shared_home_dir(Arc::new(home_dir)) - .with_meta_selector(const_selector.clone()) - .build(true) - .await; + let (cluster, _guard) = build_kafka_cluster( + "test_region_migration_multiple_regions", + &store_type, + endpoints, + [1, 2, 2], + ) + .await; let mut logical_timer = 1685508715000; let table_metadata_manager = cluster.metasrv.table_metadata_manager().clone(); @@ -792,8 +604,8 @@ pub async fn test_region_migration_multiple_regions( )), RegionMigrationProcedureTask::new( region_id, - peer_factory(from_peer_id), - peer_factory(to_peer_id), + peer(from_peer_id), + peer(to_peer_id), Duration::from_millis(1000), RegionMigrationTriggerReason::Manual, ), @@ -859,8 +671,8 @@ pub async fn test_region_migration_multiple_regions( )), RegionMigrationProcedureTask::new( region_id, - peer_factory(from_peer_id), - peer_factory(to_peer_id), + peer(from_peer_id), + peer(to_peer_id), Duration::from_millis(1000), RegionMigrationTriggerReason::Manual, ), @@ -872,48 +684,13 @@ pub async fn test_region_migration_multiple_regions( /// A region migration test for a region server contains all regions of the table. pub async fn test_region_migration_all_regions(store_type: StorageType, endpoints: Vec) { - let cluster_name = "test_region_migration_all_regions"; - let peer_factory = |id| Peer { - id, - addr: PEER_PLACEHOLDER_ADDR.to_string(), - }; - - // Prepares test cluster. - let (store_config, _guard) = get_test_store_config(&store_type); - let home_dir = create_temp_dir("test_region_migration_all_regions_data_home"); - let datanodes = 5u64; - let builder = GreptimeDbClusterBuilder::new(cluster_name).await; - let const_selector = Arc::new(ConstNodeSelector::new(vec![ - peer_factory(2), - peer_factory(2), - peer_factory(2), - ])); - let cluster = builder - .with_datanodes(datanodes as u32) - .with_store_config(store_config) - .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints.clone(), - ..Default::default() - }, - ..Default::default() - })) - .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints, - ..Default::default() - }, - kafka_topic: KafkaTopicConfig { - num_topics: 3, - topic_name_prefix: Uuid::new_v4().to_string(), - ..Default::default() - }, - ..Default::default() - })) - .with_shared_home_dir(Arc::new(home_dir)) - .with_meta_selector(const_selector.clone()) - .build(true) - .await; + let (cluster, _guard) = build_kafka_cluster( + "test_region_migration_all_regions", + &store_type, + endpoints, + [2, 2, 2], + ) + .await; let mut logical_timer = 1685508715000; let table_metadata_manager = cluster.metasrv.table_metadata_manager().clone(); @@ -954,8 +731,8 @@ pub async fn test_region_migration_all_regions(store_type: StorageType, endpoint )), RegionMigrationProcedureTask::new( region_id, - peer_factory(from_peer_id), - peer_factory(to_peer_id), + peer(from_peer_id), + peer(to_peer_id), Duration::from_millis(1000), RegionMigrationTriggerReason::Manual, ), @@ -1019,8 +796,8 @@ pub async fn test_region_migration_all_regions(store_type: StorageType, endpoint )), RegionMigrationProcedureTask::new( region_id, - peer_factory(from_peer_id), - peer_factory(to_peer_id), + peer(from_peer_id), + peer(to_peer_id), Duration::from_millis(1000), RegionMigrationTriggerReason::Manual, ), @@ -1034,48 +811,13 @@ pub async fn test_region_migration_incorrect_from_peer( store_type: StorageType, endpoints: Vec, ) { - let cluster_name = "test_region_migration_incorrect_from_peer"; - let peer_factory = |id| Peer { - id, - addr: PEER_PLACEHOLDER_ADDR.to_string(), - }; - - // Prepares test cluster. - let (store_config, _guard) = get_test_store_config(&store_type); - let home_dir = create_temp_dir("test_region_migration_incorrect_from_peer_data_home"); - let datanodes = 5u64; - let builder = GreptimeDbClusterBuilder::new(cluster_name).await; - let const_selector = Arc::new(ConstNodeSelector::new(vec![ - peer_factory(1), - peer_factory(2), - peer_factory(3), - ])); - let cluster = builder - .with_datanodes(datanodes as u32) - .with_store_config(store_config) - .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints.clone(), - ..Default::default() - }, - ..Default::default() - })) - .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints, - ..Default::default() - }, - kafka_topic: KafkaTopicConfig { - num_topics: 3, - topic_name_prefix: Uuid::new_v4().to_string(), - ..Default::default() - }, - ..Default::default() - })) - .with_shared_home_dir(Arc::new(home_dir)) - .with_meta_selector(const_selector.clone()) - .build(true) - .await; + let (cluster, _guard) = build_kafka_cluster( + "test_region_migration_incorrect_from_peer", + &store_type, + endpoints, + [1, 2, 3], + ) + .await; let logical_timer = 1685508715000; let table_metadata_manager = cluster.metasrv.table_metadata_manager().clone(); @@ -1103,8 +845,8 @@ pub async fn test_region_migration_incorrect_from_peer( )), RegionMigrationProcedureTask::new( region_id, - peer_factory(5), - peer_factory(1), + peer(5), + peer(1), Duration::from_millis(1000), RegionMigrationTriggerReason::Manual, ), @@ -1122,48 +864,13 @@ pub async fn test_region_migration_incorrect_region_id( store_type: StorageType, endpoints: Vec, ) { - let cluster_name = "test_region_migration_incorrect_region_id"; - let peer_factory = |id| Peer { - id, - addr: PEER_PLACEHOLDER_ADDR.to_string(), - }; - - // Prepares test cluster. - let (store_config, _guard) = get_test_store_config(&store_type); - let home_dir = create_temp_dir("test_region_migration_incorrect_region_id_data_home"); - let datanodes = 5u64; - let builder = GreptimeDbClusterBuilder::new(cluster_name).await; - let const_selector = Arc::new(ConstNodeSelector::new(vec![ - peer_factory(1), - peer_factory(2), - peer_factory(3), - ])); - let cluster = builder - .with_datanodes(datanodes as u32) - .with_store_config(store_config) - .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints.clone(), - ..Default::default() - }, - ..Default::default() - })) - .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { - connection: KafkaConnectionConfig { - broker_endpoints: endpoints, - ..Default::default() - }, - kafka_topic: KafkaTopicConfig { - num_topics: 3, - topic_name_prefix: Uuid::new_v4().to_string(), - ..Default::default() - }, - ..Default::default() - })) - .with_shared_home_dir(Arc::new(home_dir)) - .with_meta_selector(const_selector.clone()) - .build(true) - .await; + let (cluster, _guard) = build_kafka_cluster( + "test_region_migration_incorrect_region_id", + &store_type, + endpoints, + [1, 2, 3], + ) + .await; let logical_timer = 1685508715000; let table_metadata_manager = cluster.metasrv.table_metadata_manager().clone(); @@ -1191,8 +898,8 @@ pub async fn test_region_migration_incorrect_region_id( )), RegionMigrationProcedureTask::new( region_id, - peer_factory(2), - peer_factory(1), + peer(2), + peer(1), Duration::from_millis(1000), RegionMigrationTriggerReason::Manual, ), @@ -1230,6 +937,55 @@ impl Selector for ConstNodeSelector { } } +fn peer(id: u64) -> Peer { + Peer { + id, + addr: PEER_PLACEHOLDER_ADDR.to_string(), + } +} + +/// Starts a 5-datanode cluster on Kafka WAL whose metasrv places new regions on `region_peers`. +async fn build_kafka_cluster( + name: &str, + store_type: &StorageType, + endpoints: Vec, + region_peers: [u64; 3], +) -> (GreptimeDbCluster, TempDirGuard) { + let (store_config, guard) = get_test_store_config(store_type); + let home_dir = create_temp_dir(&format!("{name}_data_home")); + let selector = Arc::new(ConstNodeSelector::new( + region_peers.into_iter().map(peer).collect(), + )); + let cluster = GreptimeDbClusterBuilder::new(name) + .await + .with_datanodes(5) + .with_store_config(store_config) + .with_datanode_wal_config(DatanodeWalConfig::Kafka(DatanodeKafkaConfig { + connection: KafkaConnectionConfig { + broker_endpoints: endpoints.clone(), + ..Default::default() + }, + ..Default::default() + })) + .with_metasrv_wal_config(MetasrvWalConfig::Kafka(MetasrvKafkaConfig { + connection: KafkaConnectionConfig { + broker_endpoints: endpoints, + ..Default::default() + }, + kafka_topic: KafkaTopicConfig { + num_topics: 3, + topic_name_prefix: Uuid::new_v4().to_string(), + ..Default::default() + }, + ..Default::default() + })) + .with_shared_home_dir(Arc::new(home_dir)) + .with_meta_selector(selector) + .build(true) + .await; + (cluster, guard) +} + async fn wait_condition(timeout: Duration, condition: BoxFuture<'static, ()>) { tokio::time::timeout(timeout, condition).await.unwrap(); } @@ -1426,55 +1182,7 @@ async fn trigger_migration_by_sql( column.value(0).to_string() } -/// Triggers region migration through the authenticated public gRPC SQL endpoint. -async fn trigger_migration_by_grpc( - database: &Database, - region_id: u64, - from_peer_id: u64, - to_peer_id: u64, -) -> String { - let output = database - .sql(format!( - "admin migrate_region({region_id}, {from_peer_id}, {to_peer_id})" - )) - .await - .unwrap(); - let recordbatches = match output.data { - OutputData::RecordBatches(recordbatches) => recordbatches, - OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(), - OutputData::AffectedRows(_) => unreachable!(), - }; - - let record_batch = &recordbatches.take()[0]; - record_batch - .column(0) - .as_string::() - .value(0) - .to_string() -} - /// Query procedure state by SQL. -async fn query_procedure_by_sql(instance: &Arc, pid: &str) -> String { - let OutputData::RecordBatches(recordbatches) = run_sql( - instance, - &format!("admin procedure_state('{pid}')"), - QueryContext::arc(), - ) - .await - .unwrap() - .data - else { - unreachable!(); - }; - - info!("SQL result:\n {}", recordbatches.pretty_print().unwrap()); - - let record_batch = &recordbatches.take()[0]; - let column = record_batch.column(0); - let column = column.as_string::(); - column.value(0).to_string() -} - async fn insert_values(instance: &Arc, ts: u64) -> Vec> { let query_ctx = QueryContext::arc(); diff --git a/tests-integration/tests/repartition.rs b/tests-integration/tests/repartition.rs index 1db0610442f..1ceaf28be45 100644 --- a/tests-integration/tests/repartition.rs +++ b/tests-integration/tests/repartition.rs @@ -43,6 +43,10 @@ use sqlx::Row; use store_api::codec::PrimaryKeyEncoding; use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_DATA_REGION_GROUP}; use store_api::storage::{RegionId, TableId}; +use tests_integration::cluster::partition::{ + assert_partition_expression, check_partition_column_change, create_on_columns_test_table, + query_partitions_sql, repartition_on_columns_sql, split_on_columns_sql, +}; use tests_integration::cluster::{GreptimeDbCluster, GreptimeDbClusterBuilder}; use tests_integration::test_util::{ StorageType, get_test_store_config, setup_mysql_server_for_frontend_instance, @@ -1725,18 +1729,16 @@ pub async fn test_repartition_on_columns_data_correctness_mito(store_type: Stora let query_ctx = QueryContext::arc(); let instance = cluster.fe_instance(); - assert_on_columns_data_correctness( + check_partition_column_change( instance, "repartition_on_columns_data_table", &repartition_on_columns_sql("repartition_on_columns_data_table"), - query_ctx.clone(), ) .await; - assert_on_columns_data_correctness( + check_partition_column_change( instance, "split_on_columns_data_table", &split_on_columns_sql("split_on_columns_data_table"), - query_ctx.clone(), ) .await; @@ -2560,20 +2562,6 @@ async fn cluster_manifest_index_paths(cluster: &GreptimeDbCluster) -> BTreeSet String { - // We query information_schema.partitions to assert repartition results across engines, - // rather than relying on SHOW CREATE TABLE formatting differences. - format!( - "\ -SELECT table_catalog, table_schema, table_name, partition_name, partition_expression, \ -partition_description, greptime_partition_id, partition_ordinal_position \ -FROM information_schema.partitions \ -WHERE table_name = '{}' \ -ORDER BY partition_ordinal_position;", - table_name - ) -} - pub async fn test_repartition_mito(store_type: StorageType, flat_format: bool) { info!( "test_repartition_mito: store_type: {:?}, flat_format: {:?}", @@ -3285,58 +3273,17 @@ pub async fn test_repartition_metric( .unwrap(); } -async fn create_on_columns_test_table( - instance: &Arc, - table_name: &str, - query_ctx: QueryContextRef, -) { - let sql = format!( - r#" - CREATE TABLE `{table_name}`( - `id` INT, - `city` STRING, - `ts` TIMESTAMP TIME INDEX, - PRIMARY KEY(`id`, `city`) - ) PARTITION ON COLUMNS (`id`) ( - `id` < 10, - `id` >= 10 AND `id` < 20, - `id` >= 20 - ) ENGINE = mito; - "# - ); - run_sql(instance, &sql, query_ctx).await.unwrap(); -} - -async fn insert_on_columns_old_rows( - instance: &Arc, - table_name: &str, - query_ctx: QueryContextRef, -) { - let sql = format!( - r#" - INSERT INTO `{table_name}` VALUES - (1, 'London', '2022-01-01 00:00:00'), - (5, 'New York', '2022-01-01 00:00:00'), - (10, 'Paris', '2022-01-01 00:00:00'), - (15, 'Tokyo', '2022-01-01 00:00:00'), - (20, 'Beijing', '2022-01-01 00:00:00'); - "# - ); - run_sql(instance, &sql, query_ctx).await.unwrap(); -} - async fn assert_on_columns_metadata_overwrite( instance: &Arc, table_name: &str, alter_sql: &str, query_ctx: QueryContextRef, ) { - create_on_columns_test_table(instance, table_name, query_ctx.clone()).await; + create_on_columns_test_table(instance, table_name).await; run_sql(instance, alter_sql, query_ctx.clone()) .await .unwrap(); - tokio::time::sleep(Duration::from_millis(500)).await; - assert_partition_expression(instance, table_name, "id, city", query_ctx).await; + assert_partition_expression(instance, table_name, "id, city").await; } async fn assert_on_columns_rejects_removed_remaining_column( @@ -3345,7 +3292,7 @@ async fn assert_on_columns_rejects_removed_remaining_column( alter_sql: &str, query_ctx: QueryContextRef, ) { - create_on_columns_test_table(instance, table_name, query_ctx.clone()).await; + create_on_columns_test_table(instance, table_name).await; assert_sql_err_eq( instance, alter_sql, @@ -3355,97 +3302,6 @@ async fn assert_on_columns_rejects_removed_remaining_column( .await; } -async fn assert_on_columns_data_correctness( - instance: &Arc, - table_name: &str, - alter_sql: &str, - query_ctx: QueryContextRef, -) { - create_on_columns_test_table(instance, table_name, query_ctx.clone()).await; - insert_on_columns_old_rows(instance, table_name, query_ctx.clone()).await; - run_sql(instance, alter_sql, query_ctx.clone()) - .await - .unwrap(); - tokio::time::sleep(Duration::from_millis(500)).await; - - let result = run_sql( - instance, - &format!("SELECT * FROM `{table_name}` ORDER BY `id`, `city`"), - query_ctx.clone(), - ) - .await - .unwrap(); - let expected = "\ -+----+----------+---------------------+ -| id | city | ts | -+----+----------+---------------------+ -| 1 | London | 2022-01-01T00:00:00 | -| 5 | New York | 2022-01-01T00:00:00 | -| 10 | Paris | 2022-01-01T00:00:00 | -| 15 | Tokyo | 2022-01-01T00:00:00 | -| 20 | Beijing | 2022-01-01T00:00:00 | -+----+----------+---------------------+"; - check_output_stream(result.data, expected).await; - - let sql = format!( - r#" - INSERT INTO `{table_name}` VALUES - (2, 'Amsterdam', '2022-01-02 00:00:00'), - (7, 'Zurich', '2022-01-02 00:00:00'), - (12, 'Berlin', '2022-01-02 00:00:00'); - "# - ); - run_sql(instance, &sql, query_ctx.clone()).await.unwrap(); - - let result = run_sql( - instance, - &format!("SELECT * FROM `{table_name}` ORDER BY `id`, `city`"), - query_ctx, - ) - .await - .unwrap(); - let expected = "\ -+----+-----------+---------------------+ -| id | city | ts | -+----+-----------+---------------------+ -| 1 | London | 2022-01-01T00:00:00 | -| 2 | Amsterdam | 2022-01-02T00:00:00 | -| 5 | New York | 2022-01-01T00:00:00 | -| 7 | Zurich | 2022-01-02T00:00:00 | -| 10 | Paris | 2022-01-01T00:00:00 | -| 12 | Berlin | 2022-01-02T00:00:00 | -| 15 | Tokyo | 2022-01-01T00:00:00 | -| 20 | Beijing | 2022-01-01T00:00:00 | -+----+-----------+---------------------+"; - check_output_stream(result.data, expected).await; -} - -fn repartition_on_columns_sql(table_name: &str) -> String { - format!( - r#" - ALTER TABLE `{table_name}` REPARTITION ( - `id` < 10 - ) ON COLUMNS (`id`, `city`) INTO ( - `id` < 10 AND `city` < 'M', - `id` < 10 AND `city` >= 'M' - ); - "# - ) -} - -fn split_on_columns_sql(table_name: &str) -> String { - format!( - r#" - ALTER TABLE `{table_name}` SPLIT PARTITION ( - `id` < 10 - ) ON COLUMNS (`id`, `city`) INTO ( - `id` < 10 AND `city` < 'M', - `id` < 10 AND `city` >= 'M' - ); - "# - ) -} - fn repartition_on_columns_removed_column_sql(table_name: &str) -> String { format!( r#" @@ -3472,32 +3328,6 @@ fn split_on_columns_removed_column_sql(table_name: &str) -> String { ) } -async fn assert_partition_expression( - instance: &Arc, - table_name: &str, - expected_partition_expression: &str, - query_ctx: QueryContextRef, -) { - let result = run_sql( - instance, - &format!( - "SELECT DISTINCT partition_expression FROM information_schema.partitions WHERE table_name = '{table_name}' ORDER BY partition_expression" - ), - query_ctx, - ) - .await - .unwrap(); - let expected = format!( - "\ -+----------------------+ -| partition_expression | -+----------------------+ -| {expected_partition_expression:<20} | -+----------------------+" - ); - check_output_stream(result.data, &expected).await; -} - async fn assert_sql_err_eq( instance: &Arc, sql: &str, diff --git a/tests-integration/tests/repartition_event.rs b/tests-integration/tests/repartition_event.rs index 3cb436100aa..73569c4669f 100644 --- a/tests-integration/tests/repartition_event.rs +++ b/tests-integration/tests/repartition_event.rs @@ -26,7 +26,7 @@ use tests_integration::test_util::{ }; use crate::event_recorder_test_util::{ - assert_eventually_eq, assert_procedure_actor, find_eventually_string, + assert_eventually_eq, assert_procedure_actor, find_submitted_procedure_id, }; const TABLE_NAME: &str = "repartition_events"; @@ -281,24 +281,3 @@ ORDER BY source_region_id"# assert_eventually_eq(instance, &query, expected).await; } - -async fn find_submitted_procedure_id( - instance: &Arc, - event_type: &str, - predicate: &str, -) -> String { - find_eventually_string( - instance, - &format!( - r#"SELECT procedure_id -FROM greptime_private.events -WHERE type = '{event_type}' - AND json_path_match(procedure_trigger, '$.type == "Submitted"') - AND {predicate} -ORDER BY timestamp DESC -LIMIT 1"# - ), - "procedure_id", - ) - .await -} diff --git a/tests-integration/tests/view_ddl_event.rs b/tests-integration/tests/view_ddl_event.rs index 8d17e9b4e25..2fb31ccacf8 100644 --- a/tests-integration/tests/view_ddl_event.rs +++ b/tests-integration/tests/view_ddl_event.rs @@ -24,7 +24,8 @@ use tests_integration::test_util::{ use uuid::Uuid; use crate::event_recorder_test_util::{ - assert_procedure_actor, assert_single_event, find_eventually_string, + assert_grpc_event_context, assert_procedure_actor, assert_single_event, + find_submitted_procedure_id, }; const CREATE_VIEW_EVENT_TYPE: &str = "create_view"; @@ -91,7 +92,12 @@ async fn execute_view_ddl( } async fn assert_create_events(instance: &Arc, view: &str) { - let procedure_id = find_submitted_procedure_id(instance, CREATE_VIEW_EVENT_TYPE, view).await; + let procedure_id = find_submitted_procedure_id( + instance, + CREATE_VIEW_EVENT_TYPE, + &format!("view_name = '{view}'"), + ) + .await; assert_procedure_actor(instance, &procedure_id, Some(PROCEDURE_ACTOR)).await; assert_single_event( instance, @@ -114,7 +120,7 @@ WHERE type = '{CREATE_VIEW_EVENT_TYPE}' ), ) .await; - assert_event_context(instance, CREATE_VIEW_EVENT_TYPE, &procedure_id).await; + assert_grpc_event_context(instance, CREATE_VIEW_EVENT_TYPE, &procedure_id).await; assert_single_event( instance, &format!( @@ -134,24 +140,13 @@ WHERE type = '{CREATE_VIEW_EVENT_TYPE}' .await; } -async fn assert_event_context( - instance: &Arc, - event_type: &str, - procedure_id: &str, -) { - let actual = find_eventually_string( +async fn assert_drop_events(instance: &Arc, view: &str) { + let procedure_id = find_submitted_procedure_id( instance, - &format!( - "SELECT json_to_string(event_context) AS event_context FROM greptime_private.events WHERE type = '{event_type}' AND procedure_id = '{procedure_id}' AND json_path_match(procedure_trigger, '$.type == \"Submitted\"')" - ), - "event_context", + DROP_VIEW_EVENT_TYPE, + &format!("view_name = '{view}'"), ) .await; - assert_eq!(r#"{"protocol":"grpc","reason":"manual"}"#, actual); -} - -async fn assert_drop_events(instance: &Arc, view: &str) { - let procedure_id = find_submitted_procedure_id(instance, DROP_VIEW_EVENT_TYPE, view).await; assert_procedure_actor(instance, &procedure_id, Some(PROCEDURE_ACTOR)).await; assert_single_event( instance, @@ -171,7 +166,7 @@ WHERE type = '{DROP_VIEW_EVENT_TYPE}' ), ) .await; - assert_event_context(instance, DROP_VIEW_EVENT_TYPE, &procedure_id).await; + assert_grpc_event_context(instance, DROP_VIEW_EVENT_TYPE, &procedure_id).await; assert_single_event( instance, &format!( @@ -190,24 +185,3 @@ WHERE type = '{DROP_VIEW_EVENT_TYPE}' ) .await; } - -async fn find_submitted_procedure_id( - instance: &Arc, - event_type: &str, - view_name: &str, -) -> String { - find_eventually_string( - instance, - &format!( - r#"SELECT procedure_id -FROM greptime_private.events -WHERE type = '{event_type}' - AND view_name = '{view_name}' - AND json_path_match(procedure_trigger, '$.type == "Submitted"') -ORDER BY timestamp DESC -LIMIT 1"#, - ), - "procedure_id", - ) - .await -}