use crate::cluster::{
CLUSTER_SLOTS, ClusterState, MigrationState, NodeFlags, NodeId, key_hash_slot, node_id_str,
};
use crate::commands::ctx::Ctx;
use crate::resp::write::*;
use std::sync::Arc;
pub fn handle(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
let cmd = &ctx.cmd;
match name {
"CLUSTER" => {
if cmd.len() < 2 {
return Some(resp_error(
"ERR wrong number of arguments for 'cluster' command",
));
}
let sub = String::from_utf8_lossy(cmd[1]).to_ascii_uppercase();
Some(handle_cluster(ctx, &sub))
}
"ASKING" => Some(cmd_asking(ctx)),
"READONLY" => Some(cmd_readonly(ctx)),
"READWRITE" => Some(cmd_readwrite(ctx)),
_ => None,
}
}
fn handle_cluster(ctx: &mut Ctx, sub: &str) -> Vec<u8> {
let state: &Arc<ClusterState> = ctx.cluster;
match sub {
"INFO" => return cmd_info(state),
"KEYSLOT" => return cmd_keyslot(&ctx.cmd),
"NODES" => return cmd_nodes(state),
"SLOTS" => return cmd_slots(state),
"SHARDS" => return cmd_shards(state),
"ADDSLOTS" => return cmd_addslots(ctx),
"DELSLOTS" => return cmd_delslots(state, &ctx.cmd),
"ADDSLOTSRANGE" => return cmd_addslotsrange(ctx),
"DELSLOTSRANGE" => return cmd_delslotsrange(state, &ctx.cmd),
"FLUSHSLOTS" => return cmd_flushslots(ctx),
"BUMPEPOCH" => return cmd_bumpepoch(state),
"SET-CONFIG-EPOCH" => return cmd_set_config_epoch(state, &ctx.cmd),
"SAVECONFIG" => return cmd_saveconfig(state),
_ => {}
}
if !state.enabled {
if crate::commands::arity::of(&format!("CLUSTER|{sub}")).is_none()
&& !matches!(sub, "MIGRATION" | "SYNCSLOTS")
{
return unknown_cluster_subcommand(ctx);
}
return resp_error("ERR This instance has cluster support disabled");
}
match sub {
"MYID" => cmd_myid(state),
"COUNTKEYSINSLOT" => cmd_countkeysinslot(ctx),
"GETKEYSINSLOT" => cmd_getkeysinslot(ctx),
"MEET" => cmd_meet(ctx),
"FORGET" => cmd_forget(ctx),
"COUNT-FAILURE-REPORTS" => cmd_count_failure_reports(ctx),
"LINKS" => cmd_links(ctx),
"REPLICAS" | "SLAVES" => cmd_replicas(ctx),
"REPLICATE" => cmd_replicate(ctx),
"FAILOVER" => cmd_failover(ctx),
"SETSLOT" => cmd_setslot(ctx),
"RESET" => cmd_reset(ctx),
"MYSHARDID" => cmd_myshardid(ctx),
"SLOT-STATS" => cmd_slot_stats(ctx),
"MIGRATION" => cmd_migration(ctx),
"SYNCSLOTS" => cmd_syncslots(ctx),
"HELP" if ctx.cmd.len() == 2 => cluster_help(),
_ => unknown_cluster_subcommand(ctx),
}
}
fn unknown_cluster_subcommand(ctx: &Ctx) -> Vec<u8> {
resp_error(&format!(
"ERR unknown subcommand '{}'. Try CLUSTER HELP.",
String::from_utf8_lossy(ctx.cmd[1])
))
}
fn cluster_help() -> Vec<u8> {
const LINES: &[&str] = &[
"CLUSTER <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
"COUNTKEYSINSLOT <slot>",
" Return the number of keys in <slot>.",
"GETKEYSINSLOT <slot> <count>",
" Return key names stored by current node in a slot.",
"INFO",
" Return information about the cluster.",
"KEYSLOT <key>",
" Return the hash slot for <key>.",
"MYID",
" Return the node id.",
"MYSHARDID",
" Return the node's shard id.",
"NODES",
" Return cluster configuration seen by node. Output format:",
" <id> <ip:port@bus-port[,hostname]> <flags> <master> <pings> <pongs> <epoch> <link> <slot> ...",
"REPLICAS <node-id>",
" Return <node-id> replicas.",
"SLOTS",
" Return information about slots range mappings. Each range is made of:",
" start, end, master and replicas IP addresses, ports and ids",
"SLOT-STATS",
" Return an array of slot usage statistics for slots assigned to the current node.",
"SHARDS",
" Return information about slot range mappings and the nodes associated with them.",
"ADDSLOTS <slot> [<slot> ...]",
" Assign slots to current node.",
"ADDSLOTSRANGE <start slot> <end slot> [<start slot> <end slot> ...]",
" Assign slots which are between <start-slot> and <end-slot> to current node.",
"BUMPEPOCH",
" Advance the cluster config epoch.",
"COUNT-FAILURE-REPORTS <node-id>",
" Return number of failure reports for <node-id>.",
"DELSLOTS <slot> [<slot> ...]",
" Delete slots information from current node.",
"DELSLOTSRANGE <start slot> <end slot> [<start slot> <end slot> ...]",
" Delete slots information which are between <start-slot> and <end-slot> from current node.",
"FAILOVER [FORCE|TAKEOVER]",
" Promote current replica node to being a master.",
"FORGET <node-id>",
" Remove a node from the cluster.",
"FLUSHSLOTS",
" Delete current node own slots information.",
"MEET <ip> <port> [<bus-port>]",
" Connect nodes into a working cluster.",
"REPLICATE <node-id>",
" Configure current node as replica to <node-id>.",
"RESET [HARD|SOFT]",
" Reset current node (default: soft).",
"SET-CONFIG-EPOCH <epoch>",
" Set config epoch of current node.",
"SETSLOT <slot> (IMPORTING <node-id>|MIGRATING <node-id>|STABLE|NODE <node-id>)",
" Set slot state.",
"SAVECONFIG",
" Force saving cluster configuration on disk.",
"LINKS",
" Return information about all network links between this node and its peers.",
" Output format is an array where each array element is a map containing attributes of a link",
"MIGRATION IMPORT <start-slot end-slot [start-slot end-slot ...]> |",
" STATUS [ID <task-id> | ALL] | CANCEL [ID <task-id> | ALL]",
" Start, monitor and cancel slot migration.",
"HELP",
" Print this help.",
];
resp_array(LINES.iter().map(|line| resp_simple(line)).collect())
}
fn cmd_myid(state: &ClusterState) -> Vec<u8> {
resp_bulk_str(node_id_str(&state.myself()))
}
fn cmd_info(state: &ClusterState) -> Vec<u8> {
state.refresh_state();
let cluster_enabled = if state.enabled { 1 } else { 0 };
let cluster_state = state.cluster_state_str();
let (slots_assigned, slots_ok, slots_pfail, slots_fail) = state.slot_health();
let size = state.voting_master_count();
let current_epoch = state.current_epoch();
let nodes = state.nodes.read();
let known_nodes = nodes.len();
let mut out = String::with_capacity(512);
out.push_str(&format!("cluster_enabled:{cluster_enabled}\r\n"));
out.push_str(&format!("cluster_state:{cluster_state}\r\n"));
out.push_str(&format!("cluster_slots_assigned:{slots_assigned}\r\n"));
out.push_str(&format!("cluster_slots_ok:{slots_ok}\r\n"));
out.push_str(&format!("cluster_slots_pfail:{slots_pfail}\r\n"));
out.push_str(&format!("cluster_slots_fail:{slots_fail}\r\n"));
out.push_str(&format!("cluster_known_nodes:{known_nodes}\r\n"));
out.push_str(&format!("cluster_size:{size}\r\n"));
out.push_str(&format!("cluster_current_epoch:{current_epoch}\r\n"));
out.push_str(&format!(
"cluster_my_epoch:{}\r\n",
nodes
.get(&state.myself())
.map(|n| n.config_epoch)
.unwrap_or(0)
));
out.push_str(&format!(
"cluster_stats_messages_sent:{}\r\n",
state
.stats_messages_sent
.load(std::sync::atomic::Ordering::Relaxed)
));
out.push_str(&format!(
"cluster_stats_messages_received:{}\r\n",
state
.stats_messages_received
.load(std::sync::atomic::Ordering::Relaxed)
));
out.push_str(&format!(
"cluster_stats_bus_connects:{}\r\n",
state
.stats_bus_connects
.load(std::sync::atomic::Ordering::Relaxed)
));
out.push_str("total_cluster_links_buffer_limit_exceeded:0\r\n");
resp_bulk_str(&out)
}
fn cmd_keyslot(cmd: &[&[u8]]) -> Vec<u8> {
if cmd.len() != 3 {
return resp_error("ERR wrong number of arguments for 'cluster|keyslot' command");
}
let slot = key_hash_slot(cmd[2]);
resp_integer(slot as i64)
}
fn cmd_countkeysinslot(ctx: &Ctx) -> Vec<u8> {
if ctx.cmd.len() != 3 {
return resp_error("ERR wrong number of arguments for 'cluster|countkeysinslot' command");
}
let slot: u16 = match parse_slot_arg(ctx.cmd[2]) {
Ok(s) => s,
Err(e) => return e,
};
let db = &ctx.store[*ctx.selected_db];
let mut count: i64 = 0;
for shard in db.iter() {
let map = crate::read_lock!(shard);
for k in map.keys() {
if key_hash_slot(k) == slot {
count += 1;
}
}
}
resp_integer(count)
}
fn cmd_getkeysinslot(ctx: &Ctx) -> Vec<u8> {
if ctx.cmd.len() != 4 {
return resp_error("ERR wrong number of arguments for 'cluster|getkeysinslot' command");
}
let slot: u16 = match parse_slot_arg(ctx.cmd[2]) {
Ok(s) => s,
Err(e) => return e,
};
let count: i64 = match std::str::from_utf8(ctx.cmd[3])
.ok()
.and_then(|s| s.parse().ok())
{
Some(n) => n,
None => return resp_error("ERR value is not an integer or out of range"),
};
if count < 0 {
return resp_error("ERR Invalid slot or number of keys");
}
let count = count as usize;
let db = &ctx.store[*ctx.selected_db];
let mut out: Vec<Vec<u8>> = Vec::with_capacity(count.min(64));
if count == 0 {
return resp_array(out);
}
'outer: for shard in db.iter() {
let map = crate::read_lock!(shard);
for k in map.keys() {
if key_hash_slot(k) == slot {
out.push(resp_bulk(k));
if out.len() >= count {
break 'outer;
}
}
}
}
resp_array(out)
}
fn cmd_nodes(state: &ClusterState) -> Vec<u8> {
use std::fmt::Write;
let nodes = state.nodes.read();
let slots = state.slots.read();
let migrations = state.migrations.read();
let myself = state.myself();
let mut out = String::with_capacity(256 * nodes.len().max(1));
let mut sorted: Vec<&crate::cluster::ClusterNode> = nodes.values().collect();
sorted.sort_by_key(|n| n.id);
for node in sorted {
let _ = write!(
out,
"{} {}:{}@{}{}",
node_id_str(&node.id),
node.ip,
node.client_facing_port(),
node.cluster_port,
crate::cluster::persist::hostname_suffix(&node.hostname)
);
out.push(' ');
out.push_str(&format_flags_for_nodes(node.flags));
out.push(' ');
match node.master_id {
Some(m) => out.push_str(node_id_str(&m)),
None => out.push('-'),
}
let _ = write!(
out,
" {} {} {} {}",
node.ping_sent_ms,
node.pong_received_ms,
node.config_epoch,
link_state(node)
);
if node.flags.contains(NodeFlags::MASTER) {
for (a, b) in compute_slot_ranges(&slots, node.id) {
if a == b {
let _ = write!(out, " {a}");
} else {
let _ = write!(out, " {a}-{b}");
}
}
}
if node.id == myself {
let mut open: Vec<(u16, MigrationState)> =
migrations.iter().map(|(slot, m)| (*slot, *m)).collect();
open.sort_by_key(|(slot, _)| *slot);
for (slot, migration) in open {
let _ = match migration {
MigrationState::Migrating { dest_id } => {
write!(out, " [{slot}->-{}]", node_id_str(&dest_id))
}
MigrationState::Importing { src_id } => {
write!(out, " [{slot}-<-{}]", node_id_str(&src_id))
}
};
}
}
out.push('\n');
}
resp_bulk_str(&out)
}
fn cmd_slots(state: &ClusterState) -> Vec<u8> {
let nodes = state.nodes.read();
let slots = state.slots.read();
let mut ranges: Vec<(usize, usize, NodeId)> = Vec::new();
let mut start: Option<(usize, NodeId)> = None;
for i in 0..CLUSTER_SLOTS {
match (slots[i], start) {
(Some(owner), None) => start = Some((i, owner)),
(Some(owner), Some((s, prev_owner))) if owner != prev_owner => {
ranges.push((s, i - 1, prev_owner));
start = Some((i, owner));
}
(None, Some((s, prev_owner))) => {
ranges.push((s, i - 1, prev_owner));
start = None;
}
_ => {}
}
}
if let Some((s, owner)) = start {
ranges.push((s, CLUSTER_SLOTS - 1, owner));
}
let mut entries: Vec<Vec<u8>> = Vec::with_capacity(ranges.len());
for (a, b, owner_id) in ranges {
let owner = match nodes.get(&owner_id) {
Some(n) => n,
None => continue,
};
let mut entry = vec![
resp_integer(a as i64),
resp_integer(b as i64),
slots_node_entry(state, owner),
];
for replica in nodes
.values()
.filter(|n| n.flags.contains(NodeFlags::REPLICA) && n.master_id == Some(owner_id))
{
entry.push(slots_node_entry(state, replica));
}
entries.push(resp_array(entry));
}
resp_array(entries)
}
fn slots_node_entry(state: &ClusterState, node: &crate::cluster::ClusterNode) -> Vec<u8> {
use crate::cluster::Endpoint;
let preferred = state.preferred_endpoint();
let mut fields = vec![
match preferred {
Endpoint::Unknown => resp_null_bulk(),
_ => resp_bulk_str(&state.endpoint_of(node)),
},
resp_integer(node.client_facing_port() as i64),
resp_bulk_str(node_id_str(&node.id)),
];
let mut metadata: Vec<Vec<u8>> = Vec::new();
if preferred != Endpoint::Ip {
metadata.push(resp_bulk_str("ip"));
metadata.push(resp_bulk_str(&node.ip));
}
if preferred != Endpoint::Hostname && !node.hostname.is_empty() {
metadata.push(resp_bulk_str("hostname"));
metadata.push(resp_bulk_str(&node.hostname));
}
if !metadata.is_empty() {
fields.push(resp_array(metadata));
}
resp_array(fields)
}
fn cmd_shards(state: &ClusterState) -> Vec<u8> {
let nodes = state.nodes.read();
let slots = state.slots.read();
let mut shards: Vec<Vec<u8>> = Vec::new();
for master in nodes
.values()
.filter(|n| n.flags.contains(NodeFlags::MASTER))
{
let mut slot_pairs: Vec<Vec<u8>> = Vec::new();
for (a, b) in compute_slot_ranges(&slots, master.id) {
slot_pairs.push(resp_integer(a as i64));
slot_pairs.push(resp_integer(b as i64));
}
let mut node_descs: Vec<Vec<u8>> = Vec::new();
node_descs.push(node_description(state, master));
for replica in nodes
.values()
.filter(|n| n.flags.contains(NodeFlags::REPLICA) && n.master_id == Some(master.id))
{
node_descs.push(node_description(state, replica));
}
shards.push(resp_array(vec![
resp_bulk_str("slots"),
resp_array(slot_pairs),
resp_bulk_str("nodes"),
resp_array(node_descs),
]));
}
resp_array(shards)
}
fn link_state(node: &crate::cluster::ClusterNode) -> &'static str {
if !node.flags.contains(NodeFlags::MYSELF)
&& node
.flags
.intersects(NodeFlags::PFAIL | NodeFlags::FAIL | NodeFlags::HANDSHAKE)
{
"disconnected"
} else {
"connected"
}
}
fn node_description(state: &ClusterState, node: &crate::cluster::ClusterNode) -> Vec<u8> {
let role = if node.flags.contains(NodeFlags::MASTER) {
"master"
} else if node.flags.contains(NodeFlags::REPLICA) {
"replica"
} else {
"unknown"
};
let health = if node.flags.contains(NodeFlags::FAIL) {
"fail"
} else {
"online"
};
let mut fields = vec![
resp_bulk_str("id"),
resp_bulk_str(node_id_str(&node.id)),
resp_bulk_str("port"),
resp_integer(node.client_facing_port() as i64),
resp_bulk_str("ip"),
resp_bulk_str(&node.ip),
resp_bulk_str("endpoint"),
resp_bulk_str(&state.endpoint_of(node)),
];
if !node.hostname.is_empty() {
fields.push(resp_bulk_str("hostname"));
fields.push(resp_bulk_str(&node.hostname));
}
fields.extend([
resp_bulk_str("role"),
resp_bulk_str(role),
resp_bulk_str("replication-offset"),
resp_integer(0),
resp_bulk_str("health"),
resp_bulk_str(health),
]);
resp_array(fields)
}
fn parse_slot_arg(arg: &[u8]) -> Result<u16, Vec<u8>> {
let s = std::str::from_utf8(arg).map_err(|_| resp_error("ERR invalid slot"))?;
let n: i64 = s
.parse()
.map_err(|_| resp_error("ERR value is not an integer or out of range"))?;
if !(0..CLUSTER_SLOTS as i64).contains(&n) {
return Err(resp_error(&format!(
"ERR Invalid slot {n}, must be between 0 and {}",
CLUSTER_SLOTS - 1
)));
}
Ok(n as u16)
}
fn format_flags_for_nodes(f: NodeFlags) -> String {
let mut parts: Vec<&str> = Vec::new();
if f.contains(NodeFlags::MYSELF) {
parts.push("myself");
}
if f.contains(NodeFlags::MASTER) {
parts.push("master");
}
if f.contains(NodeFlags::REPLICA) {
parts.push("slave");
}
if f.contains(NodeFlags::PFAIL) {
parts.push("fail?");
}
if f.contains(NodeFlags::FAIL) {
parts.push("fail");
}
if f.contains(NodeFlags::HANDSHAKE) {
parts.push("handshake");
}
if f.contains(NodeFlags::NOADDR) {
parts.push("noaddr");
}
if parts.is_empty() {
return "noflags".into();
}
parts.join(",")
}
fn compute_slot_ranges(
slots: &[Option<NodeId>; CLUSTER_SLOTS],
owner: NodeId,
) -> Vec<(usize, usize)> {
let mut ranges = Vec::new();
let mut start: Option<usize> = None;
for (i, slot) in slots.iter().enumerate().take(CLUSTER_SLOTS) {
let owned = matches!(*slot, Some(o) if o == owner);
match (start, owned) {
(None, true) => start = Some(i),
(Some(s), false) => {
ranges.push((s, i - 1));
start = None;
}
_ => {}
}
}
if let Some(s) = start {
ranges.push((s, CLUSTER_SLOTS - 1));
}
ranges
}
fn require_cluster_mode(state: &ClusterState) -> Option<Vec<u8>> {
if !state.enabled {
Some(resp_error("ERR This instance has cluster support disabled"))
} else {
None
}
}
fn cmd_addslots(ctx: &mut Ctx) -> Vec<u8> {
let (state, cmd): (&ClusterState, &[&[u8]]) = (ctx.cluster, &ctx.cmd);
if let Some(err) = require_cluster_mode(state) {
return err;
}
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'cluster|addslots' command");
}
let mut slots: Vec<u16> = Vec::with_capacity(cmd.len() - 2);
for arg in &cmd[2..] {
match parse_slot_arg(arg) {
Ok(s) => slots.push(s),
Err(e) => return e,
}
}
if let Err(e) = state.check_slots_claimable(&slots) {
return resp_error(&format!("ERR {e}"));
}
if let Some(refused) = before_slots_come(ctx, &slots, "ADDSLOTS") {
return refused;
}
let state: &ClusterState = ctx.cluster;
if let Err(e) = state.claim_slots(&slots) {
return resp_error(&format!("ERR {e}"));
}
if let Err(e) = state.save_to_disk() {
return resp_error(&format!(
"ERR ADDSLOTS persisted in memory but disk save failed: {e}"
));
}
resp_simple("OK")
}
fn cmd_delslots(state: &ClusterState, cmd: &[&[u8]]) -> Vec<u8> {
if let Some(err) = require_cluster_mode(state) {
return err;
}
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'cluster|delslots' command");
}
let mut slots: Vec<u16> = Vec::with_capacity(cmd.len() - 2);
for arg in &cmd[2..] {
match parse_slot_arg(arg) {
Ok(s) => slots.push(s),
Err(e) => return e,
}
}
{
let mut seen = std::collections::HashSet::with_capacity(slots.len());
for &s in &slots {
if !seen.insert(s) {
return resp_error(&format!("ERR Slot {s} specified multiple times"));
}
}
}
if let Err(e) = state.release_slots(&slots) {
return resp_error(&format!("ERR {e}"));
}
if let Err(e) = state.save_to_disk() {
return resp_error(&format!(
"ERR DELSLOTS persisted in memory but disk save failed: {e}"
));
}
resp_simple("OK")
}
fn cmd_addslotsrange(ctx: &mut Ctx) -> Vec<u8> {
let (state, cmd): (&ClusterState, &[&[u8]]) = (ctx.cluster, &ctx.cmd);
if let Some(err) = require_cluster_mode(state) {
return err;
}
if cmd.len() < 4 || !(cmd.len() - 2).is_multiple_of(2) {
return resp_error("ERR wrong number of arguments for 'cluster|addslotsrange' command");
}
let mut ranges: Vec<(u16, u16)> = Vec::new();
let mut i = 2;
while i + 1 < cmd.len() {
let start = match parse_slot_arg(cmd[i]) {
Ok(s) => s,
Err(e) => return e,
};
let end = match parse_slot_arg(cmd[i + 1]) {
Ok(s) => s,
Err(e) => return e,
};
if start > end {
return resp_error(&format!(
"ERR start slot number {start} is greater than end slot number {end}"
));
}
ranges.push((start, end));
i += 2;
}
let slots: Vec<u16> = ranges
.iter()
.flat_map(|&(start, end)| start..=end)
.collect();
if let Err(e) = state.check_slots_claimable(&slots) {
return resp_error(&format!("ERR {e}"));
}
if let Some(refused) = before_slots_come(ctx, &slots, "ADDSLOTSRANGE") {
return refused;
}
let state: &ClusterState = ctx.cluster;
if let Err(e) = state.claim_slots(&slots) {
return resp_error(&format!("ERR {e}"));
}
if let Err(e) = state.save_to_disk() {
return resp_error(&format!(
"ERR ADDSLOTSRANGE persisted in memory but disk save failed: {e}"
));
}
resp_simple("OK")
}
fn cmd_delslotsrange(state: &ClusterState, cmd: &[&[u8]]) -> Vec<u8> {
if let Some(err) = require_cluster_mode(state) {
return err;
}
if cmd.len() < 4 || !(cmd.len() - 2).is_multiple_of(2) {
return resp_error("ERR wrong number of arguments for 'cluster|delslotsrange' command");
}
let mut ranges: Vec<(u16, u16)> = Vec::new();
let mut i = 2;
while i + 1 < cmd.len() {
let start = match parse_slot_arg(cmd[i]) {
Ok(s) => s,
Err(e) => return e,
};
let end = match parse_slot_arg(cmd[i + 1]) {
Ok(s) => s,
Err(e) => return e,
};
if start > end {
return resp_error(&format!("ERR Invalid range {start}-{end}"));
}
ranges.push((start, end));
i += 2;
}
let mut slots: Vec<u16> = Vec::new();
let mut seen = vec![false; crate::cluster::CLUSTER_SLOTS];
for (start, end) in ranges {
for s in start..=end {
if std::mem::replace(&mut seen[s as usize], true) {
return resp_error(&format!("ERR Slot {s} specified multiple times"));
}
slots.push(s);
}
}
if let Err(e) = state.release_slots(&slots) {
return resp_error(&format!("ERR {e}"));
}
if let Err(e) = state.save_to_disk() {
return resp_error(&format!(
"ERR DELSLOTSRANGE persisted in memory but disk save failed: {e}"
));
}
resp_simple("OK")
}
fn cmd_flushslots(ctx: &Ctx) -> Vec<u8> {
let state: &ClusterState = ctx.cluster;
if let Some(err) = require_cluster_mode(state) {
return err;
}
{
let _cut = (!crate::command_gate::alone_on_this_thread()).then(crate::write_gate::cut);
let has_keys = ctx
.store
.iter()
.any(|db| db.iter().any(|shard| !crate::read_lock!(shard).is_empty()));
if has_keys {
return resp_error("ERR DB must be empty to perform CLUSTER FLUSHSLOTS.");
}
state.flush_slots();
}
if let Err(e) = state.save_to_disk() {
return resp_error(&format!(
"ERR FLUSHSLOTS persisted in memory but disk save failed: {e}"
));
}
resp_simple("OK")
}
fn cmd_bumpepoch(state: &ClusterState) -> Vec<u8> {
if let Some(err) = require_cluster_mode(state) {
return err;
}
let (bumped, epoch) = state.bump_config_epoch_without_consensus();
if !bumped {
return resp_simple(&format!("STILL {epoch}"));
}
if let Err(e) = state.save_to_disk() {
return resp_error(&format!(
"ERR BUMPEPOCH persisted in memory but disk save failed: {e}"
));
}
resp_simple(&format!("BUMPED {epoch}"))
}
fn cmd_set_config_epoch(state: &ClusterState, cmd: &[&[u8]]) -> Vec<u8> {
if let Some(err) = require_cluster_mode(state) {
return err;
}
if cmd.len() != 3 {
return resp_error("ERR wrong number of arguments for 'cluster|set-config-epoch' command");
}
let new_epoch: i64 = match std::str::from_utf8(cmd[2])
.ok()
.and_then(|s| s.parse().ok())
{
Some(n) => n,
None => return resp_error("ERR value is not an integer or out of range"),
};
if new_epoch < 0 {
return resp_error(&format!("ERR Invalid config epoch specified: {new_epoch}"));
}
if let Err(e) = state.set_my_config_epoch(new_epoch as u64) {
return resp_error(&format!("ERR {e}"));
}
if let Err(e) = state.save_to_disk() {
return resp_error(&format!(
"ERR SET-CONFIG-EPOCH persisted in memory but disk save failed: {e}"
));
}
resp_simple("OK")
}
fn cmd_saveconfig(state: &ClusterState) -> Vec<u8> {
if let Some(err) = require_cluster_mode(state) {
return err;
}
match state.save_to_disk() {
Ok(()) => resp_simple("OK"),
Err(e) => resp_error(&format!("ERR {e}")),
}
}
fn cmd_meet(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
if cmd.len() < 4 || cmd.len() > 5 {
return resp_error("ERR wrong number of arguments for 'cluster|meet' command");
}
let ip = match std::str::from_utf8(cmd[2]) {
Ok(s) => s.to_string(),
Err(_) => return resp_error("ERR invalid IP"),
};
let client_port: u16 = match std::str::from_utf8(cmd[3])
.ok()
.and_then(|s| s.parse().ok())
{
Some(p) => p,
None => return resp_error("ERR invalid port"),
};
let bus_port: u16 = if cmd.len() == 5 {
match std::str::from_utf8(cmd[4])
.ok()
.and_then(|s| s.parse().ok())
{
Some(p) => p,
None => return resp_error("ERR invalid cluster bus port"),
}
} else {
client_port + crate::cluster::bus::BUS_PORT_OFFSET
};
let Some(bus) = ctx.cluster.bus_runtime.get() else {
return resp_error("ERR the cluster bus is not running");
};
let placed =
crate::cluster::bus::dialer::insert_handshake_placeholder(ctx.cluster, &ip, client_port);
let state = std::sync::Arc::clone(ctx.cluster);
bus.spawn(async move {
if let Err(e) =
crate::cluster::bus::dialer::send_meet(Arc::clone(&state), ip.clone(), bus_port).await
{
log_warn!("Cluster: MEET {ip}:{client_port} failed: {e}");
if placed {
crate::cluster::bus::dialer::remove_handshake_placeholder(&state, &ip, client_port);
}
}
});
resp_simple("OK")
}
fn cmd_forget(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
if cmd.len() != 3 {
return resp_error("ERR wrong number of arguments for 'cluster|forget' command");
}
let id = match crate::cluster::node::parse_node_id(cmd[2]) {
Some(id) => id,
None => return resp_error("ERR Invalid node id"),
};
if id == ctx.cluster.myself() {
return resp_error("ERR I tried hard but I can't forget myself...");
}
if ctx.cluster.my_master_id() == Some(id) {
return resp_error("ERR Can't forget my master!");
}
if !ctx.cluster.forget_node(id) {
return resp_error("ERR Unknown node");
}
if let Err(e) = ctx.cluster.save_to_disk() {
return resp_error(&format!(
"ERR FORGET applied in memory but disk save failed: {e}"
));
}
resp_simple("OK")
}
fn cmd_count_failure_reports(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
if cmd.len() != 3 {
return resp_error(
"ERR wrong number of arguments for 'cluster|count-failure-reports' command",
);
}
let id = crate::cluster::node::parse_node_id(cmd[2])
.filter(|id| ctx.cluster.nodes.read().contains_key(id));
let Some(id) = id else {
return resp_error(&format!(
"ERR Unknown node {}",
String::from_utf8_lossy(cmd[2])
));
};
let count = ctx.cluster.failure_report_count(id);
resp_integer(count as i64)
}
fn cmd_links(ctx: &mut Ctx) -> Vec<u8> {
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
let nodes = ctx.cluster.nodes.read();
let mut out: Vec<Vec<u8>> = Vec::new();
for n in nodes.values() {
if n.id == ctx.cluster.myself() || n.flags.contains(crate::cluster::NodeFlags::HANDSHAKE) {
continue;
}
let entry = resp_array(vec![
resp_bulk_str("direction"),
resp_bulk_str("to"),
resp_bulk_str("node"),
resp_bulk_str(crate::cluster::node_id_str(&n.id)),
resp_bulk_str("create-time"),
resp_integer(n.ping_sent_ms as i64),
resp_bulk_str("events"),
resp_bulk_str("rw"),
resp_bulk_str("send-buffer-allocated"),
resp_integer(0),
resp_bulk_str("send-buffer-used"),
resp_integer(0),
]);
out.push(entry);
}
resp_array(out)
}
fn cmd_replicas(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
if cmd.len() != 3 {
return resp_error("ERR wrong number of arguments");
}
let master_id = match crate::cluster::node::parse_node_id(cmd[2]) {
Some(id) => id,
None => return resp_error("ERR Invalid node id"),
};
let nodes = ctx.cluster.nodes.read();
if !nodes.contains_key(&master_id) {
return resp_error("ERR Unknown node");
}
let mut out = Vec::new();
for n in nodes.values() {
if n.flags.contains(crate::cluster::NodeFlags::REPLICA) && n.master_id == Some(master_id) {
out.push(resp_bulk_str(&format!(
"{} {}:{}@{}{} {} {} {} {} {} connected",
crate::cluster::node_id_str(&n.id),
n.ip,
n.client_facing_port(),
n.cluster_port,
crate::cluster::persist::hostname_suffix(&n.hostname),
format_flags_for_nodes(n.flags),
crate::cluster::node_id_str(&master_id),
n.ping_sent_ms,
n.pong_received_ms,
n.config_epoch,
)));
}
}
resp_array(out)
}
fn cmd_replicate(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
if cmd.len() != 3 {
return resp_error("ERR wrong number of arguments for 'cluster|replicate' command");
}
let master_id = match crate::cluster::node::parse_node_id(cmd[2]) {
Some(id) => id,
None => return resp_error("ERR Invalid node id"),
};
let (master_ip, master_port) = match ctx.cluster.set_replica_of(master_id) {
Ok(v) => v,
Err(e) => return resp_error(&format!("ERR {e}")),
};
if let Err(e) = ctx.cluster.save_to_disk() {
return resp_error(&format!(
"ERR REPLICATE applied in memory but disk save failed: {e}"
));
}
crate::replication::replica_client::ReplicaStarter::from_ctx(ctx).start(master_ip, master_port);
resp_simple("OK")
}
fn cmd_failover(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
let mode = if cmd.len() == 2 {
"default"
} else if cmd.len() == 3 {
match std::str::from_utf8(cmd[2]) {
Ok(s) => match s.to_ascii_uppercase().as_str() {
"FORCE" => "force",
"TAKEOVER" => "takeover",
_ => return resp_error("ERR syntax: CLUSTER FAILOVER [FORCE | TAKEOVER]"),
},
Err(_) => return resp_error("ERR invalid argument"),
}
} else {
return resp_error("ERR wrong number of arguments for 'cluster|failover' command");
};
let master_id = match ctx.cluster.my_master_id() {
Some(id) => id,
None => return resp_error("ERR You should send CLUSTER FAILOVER to a replica"),
};
if !ctx.cluster.nodes.read().contains_key(&master_id) {
return resp_error("ERR Master is unknown. Please use CLUSTER FAILOVER FORCE.");
}
let Some(bus) = ctx.cluster.bus_runtime.get() else {
return resp_error("ERR the cluster bus is not running");
};
match mode {
"takeover" => {
let epoch = ctx.cluster.bump_epoch();
let claimed = ctx.cluster.promote_self(master_id, epoch);
ctx.repl_state.become_master();
ctx.cluster.drop_slots_lost_while_promoting(&claimed);
log_info!("Cluster: Manual TAKEOVER promoted us to master at epoch {epoch}");
let state = Arc::clone(ctx.cluster);
bus.spawn(async move {
crate::cluster::bus::heartbeat::send_one_round(&state).await;
});
resp_simple("OK")
}
"force" => {
let state = Arc::clone(ctx.cluster);
bus.spawn(async move {
crate::cluster::bus::heartbeat::start_forced_election(&state, master_id, None)
.await;
});
resp_simple("OK")
}
_ => {
if !ctx
.repl_state
.slave_link_up
.load(std::sync::atomic::Ordering::Acquire)
{
return resp_error(
"ERR Master is down or failed, please use CLUSTER FAILOVER FORCE",
);
}
let state = Arc::clone(ctx.cluster);
bus.spawn(async move {
if let Err(e) =
crate::cluster::bus::heartbeat::run_manual_failover(state, master_id).await
{
log_warn!("Cluster: Manual failover aborted: {e}");
}
});
resp_simple("OK")
}
}
}
fn cmd_asking(ctx: &mut Ctx) -> Vec<u8> {
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
ctx.client_registry.update(ctx.client_id, |info| {
info.asking = true;
});
resp_simple("OK")
}
fn cmd_readonly(ctx: &mut Ctx) -> Vec<u8> {
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
ctx.client_registry.update(ctx.client_id, |info| {
info.readonly = true;
});
resp_simple("OK")
}
fn cmd_readwrite(ctx: &mut Ctx) -> Vec<u8> {
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
ctx.client_registry.update(ctx.client_id, |info| {
info.readonly = false;
});
resp_simple("OK")
}
fn slot_changed_state() {
crate::pause::routes_moved();
}
fn before_slots_come(ctx: &Ctx, slots: &[u16], what: &str) -> Option<Vec<u8>> {
let env = crate::cluster::migration::Env::from_ctx(ctx);
crate::cluster::migration::delete_before_coming(&env, slots, what, None)
.err()
.map(|e| resp_error(&e))
}
fn cmd_setslot(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
if cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'cluster|setslot' command");
}
let slot: u16 = match parse_slot_arg(cmd[2]) {
Ok(s) => s,
Err(e) => return e,
};
let action = match std::str::from_utf8(cmd[3]) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => return resp_error("ERR invalid action"),
};
match action.as_str() {
"MIGRATING" => {
if cmd.len() != 5 {
return resp_error(
"ERR wrong number of arguments for 'cluster|setslot|migrating' command",
);
}
let dest = match crate::cluster::node::parse_node_id(cmd[4]) {
Some(id) => id,
None => return resp_error("ERR Invalid node id"),
};
if let Err(e) = ctx.cluster.set_migrating(slot, dest) {
return resp_error(&format!("ERR {e}"));
}
slot_changed_state();
drop(crate::write_gate::cut());
let _ = ctx.cluster.save_to_disk();
resp_simple("OK")
}
"IMPORTING" => {
if cmd.len() != 5 {
return resp_error(
"ERR wrong number of arguments for 'cluster|setslot|importing' command",
);
}
let src = match crate::cluster::node::parse_node_id(cmd[4]) {
Some(id) => id,
None => return resp_error("ERR Invalid node id"),
};
if let Some(refused) = before_slots_come(ctx, &[slot], "SETSLOT IMPORTING") {
return refused;
}
if let Err(e) = ctx.cluster.set_importing(slot, src) {
return resp_error(&format!("ERR {e}"));
}
slot_changed_state();
let _ = ctx.cluster.save_to_disk();
resp_simple("OK")
}
"STABLE" => {
if cmd.len() != 4 {
return resp_error(
"ERR wrong number of arguments for 'cluster|setslot|stable' command",
);
}
ctx.cluster.clear_migration(slot);
slot_changed_state();
let _ = ctx.cluster.save_to_disk();
resp_simple("OK")
}
"NODE" => {
if cmd.len() != 5 {
return resp_error(
"ERR wrong number of arguments for 'cluster|setslot|node' command",
);
}
let new_owner = match crate::cluster::node::parse_node_id(cmd[4]) {
Some(id) => id,
None => return resp_error("ERR Invalid node id"),
};
let _gate = if new_owner != ctx.cluster.myself() {
#[cfg(feature = "lua")]
let overrun = crate::commands::lua::running_script_is_over_its_time_limit;
#[cfg(not(feature = "lua"))]
let overrun = || false;
match crate::command_gate::enter_unless(
std::time::Duration::from_millis(10),
overrun,
) {
Some(gate) => Some(gate),
None => {
return resp_error(
"BUSY Redis is busy running a script. You can only call SCRIPT KILL \
or SHUTDOWN NOSAVE.",
);
}
}
} else {
None
};
if new_owner != ctx.cluster.myself()
&& ctx.cluster.owns_slot(slot)
&& slot_has_keys(ctx, slot)
{
return resp_error(&format!(
"ERR Can't assign hashslot {slot} to a different node while I still hold \
keys for this hash slot."
));
}
if new_owner == ctx.cluster.myself()
&& let Some(refused) = before_slots_come(ctx, &[slot], "SETSLOT NODE")
{
return refused;
}
if let Err(e) = ctx.cluster.finalize_slot(slot, new_owner) {
return resp_error(&format!("ERR {e}"));
}
slot_changed_state();
let _ = ctx.cluster.save_to_disk();
resp_simple("OK")
}
other => resp_error(&format!("ERR Unknown SETSLOT subcommand '{other}'")),
}
}
fn cmd_migration(ctx: &mut Ctx) -> Vec<u8> {
use crate::cluster::migration;
let cmd = &ctx.cmd;
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'cluster|migration' command");
}
let registry = &ctx.cluster.slot_migrations;
let action = String::from_utf8_lossy(cmd[2]).to_ascii_uppercase();
let selector = |args: &[&[u8]]| -> Result<Option<String>, Vec<u8>> {
match args {
[all] if all.eq_ignore_ascii_case(b"ALL") => Ok(None),
[id, task] if id.eq_ignore_ascii_case(b"ID") => {
Ok(Some(String::from_utf8_lossy(task).into_owned()))
}
_ => Err(resp_error("ERR syntax error")),
}
};
match action.as_str() {
"IMPORT" => {
let ranges = match migration::parse_ranges(&cmd[3..]) {
Ok(r) => r,
Err(e) => return resp_error(&format!("ERR {e}")),
};
match migration::start_import(migration::Env::from_ctx(ctx), ranges) {
Ok(id) => resp_bulk_str(&id),
Err(e) => resp_error(&format!("ERR {e}")),
}
}
"CANCEL" => match selector(&cmd[3..]) {
Ok(id) => resp_integer(registry.cancel(id.as_deref()) as i64),
Err(e) => e,
},
"STATUS" => {
let id = if cmd.len() == 3 {
None
} else {
match selector(&cmd[3..]) {
Ok(id) => id,
Err(e) => return e,
}
};
let resp = crate::commands::handler::effective_resp_for_reply(ctx);
let text = |s: &str| resp_bulk_str(s);
let number = |n: u64| resp_integer(n.min(i64::MAX as u64) as i64);
let tasks: Vec<Vec<u8>> = registry
.all()
.iter()
.filter(|task| id.as_deref().is_none_or(|id| task.id == id))
.map(|task| {
resp_map_for(
resp,
vec![
text("id"),
text(&task.id),
text("slots"),
text(&migration::ranges_text(&task.ranges)),
text("source"),
text(node_id_str(&task.source)),
text("dest"),
text(node_id_str(&task.dest)),
text("operation"),
text(match task.operation {
migration::Operation::Import => "import",
migration::Operation::Migrate => "migrate",
}),
text("state"),
text(task.state.name()),
text("last_error"),
text(&task.last_error),
text("retries"),
number(task.retries),
text("create_time"),
number(task.create_time_ms),
text("start_time"),
number(task.start_time_ms),
text("end_time"),
number(task.end_time_ms),
text("write_pause_ms"),
number(task.write_pause_ms),
text("capture_pause_ms"),
number(task.capture_pause_ms),
],
)
})
.collect();
resp_array(tasks)
}
other => resp_error(&format!(
"ERR unknown CLUSTER MIGRATION subcommand '{other}'"
)),
}
}
fn cmd_syncslots(ctx: &mut Ctx) -> Vec<u8> {
use crate::cluster::migration;
if ctx.cmd.len() < 4 {
return resp_error("ERR wrong number of arguments for 'cluster|syncslots' command");
}
let action = String::from_utf8_lossy(ctx.cmd[2]).to_ascii_uppercase();
let task_id = String::from_utf8_lossy(ctx.cmd[3]).into_owned();
let done = |result: Result<(), String>| match result {
Ok(()) => resp_simple("OK"),
Err(e) => resp_error(&format!("ERR {e}")),
};
match action.as_str() {
"START" => {
if ctx.cmd.len() < 7 {
return resp_error("ERR syntax error");
}
let Some(dest) = crate::cluster::node::parse_node_id(ctx.cmd[4]) else {
return resp_error("ERR Invalid node id");
};
let ranges = match migration::parse_ranges(&ctx.cmd[5..]) {
Ok(r) => r,
Err(e) => return resp_error(&format!("ERR {e}")),
};
done(migration::start_source(
migration::Env::from_ctx(ctx),
&task_id,
dest,
ranges,
))
}
"CANCEL" => {
ctx.cluster.slot_migrations.cancel(Some(&task_id));
resp_simple("OK")
}
"TAKEOVER" => done(migration::take_over(ctx.cluster, &task_id, ctx.client_id)),
"FAIL" => {
let reason = ctx
.cmd
.get(4)
.map(|r| String::from_utf8_lossy(r).into_owned())
.unwrap_or_default();
let mut rest: &[&[u8]] = ctx.cmd.get(5..).unwrap_or_default();
let mut from = None;
if let [head @ .., word, id] = rest
&& word.eq_ignore_ascii_case(b"FROM")
{
let Some(id) = crate::cluster::node::parse_node_id(id) else {
return resp_error("ERR Invalid node id");
};
from = Some(id);
rest = head;
}
let ranges = if rest.is_empty() {
Vec::new()
} else {
match migration::parse_ranges(rest) {
Ok(r) => r,
Err(e) => return resp_error(&format!("ERR {e}")),
}
};
done(migration::source_failed(
ctx.cluster,
&task_id,
&reason,
&ranges,
from,
))
}
"APPLY" => syncslots_apply(ctx, &task_id),
other => resp_error(&format!(
"ERR unknown CLUSTER SYNCSLOTS subcommand '{other}'"
)),
}
}
fn syncslots_apply(ctx: &mut Ctx, task_id: &str) -> Vec<u8> {
use crate::cluster::migration;
if ctx.cmd.len() < 5 {
return resp_error("ERR syntax error");
}
if let Err(e) = migration::accept_apply(ctx.cluster, task_id, ctx.client_id) {
return resp_error(&format!("ERR {e}"));
}
let inner: Vec<&[u8]> = ctx.cmd[4..].to_vec();
let name = String::from_utf8_lossy(inner[0]).to_ascii_uppercase();
if !crate::replication::command_mutates_for_replication(&name, &inner) {
return resp_error("ERR only writes can be applied to an importing slot");
}
let Some(task) = ctx.cluster.slot_migrations.get(task_id) else {
return resp_error("ERR no such import in progress");
};
let keys = crate::keyspec::key_positions(&name, &inner);
let inside = !keys.is_empty()
&& keys
.iter()
.all(|pos| migration::in_ranges(&task.ranges, key_hash_slot(inner[pos])));
if !inside {
return resp_error("ERR the command's keys are not in the importing slots");
}
let saved_cmd = std::mem::replace(&mut ctx.cmd, inner);
let saved_bypass = std::mem::replace(&mut ctx.bypass_cluster_check, true);
let result = {
let _command = crate::command_gate::enter();
let _gate = crate::write_gate::enter();
let _order = crate::write_order::lock_keys(
*ctx.selected_db,
crate::keyspec::key_positions(&name, &ctx.cmd)
.iter()
.map(|pos| ctx.cmd[pos]),
);
let result = crate::commands::handler::dispatch_command_handlers(ctx, &name)
.unwrap_or_else(|| resp_error("ERR unknown command"));
crate::commands::handler::apply_write_side_effects(ctx, &name, &result);
result
};
ctx.cmd = saved_cmd;
ctx.bypass_cluster_check = saved_bypass;
if result.starts_with(b"-") {
result
} else {
resp_simple("OK")
}
}
fn slot_has_keys(ctx: &Ctx, slot: u16) -> bool {
ctx.store[*ctx.selected_db].iter().any(|shard| {
crate::read_lock!(shard)
.keys()
.any(|k| key_hash_slot(k) == slot)
})
}
pub fn handle_migrate(ctx: &mut Ctx, name: &str) -> Option<Vec<u8>> {
if name != "MIGRATE" {
return None;
}
Some(off_the_runtime(|| migrate(ctx)))
}
fn off_the_runtime<R>(f: impl FnOnce() -> R) -> R {
match tokio::runtime::Handle::try_current() {
Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
tokio::task::block_in_place(f)
}
_ => f(),
}
}
struct Outgoing {
key: crate::store::Key,
payload: Vec<u8>,
expires_at_ms: u64,
}
fn migrate(ctx: &mut Ctx) -> Vec<u8> {
use std::io::Write;
use std::net::ToSocketAddrs;
use std::time::Duration;
let cmd = &ctx.cmd;
if cmd.len() < 6 {
return resp_error("ERR wrong number of arguments for 'migrate' command");
}
let Ok(host) = std::str::from_utf8(cmd[1]) else {
return resp_error("ERR invalid host");
};
let Some(port) = std::str::from_utf8(cmd[2])
.ok()
.and_then(|s| s.parse::<u16>().ok())
else {
return resp_error("ERR invalid port");
};
let Some(dest_db) = std::str::from_utf8(cmd[4])
.ok()
.and_then(|s| s.parse::<usize>().ok())
else {
return resp_error("ERR value is not an integer or out of range");
};
let timeout = match std::str::from_utf8(cmd[5])
.ok()
.and_then(|s| s.parse::<i64>().ok())
{
Some(ms) if ms > 0 => Duration::from_millis(ms as u64),
Some(_) => Duration::from_secs(1),
None => return resp_error("ERR value is not an integer or out of range"),
};
let mut copy = false;
let mut replace = false;
let mut auth: Option<Vec<Vec<u8>>> = None;
let mut keys: Vec<&[u8]> = Vec::new();
let mut i = 6;
while i < cmd.len() {
let option = cmd[i].to_ascii_uppercase();
match option.as_slice() {
b"COPY" => copy = true,
b"REPLACE" => replace = true,
b"AUTH" => {
let Some(password) = cmd.get(i + 1) else {
return resp_error("ERR syntax error");
};
auth = Some(vec![b"AUTH".to_vec(), password.to_vec()]);
i += 1;
}
b"AUTH2" => {
let (Some(user), Some(password)) = (cmd.get(i + 1), cmd.get(i + 2)) else {
return resp_error("ERR syntax error");
};
auth = Some(vec![b"AUTH".to_vec(), user.to_vec(), password.to_vec()]);
i += 2;
}
b"KEYS" => {
if !cmd[3].is_empty() {
return resp_error(
"ERR When using MIGRATE KEYS option, the key argument must be set to \
the empty string",
);
}
keys = cmd[i + 1..].to_vec();
break;
}
_ => return resp_error("ERR syntax error"),
}
i += 1;
}
if keys.is_empty() {
if cmd[3].is_empty() {
return resp_error("ERR syntax error");
}
keys.push(cmd[3]);
}
let db = *ctx.selected_db;
let _holding = if copy {
None
} else {
hold_while_moving(db, &keys)
};
if !copy && !ctx.apply_replication && ctx.repl_state.is_slave() {
return resp_error("READONLY You can't write against a read only replica.");
}
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let mut outgoing: Vec<Outgoing> = Vec::with_capacity(keys.len());
for &key in &keys {
if crate::commands::helpers::lazy_expire_key(ctx.store, db, key) {
continue;
}
let (value, expires_at_ms) = {
let shard = crate::store::get_shard(&ctx.store[db], key);
match crate::read_lock!(shard).get_expiring(key) {
Some((v, expires)) => (v.to_value(), expires.unwrap_or(0)),
None => continue,
}
};
if expires_at_ms != 0 && expires_at_ms <= now_ms {
continue;
}
let payload = match crate::snapshot::dump_payload(&value) {
Ok(p) => p,
Err(e) => {
let key = String::from_utf8_lossy(key);
return resp_error(&format!("ERR could not serialise '{key}': {e}"));
}
};
outgoing.push(Outgoing {
key: crate::store::Key::new(key),
payload,
expires_at_ms,
});
}
if outgoing.is_empty() {
return resp_simple("NOKEY");
}
let addr = format!("{host}:{port}");
let Some(socket_addr) = addr.to_socket_addrs().ok().and_then(|mut it| it.next()) else {
return resp_error(&format!("IOERR could not resolve {addr}"));
};
let mut sock = match crate::node_tls::connect_node(host, &socket_addr, timeout) {
Ok((stream, _)) => stream,
Err(e) => {
return resp_error(&format!(
"IOERR error or timeout connecting to the client: {e}"
));
}
};
let mut pipeline = Vec::new();
let mut preamble: Vec<&str> = Vec::new();
if let Some(auth) = &auth {
pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(auth));
preamble.push("AUTH");
}
pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
b"SELECT".to_vec(),
dest_db.to_string().into_bytes(),
]));
preamble.push("SELECT");
for item in &outgoing {
pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
b"ASKING".to_vec()
]));
let mut restore = vec![
b"RESTORE".to_vec(),
item.key.as_bytes().to_vec(),
item.expires_at_ms.to_string().into_bytes(),
item.payload.clone(),
];
if replace {
restore.push(b"REPLACE".to_vec());
}
if item.expires_at_ms != 0 {
restore.push(b"ABSTTL".to_vec());
}
pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&restore));
}
if let Err(e) = sock.write_all(&pipeline).and_then(|()| sock.flush()) {
return resp_error(&format!(
"IOERR error or timeout writing to target instance: {e}"
));
}
let mut reader = std::io::BufReader::new(sock);
for what in preamble {
match read_status_reply(&mut reader) {
Ok(Ok(())) => {}
Ok(Err(reply)) => {
return resp_error(&format!(
"ERR Target instance replied with error to {what}: {reply}"
));
}
Err(e) => {
return resp_error(&format!(
"IOERR error or timeout reading to target instance: {e}"
));
}
}
}
let mut moved: Vec<&Outgoing> = Vec::with_capacity(outgoing.len());
let mut failure: Option<String> = None;
for item in &outgoing {
let asking = read_status_reply(&mut reader);
let restore = match asking {
Err(e) => Err(e),
Ok(_) => read_status_reply(&mut reader),
};
match restore {
Ok(Ok(())) => moved.push(item),
Ok(Err(reply)) => {
failure.get_or_insert(format!("ERR Target instance replied with error: {reply}"));
}
Err(e) => {
failure.get_or_insert(format!(
"IOERR error or timeout reading to target instance: {e}"
));
break;
}
}
}
if copy || moved.is_empty() {
return match failure {
None => resp_simple("OK"),
Some(error) => resp_error(&error),
};
}
crate::aof::failpoint("migrate-before-delete");
let not_deleted = delete_moved(ctx, db, &moved, _holding.is_some());
let taken_back = !not_deleted.kept.is_empty()
&& only_here(ctx, ¬_deleted.kept)
&& take_back_copies(&mut reader, ¬_deleted.kept);
let written: Vec<&[u8]> = not_deleted
.kept
.iter()
.chain(¬_deleted.gone)
.copied()
.collect();
drop(not_deleted);
if failure.is_none() && !written.is_empty() {
failure = Some(written_while_moving(&written, &addr, taken_back));
}
match failure {
None => resp_simple("OK"),
Some(error) => resp_error(&error),
}
}
struct MoveHold {
_order: crate::write_order::OrderGuard,
_gate: crate::write_gate::WriteGuard,
_marked: crate::key_moves::Marked,
}
fn hold_while_moving(db: usize, keys: &[&[u8]]) -> Option<MoveHold> {
if crate::command_gate::alone_on_this_thread() || crate::write_gate::held_by_this_thread() {
return None;
}
while crate::pause::handoff() {
crate::pause::wait_out_handoff();
}
let marked = crate::key_moves::mark(db, keys.iter().map(|key| key.to_vec()).collect());
drop(crate::write_gate::cut());
let gate = crate::write_gate::enter();
let order = crate::write_order::lock_keys(db, keys.iter().copied());
Some(MoveHold {
_order: order,
_gate: gate,
_marked: marked,
})
}
const FIELD_TIME_SLACK_MS: u64 = 5;
fn same_hash_but_for_expired_fields(value: &crate::types::KiviDBValue, payload: &[u8]) -> bool {
use crate::types::{HashInner, KiviDBValue};
let (KiviDBValue::HashEx(now), Some(KiviDBValue::HashEx(then))) =
(value, crate::snapshot::restore_payload(payload))
else {
return false;
};
let (now, then) = (now.read(), then.read());
let soon = crate::types::field_now().saturating_add(FIELD_TIME_SLACK_MS);
let same_time = |a: Option<&u64>, b: Option<&u64>| a == b;
let held_by = |a: &HashInner, b: &HashInner| {
a.fields.iter().all(|(field, val)| {
let time = a.expiries.get(field);
time.is_some_and(|time| *time <= soon)
|| (b.fields.get(field.as_str()) == Some(val)
&& same_time(time, b.expiries.get(field)))
})
};
held_by(&now, &then) && held_by(&then, &now)
}
fn delete_moved<'a>(ctx: &Ctx, db: usize, moved: &[&'a Outgoing], held: bool) -> NotDeleted<'a> {
let nested = crate::write_gate::held_by_this_thread();
let mut gate = crate::write_gate::enter();
while !nested && !ctx.apply_replication && crate::pause::handoff() {
drop(gate);
crate::pause::wait_out_handoff();
gate = crate::write_gate::enter();
}
let order = crate::write_order::lock_keys(db, moved.iter().map(|item| item.key.as_bytes()));
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let mut del: Vec<Vec<u8>> = vec![b"DEL".to_vec()];
let mut kept: Vec<&'a [u8]> = Vec::new();
let mut gone: Vec<&'a [u8]> = Vec::new();
for item in moved {
let key = item.key.as_bytes();
let shard = crate::store::get_shard(&ctx.store[db], key);
let removal = {
let mut map = crate::write_lock!(shard);
let expires_at_ms = map.expires(key).unwrap_or(0);
map.remove_if(key, |value| {
let value = value.to_value();
expires_at_ms == item.expires_at_ms
&& (crate::snapshot::dump_payload(&value).is_ok_and(|now| now == item.payload)
|| (held && same_hash_but_for_expired_fields(&value, &item.payload)))
})
};
match removal {
crate::store::Removal::Taken(taken) => {
drop(taken);
crate::vector::maybe_unindex(ctx.index_store, db, key);
del.push(key.to_vec());
}
crate::store::Removal::Kept => kept.push(key),
crate::store::Removal::Absent => {
let expired = item.expires_at_ms != 0 && item.expires_at_ms <= now_ms;
if !expired {
gone.push(key);
}
}
}
}
if del.len() > 1 && ctx.cluster.enabled {
crate::pause::routes_moved();
}
crate::aof::failpoint("migrate-deleted");
if del.len() > 1 && crate::replication::write_is_observed(ctx) {
crate::replication::replicate_one_write(ctx, &del);
}
drop(gate);
NotDeleted {
kept,
gone,
_order: order,
}
}
struct NotDeleted<'a> {
kept: Vec<&'a [u8]>,
gone: Vec<&'a [u8]>,
_order: crate::write_order::OrderGuard,
}
fn only_here(ctx: &Ctx, keys: &[&[u8]]) -> bool {
ctx.cluster.enabled
&& keys
.iter()
.all(|key| ctx.cluster.owns_slot(crate::cluster::key_hash_slot(key)))
}
fn take_back_copies(
reader: &mut std::io::BufReader<Box<dyn crate::node_tls::ReadWrite>>,
keys: &[&[u8]],
) -> bool {
use std::io::Write;
let mut pipeline = Vec::new();
for key in keys {
pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
b"ASKING".to_vec()
]));
pipeline.extend_from_slice(&crate::resp::write::encode_resp_command(&[
b"DEL".to_vec(),
key.to_vec(),
]));
}
let sock = reader.get_mut();
if sock
.write_all(&pipeline)
.and_then(|()| sock.flush())
.is_err()
{
return false;
}
(0..keys.len() * 2).all(|_| read_status_reply(reader).is_ok())
}
fn written_while_moving(keys: &[&[u8]], addr: &str, taken_back: bool) -> String {
const SHOWN: usize = 5;
let mut names = keys
.iter()
.take(SHOWN)
.map(|k| format!("'{}'", String::from_utf8_lossy(k)))
.collect::<Vec<_>>()
.join(", ");
if keys.len() > SHOWN {
names.push_str(&format!(" and {} more", keys.len() - SHOWN));
}
let copies = if taken_back {
format!("The copies sent to {addr} were deleted there; MIGRATE them again")
} else {
format!("The copy sent to {addr} may be older; MIGRATE them again with REPLACE")
};
format!(
"TRYAGAIN {} written while being migrated, and kept here: {names}. {copies}",
if keys.len() == 1 {
"a key was"
} else {
"keys were"
}
)
}
fn read_status_reply(
reader: &mut std::io::BufReader<Box<dyn crate::node_tls::ReadWrite>>,
) -> std::io::Result<Result<(), String>> {
use std::io::BufRead;
let mut line = String::new();
if reader.read_line(&mut line)? == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"connection closed by target instance",
));
}
let line = line.trim_end_matches(['\r', '\n']);
Ok(match line.strip_prefix('+') {
Some(_) => Ok(()),
None => Err(line.trim_start_matches('-').to_string()),
})
}
fn cmd_reset(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
let hard = if cmd.len() == 2 {
false } else if cmd.len() == 3 {
match std::str::from_utf8(cmd[2]) {
Ok(s) => match s.to_ascii_uppercase().as_str() {
"HARD" => true,
"SOFT" => false,
_ => return resp_error("ERR syntax: CLUSTER RESET [HARD | SOFT]"),
},
Err(_) => return resp_error("ERR invalid argument"),
}
} else {
return resp_error("ERR wrong number of arguments for 'cluster|reset' command");
};
let cut = (!crate::command_gate::alone_on_this_thread()).then(crate::write_gate::cut);
if ctx.cluster.my_master_id().is_none() && !hard {
let has_keys = ctx
.store
.iter()
.any(|db| db.iter().any(|shard| !crate::read_lock!(shard).is_empty()));
if has_keys {
return resp_error(
"ERR CLUSTER RESET can't be called with master nodes containing keys",
);
}
}
if hard {
let new_id = ctx.cluster.hard_reset();
let flushed = crate::store::clear_store(ctx.store);
let indexes = crate::vector::drop_all_indexes(ctx.index_store);
crate::vector::drop_all_dicts(ctx.dict_store);
crate::store::clear_ts_label_index(ctx.ts_index);
if flushed.should_trim() || indexes > 0 {
crate::commands::memory::purge_allocator();
}
log_info!(
"Cluster: Hard reset performed ā new node ID {}",
node_id_str(&new_id)
);
} else {
ctx.cluster.soft_reset();
log_info!("Cluster: Soft reset performed");
}
drop(cut);
ctx.repl_state.become_master();
resp_simple("OK")
}
fn cmd_myshardid(ctx: &mut Ctx) -> Vec<u8> {
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
let shard_id = match ctx.cluster.my_master_id() {
Some(master_id) => master_id, None => ctx.cluster.myself(), };
resp_bulk_str(crate::cluster::node_id_str(&shard_id))
}
fn cmd_slot_stats(ctx: &mut Ctx) -> Vec<u8> {
let cmd = &ctx.cmd;
if let Some(err) = require_cluster_mode(ctx.cluster) {
return err;
}
if cmd.len() < 3 {
return resp_error("ERR wrong number of arguments for 'cluster|slot-stats' command");
}
let mode = match std::str::from_utf8(cmd[2]) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => return resp_error("ERR syntax error"),
};
let key_counts = key_counts_per_slot(&ctx.store[*ctx.selected_db], ctx.cluster);
let entries: Vec<(u16, u64)> = match mode.as_str() {
"SLOTSRANGE" => {
if cmd.len() != 5 {
return resp_error("ERR syntax: CLUSTER SLOT-STATS SLOTSRANGE start-slot end-slot");
}
let start: u16 = match parse_slot_arg(cmd[3]) {
Ok(s) => s,
Err(e) => return e,
};
let end: u16 = match parse_slot_arg(cmd[4]) {
Ok(s) => s,
Err(e) => return e,
};
if start > end {
return resp_error(&format!("ERR Invalid range {start}-{end}"));
}
(start..=end)
.filter(|s| ctx.cluster.owns_slot(*s))
.map(|s| (s, key_counts.get(&s).copied().unwrap_or(0)))
.collect()
}
"ORDERBY" => {
if cmd.len() < 4 {
return resp_error(
"ERR syntax: CLUSTER SLOT-STATS ORDERBY metric [LIMIT n] [ASC | DESC]",
);
}
let metric = match std::str::from_utf8(cmd[3]) {
Ok(s) => s.to_ascii_lowercase(),
Err(_) => return resp_error("ERR invalid metric"),
};
if metric != "key-count" {
return resp_error(&format!(
"ERR ORDERBY metric '{metric}' not supported (use 'key-count')"
));
}
let mut limit: usize = 16384;
let mut descending = true;
let mut i = 4;
while i < cmd.len() {
let arg = match std::str::from_utf8(cmd[i]) {
Ok(s) => s.to_ascii_uppercase(),
Err(_) => return resp_error("ERR syntax error"),
};
match arg.as_str() {
"LIMIT" => {
i += 1;
if i >= cmd.len() {
return resp_error("ERR LIMIT requires a value");
}
limit = match std::str::from_utf8(cmd[i])
.ok()
.and_then(|s| s.parse().ok())
{
Some(n) => n,
None => return resp_error("ERR invalid LIMIT"),
};
}
"ASC" => descending = false,
"DESC" => descending = true,
other => {
return resp_error(&format!("ERR unexpected token '{other}'"));
}
}
i += 1;
}
let mut all: Vec<(u16, u64)> = (0..crate::cluster::CLUSTER_SLOTS as u16)
.filter(|s| ctx.cluster.owns_slot(*s))
.map(|s| (s, key_counts.get(&s).copied().unwrap_or(0)))
.collect();
if descending {
all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
} else {
all.sort_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)));
}
all.truncate(limit);
all
}
other => return resp_error(&format!("ERR Unknown subcommand '{other}'")),
};
let resp_entries: Vec<Vec<u8>> = entries
.into_iter()
.map(|(slot, key_count)| {
resp_array(vec![
resp_integer(slot as i64),
resp_array(vec![
resp_bulk_str("key-count"),
resp_integer(key_count as i64),
resp_bulk_str("cpu-usec"),
resp_integer(0),
resp_bulk_str("network-bytes-in"),
resp_integer(0),
resp_bulk_str("network-bytes-out"),
resp_integer(0),
]),
])
})
.collect();
resp_array(resp_entries)
}
pub(crate) fn key_counts_per_slot(
db: &crate::store::Db,
cluster: &ClusterState,
) -> std::collections::HashMap<u16, u64> {
let owned = cluster.owned_slots();
let mut counts: std::collections::HashMap<u16, u64> = std::collections::HashMap::new();
for shard in db.iter() {
let map = crate::read_lock!(shard);
for k in map.keys() {
let slot = key_hash_slot(k);
if owned[slot as usize] {
*counts.entry(slot).or_insert(0) += 1;
}
}
}
counts
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{HashInner, KiviDBValue};
use std::time::Instant;
fn hash(fields: &[(&str, &str, Option<u64>)]) -> KiviDBValue {
let mut inner = HashInner::new();
for (field, value, time) in fields {
inner
.fields
.insert(field.to_string(), std::sync::Arc::from(value.as_bytes()));
if let Some(time) = time {
inner.expiries.insert(field.to_string(), *time);
}
}
KiviDBValue::HashEx(std::sync::Arc::new(parking_lot::RwLock::new(inner)))
}
fn payload(value: &KiviDBValue) -> Vec<u8> {
crate::snapshot::dump_payload(value).unwrap()
}
#[test]
fn a_hash_whose_field_is_about_to_expire_is_unchanged() {
let now = crate::types::field_now();
let later = now + 3_600_000;
let sent = payload(&hash(&[
("kept", "1", None),
("timed", "2", Some(later)),
("brief", "3", Some(now - 1)),
]));
let here = hash(&[
("kept", "1", None),
("timed", "2", Some(later)),
("brief", "3", Some(now + 3)),
]);
assert!(same_hash_but_for_expired_fields(&here, &sent));
let sent = payload(&hash(&[("kept", "1", None), ("brief", "3", Some(now + 3))]));
let here = hash(&[("kept", "1", None)]);
assert!(same_hash_but_for_expired_fields(&here, &sent));
}
#[test]
fn a_hash_written_while_it_travelled_is_not_the_same() {
let later = crate::types::field_now() + 3_600_000;
let sent = payload(&hash(&[("a", "1", None), ("b", "2", Some(later))]));
for here in [
hash(&[("a", "9", None), ("b", "2", Some(later))]),
hash(&[("a", "1", None), ("b", "9", Some(later))]),
hash(&[("a", "1", None), ("b", "2", Some(later)), ("c", "3", None)]),
hash(&[("a", "1", None)]),
hash(&[("a", "1", None), ("b", "2", None)]),
hash(&[("a", "1", Some(later)), ("b", "2", Some(later))]),
hash(&[("a", "1", None), ("b", "2", Some(later + 1_000))]),
hash(&[("a", "1", None), ("b", "2", Some(later + 1))]),
] {
assert!(!same_hash_but_for_expired_fields(&here, &sent));
}
let here = hash(&[("a", "1", None), ("b", "2", Some(later))]);
assert!(same_hash_but_for_expired_fields(&here, &sent));
}
fn migrate_after_routing(
store: &crate::store::Store,
repl_state: &Arc<crate::replication::ReplState>,
args: &[&str],
) -> Vec<u8> {
use crate::commands::ctx::NoopAofSender;
let lastsave = Arc::new(parking_lot::RwLock::new(0i64));
let (hub_tx, _hub_rx) = tokio::sync::mpsc::unbounded_channel();
let config = Arc::new(crate::config::Config::default());
let started_at = Instant::now();
let index_store = crate::vector::new_index_store();
let dict_store = crate::vector::new_dict_store();
let wait_table = Arc::new(crate::wait_table::WaitTable::new());
let ts_index = crate::store::new_ts_index();
let pubsub = crate::pubsub::PubSubHub::new();
let acl_store = crate::acl::new_acl_store("");
let acl_log = crate::acl::new_acl_log();
let slowlog = crate::slowlog::new_slowlog(u64::MAX, 0);
let latency = crate::latency::new_latency_tracker();
let (compaction_tx, _compaction_rx) = crate::vector::new_compaction_channel();
let cluster = Arc::new(ClusterState::new_disabled());
let client_registry = crate::client_registry::new_client_registry();
let monitor_registry = crate::monitor::new_monitor_registry();
let tracking_table = crate::tracking::new_tracking_table();
let mut selected_db = 0usize;
let mut ctx = Ctx {
cmd: args.iter().map(|a| a.as_bytes()).collect(),
store,
lastsave: &lastsave,
selected_db: &mut selected_db,
aof_tx: &NoopAofSender,
aof_enabled: false,
config: &config,
started_at: &started_at,
index_store: &index_store,
dict_store: &dict_store,
wait_table: &wait_table,
ts_index: &ts_index,
pubsub: &pubsub,
hub_tx: &hub_tx,
repl_state,
watch_registry: &crate::watch::NoopWatchRegistry,
client_id: 0,
client_registry: &client_registry,
resp: 2,
acl_store: &acl_store,
acl_log: &acl_log,
slowlog: &slowlog,
latency: &latency,
compaction_tx: &compaction_tx,
cluster: &cluster,
bypass_cluster_check: false,
apply_replication: false,
skip_write_side_effects: false,
peer_addr: "127.0.0.1:1",
monitor_registry: &monitor_registry,
authenticated_user: "default",
tracking_table: &tracking_table,
blocking: None,
};
handle_migrate(&mut ctx, "MIGRATE").unwrap()
}
#[test]
fn migrate_on_a_node_that_became_a_replica_after_routing_is_refused() {
let _pause = crate::pause::TEST_LOCK.lock();
crate::pause::clear_pause();
let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
destination.set_nonblocking(true).unwrap();
let port = destination.local_addr().unwrap().port().to_string();
let store = crate::store::new_store(1);
let _ = crate::store::get_shard(&store[0], "moving")
.write()
.insert_str("moving", "v");
let has_key = || {
crate::read_lock!(crate::store::get_shard(&store[0], "moving")).contains_key("moving")
};
let args = ["MIGRATE", "127.0.0.1", port.as_str(), "moving", "0", "200"];
let repl_state = Arc::new(crate::replication::ReplState::new_master());
repl_state.become_slave();
let reply = migrate_after_routing(&store, &repl_state, &args);
assert!(
reply.starts_with(b"-READONLY"),
"{}",
String::from_utf8_lossy(&reply)
);
assert!(has_key());
assert!(
destination.accept().is_err(),
"a replica's MIGRATE reached the destination"
);
let repl_state = Arc::new(crate::replication::ReplState::new_master());
let reply = migrate_after_routing(&store, &repl_state, &args);
assert!(
!reply.starts_with(b"-READONLY"),
"{}",
String::from_utf8_lossy(&reply)
);
assert!(destination.accept().is_ok());
assert!(has_key());
}
}