mito2/worker/handle_write.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
// 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.
//! Handling write requests.
use std::collections::{hash_map, HashMap};
use std::sync::Arc;
use api::v1::OpType;
use common_telemetry::{debug, error};
use common_wal::options::WalOptions;
use snafu::ensure;
use store_api::codec::PrimaryKeyEncoding;
use store_api::logstore::LogStore;
use store_api::storage::RegionId;
use crate::error::{InvalidRequestSnafu, RegionStateSnafu, RejectWriteSnafu, Result};
use crate::metrics::{WRITE_REJECT_TOTAL, WRITE_ROWS_TOTAL, WRITE_STAGE_ELAPSED};
use crate::region::{RegionLeaderState, RegionRoleState};
use crate::region_write_ctx::RegionWriteCtx;
use crate::request::{SenderWriteRequest, WriteRequest};
use crate::worker::RegionWorkerLoop;
impl<S: LogStore> RegionWorkerLoop<S> {
/// Takes and handles all write requests.
pub(crate) async fn handle_write_requests(
&mut self,
write_requests: &mut Vec<SenderWriteRequest>,
allow_stall: bool,
) {
if write_requests.is_empty() {
return;
}
// Flush this worker if the engine needs to flush.
self.maybe_flush_worker();
if self.should_reject_write() {
// The memory pressure is still too high, reject write requests.
reject_write_requests(write_requests);
// Also reject all stalled requests.
self.reject_stalled_requests();
return;
}
if self.write_buffer_manager.should_stall() && allow_stall {
self.stalled_count.add(write_requests.len() as i64);
self.stalled_requests.append(write_requests);
self.listener.on_write_stall();
return;
}
// Prepare write context.
let mut region_ctxs = {
let _timer = WRITE_STAGE_ELAPSED
.with_label_values(&["prepare_ctx"])
.start_timer();
self.prepare_region_write_ctx(write_requests)
};
// Write to WAL.
{
let _timer = WRITE_STAGE_ELAPSED
.with_label_values(&["write_wal"])
.start_timer();
let mut wal_writer = self.wal.writer();
for region_ctx in region_ctxs.values_mut() {
if let WalOptions::Noop = ®ion_ctx.version().options.wal_options {
// Skip wal write for noop region.
continue;
}
if let Err(e) = region_ctx.add_wal_entry(&mut wal_writer).map_err(Arc::new) {
region_ctx.set_error(e);
}
}
match wal_writer.write_to_wal().await.map_err(Arc::new) {
Ok(response) => {
for (region_id, region_ctx) in region_ctxs.iter_mut() {
if let WalOptions::Noop = ®ion_ctx.version().options.wal_options {
continue;
}
// Safety: the log store implementation ensures that either the `write_to_wal` fails and no
// response is returned or the last entry ids for each region do exist.
let last_entry_id = response.last_entry_ids.get(region_id).unwrap();
region_ctx.set_next_entry_id(last_entry_id + 1);
}
}
Err(e) => {
// Failed to write wal.
for mut region_ctx in region_ctxs.into_values() {
region_ctx.set_error(e.clone());
}
return;
}
}
}
let (mut put_rows, mut delete_rows) = (0, 0);
// Write to memtables.
{
let _timer = WRITE_STAGE_ELAPSED
.with_label_values(&["write_memtable"])
.start_timer();
if region_ctxs.len() == 1 {
// fast path for single region.
let mut region_ctx = region_ctxs.into_values().next().unwrap();
region_ctx.write_memtable().await;
put_rows += region_ctx.put_num;
delete_rows += region_ctx.delete_num;
} else {
let region_write_task = region_ctxs
.into_values()
.map(|mut region_ctx| {
// use tokio runtime to schedule tasks.
common_runtime::spawn_global(async move {
region_ctx.write_memtable().await;
(region_ctx.put_num, region_ctx.delete_num)
})
})
.collect::<Vec<_>>();
for result in futures::future::join_all(region_write_task).await {
match result {
Ok((put, delete)) => {
put_rows += put;
delete_rows += delete;
}
Err(e) => {
error!(e; "unexpected error when joining region write tasks");
}
}
}
}
}
WRITE_ROWS_TOTAL
.with_label_values(&["put"])
.inc_by(put_rows as u64);
WRITE_ROWS_TOTAL
.with_label_values(&["delete"])
.inc_by(delete_rows as u64);
}
/// Handles all stalled write requests.
pub(crate) async fn handle_stalled_requests(&mut self) {
// Handle stalled requests.
let stalled = std::mem::take(&mut self.stalled_requests);
self.stalled_count.sub(stalled.stalled_count() as i64);
// We already stalled these requests, don't stall them again.
for (_, (_, mut requests)) in stalled.requests {
self.handle_write_requests(&mut requests, false).await;
}
}
/// Rejects all stalled requests.
pub(crate) fn reject_stalled_requests(&mut self) {
let stalled = std::mem::take(&mut self.stalled_requests);
self.stalled_count.sub(stalled.stalled_count() as i64);
for (_, (_, mut requests)) in stalled.requests {
reject_write_requests(&mut requests);
}
}
/// Rejects a specific region's stalled requests.
pub(crate) fn reject_region_stalled_requests(&mut self, region_id: &RegionId) {
debug!("Rejects stalled requests for region {}", region_id);
let mut requests = self.stalled_requests.remove(region_id);
self.stalled_count.sub(requests.len() as i64);
reject_write_requests(&mut requests);
}
/// Handles a specific region's stalled requests.
pub(crate) async fn handle_region_stalled_requests(&mut self, region_id: &RegionId) {
debug!("Handles stalled requests for region {}", region_id);
let mut requests = self.stalled_requests.remove(region_id);
self.stalled_count.sub(requests.len() as i64);
self.handle_write_requests(&mut requests, true).await;
}
}
impl<S> RegionWorkerLoop<S> {
/// Validates and groups requests by region.
fn prepare_region_write_ctx(
&mut self,
write_requests: &mut Vec<SenderWriteRequest>,
) -> HashMap<RegionId, RegionWriteCtx> {
// Initialize region write context map.
let mut region_ctxs = HashMap::new();
for mut sender_req in write_requests.drain(..) {
let region_id = sender_req.request.region_id;
// If region is waiting for alteration, add requests to pending writes.
if self.flush_scheduler.has_pending_ddls(region_id) {
// TODO(yingwen): consider adding some metrics for this.
// Safety: The region has pending ddls.
self.flush_scheduler
.add_write_request_to_pending(sender_req);
continue;
}
// Checks whether the region exists and is it stalling.
if let hash_map::Entry::Vacant(e) = region_ctxs.entry(region_id) {
let Some(region) = self
.regions
.get_region_or(region_id, &mut sender_req.sender)
else {
// No such region.
continue;
};
match region.state() {
RegionRoleState::Leader(RegionLeaderState::Writable) => {
let region_ctx = RegionWriteCtx::new(
region.region_id,
®ion.version_control,
region.provider.clone(),
);
e.insert(region_ctx);
}
RegionRoleState::Leader(RegionLeaderState::Altering) => {
debug!(
"Region {} is altering, add request to pending writes",
region.region_id
);
self.stalled_count.add(1);
self.stalled_requests.push(sender_req);
continue;
}
state => {
// The region is not writable.
sender_req.sender.send(
RegionStateSnafu {
region_id,
state,
expect: RegionRoleState::Leader(RegionLeaderState::Writable),
}
.fail(),
);
continue;
}
}
}
// Safety: Now we ensure the region exists.
let region_ctx = region_ctxs.get_mut(®ion_id).unwrap();
if let Err(e) = check_op_type(
region_ctx.version().options.append_mode,
&sender_req.request,
) {
// Do not allow non-put op under append mode.
sender_req.sender.send(Err(e));
continue;
}
// Double check the request schema
let need_fill_missing_columns =
if let Some(ref region_metadata) = sender_req.request.region_metadata {
region_ctx.version().metadata.schema_version != region_metadata.schema_version
} else {
true
};
// Only fill missing columns if primary key is dense encoded.
if need_fill_missing_columns
&& sender_req.request.primary_key_encoding() == PrimaryKeyEncoding::Dense
{
if let Err(e) = sender_req
.request
.maybe_fill_missing_columns(®ion_ctx.version().metadata)
{
sender_req.sender.send(Err(e));
continue;
}
}
// Collect requests by region.
region_ctx.push_mutation(
sender_req.request.op_type as i32,
Some(sender_req.request.rows),
sender_req.request.hint,
sender_req.sender,
);
}
region_ctxs
}
/// Returns true if the engine needs to reject some write requests.
fn should_reject_write(&self) -> bool {
// If memory usage reaches high threshold (we should also consider stalled requests) returns true.
self.write_buffer_manager.memory_usage() + self.stalled_requests.estimated_size
>= self.config.global_write_buffer_reject_size.as_bytes() as usize
}
}
/// Send rejected error to all `write_requests`.
fn reject_write_requests(write_requests: &mut Vec<SenderWriteRequest>) {
WRITE_REJECT_TOTAL.inc_by(write_requests.len() as u64);
for req in write_requests.drain(..) {
req.sender.send(
RejectWriteSnafu {
region_id: req.request.region_id,
}
.fail(),
);
}
}
/// Rejects delete request under append mode.
fn check_op_type(append_mode: bool, request: &WriteRequest) -> Result<()> {
if append_mode {
ensure!(
request.op_type == OpType::Put,
InvalidRequestSnafu {
region_id: request.region_id,
reason: "DELETE is not allowed under append mode",
}
);
}
Ok(())
}