yo_resp/dispatch/server.rs
1//! The connection and server commands.
2//!
3//! None of these touch a key. They are here because a client library sends most
4//! of them before it sends anything else: a driver opens a socket, says `HELLO
5//! 3`, maybe `SELECT 4`, asks `COMMAND DOCS` or `COMMAND COUNT` to build its
6//! own routing table, and only then does any work. A server that answers `GET`
7//! perfectly and `HELLO` badly is a server no client library can talk to, which
8//! is why these land in the same milestone as the string commands rather than
9//! after them.
10//!
11//! The replies were read off a running Redis 8.8 in both protocols. The shapes
12//! are not obvious from the documentation: `HELLO` is a map on RESP3 and the
13//! same pairs flattened on RESP2, `CONFIG GET` is the same, `INFO` is a
14//! verbatim string on RESP3 and a bulk string on RESP2, and the flags in
15//! `COMMAND INFO` are simple strings inside an array rather than bulk strings.
16
17use super::args::{self, Args, is};
18use super::cluster::Migration;
19use super::keyspec::{self, Begin, Find, KeySpec};
20use super::table::{self, Spec};
21use super::{
22 DATABASES, Flow, Server, Session, acl, auth, backup, cpu, debug, multi, notify, persist,
23};
24use crate::proto::Proto;
25use crate::reply::Out;
26use core::fmt::Write;
27use std::time::{SystemTime, UNIX_EPOCH};
28use yo_common::num::parse_i64;
29use yo_common::{Code, Error, Result, glob};
30use yo_kv::Keyspace;
31use yo_kv::access::Policy;
32
33/// What we tell a client we are.
34///
35/// It is a lie and it is a deliberate one. Every client library in the world
36/// branches on this pair to decide which commands exist, and a driver that
37/// reads `yo` here falls back to its oldest code path or refuses to connect.
38/// Divergence D-12 in `divergences.toml` says so, and the honest answer is in
39/// the `yo_version` field of `INFO` next to this one.
40const REPORTED_SERVER: &str = "redis";
41/// The Redis version we answer 100 percent of, which is what `HELLO` reports.
42///
43/// [`super::backup`] writes it into the `redis-ver` aux field of the base file
44/// it produces, so a server told to load one reads the same version out of the
45/// file that a client reads off the connection.
46pub(super) const REPORTED_VERSION: &str = "8.8.0";
47
48/// The settings that are fixed for the life of the process.
49///
50/// `CONFIG SET` accepts a write to one of these that changes nothing and
51/// refuses everything else rather than pretending to have taken it. A client
52/// that sets `appendonly no` on a server that already has no append only file
53/// gets an `OK` and is telling the truth; one that sets `appendonly yes` gets
54/// told it cannot, which is better than an `OK` and no file.
55const SETTINGS: &[(&str, &str)] = &[
56 ("appendonly", "no"),
57 ("appendfsync", "everysec"),
58 // Where `BACKUP` writes, under `dir`. Fixed here where a real server takes
59 // it at startup, because nothing in this build reads it from a file.
60 ("backupdirname", backup::DIR_NAME),
61 ("databases", "16"),
62 ("proto-max-bulk-len", "536870912"),
63 // How much of the command stream a master keeps for a replica that comes
64 // back, which is a compiled in size here and happens to be the size Redis
65 // ships with. Fixed rather than writable because the backlog is one buffer
66 // that is allocated once and resizing it under a replica that is reading
67 // out of it is a change of its own. There is a test below that this number
68 // and `repl::BACKLOG_BYTES` are the same number.
69 ("repl-backlog-size", "1048576"),
70 ("save", ""),
71 ("timeout", "0"),
72];
73
74/// Which number on the size ladder a settings name refers to.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76enum Knob {
77 SetIntsetEntries,
78 SetListpackEntries,
79 SetListpackValue,
80 HashListpackEntries,
81 HashListpackValue,
82 MaxmemorySamples,
83 LfuLogFactor,
84 LfuDecayTime,
85}
86
87/// The settings that move the size ladder, which are the ones that really move.
88///
89/// These decide where a collection stops being a packed blob and becomes an
90/// element table, so they decide what `OBJECT ENCODING` answers, and a client
91/// that reads `OBJECT ENCODING` after setting one of these expects the two to
92/// agree. That is the whole reason they are writable when nothing else here is.
93///
94/// The `ziplist` spellings are the names these had before Redis renamed them
95/// and it still answers to both, so this does too. Two names, one number: a
96/// `CONFIG SET hash-max-ziplist-entries 4` shows up under the listpack name
97/// too, which was checked against 8.10.1 rather than assumed.
98///
99/// Moving one of these leaves every collection that already exists exactly as
100/// it is, and only decides what the next write builds. Redis does the same, and
101/// it is the reason `CONFIG SET set-max-listpack-entries 0` does not rewrite
102/// the keyspace.
103///
104/// The three eviction numbers are in here too, which stretches the name a
105/// little. They belong with these rather than with the immutable settings for
106/// the same reason: a client that sets one and then reads `OBJECT FREQ` or
107/// watches `evicted_keys` expects the two to agree. `maxmemory-samples` says how
108/// many keys a round of sampling looks at, and the two `lfu` numbers set what
109/// the counter under an LFU policy actually measures.
110const LADDER: &[(&str, Knob)] = &[
111 ("hash-max-listpack-entries", Knob::HashListpackEntries),
112 ("hash-max-listpack-value", Knob::HashListpackValue),
113 ("hash-max-ziplist-entries", Knob::HashListpackEntries),
114 ("hash-max-ziplist-value", Knob::HashListpackValue),
115 ("lfu-decay-time", Knob::LfuDecayTime),
116 ("lfu-log-factor", Knob::LfuLogFactor),
117 ("maxmemory-samples", Knob::MaxmemorySamples),
118 ("set-max-intset-entries", Knob::SetIntsetEntries),
119 ("set-max-listpack-entries", Knob::SetListpackEntries),
120 ("set-max-listpack-value", Knob::SetListpackValue),
121];
122
123/// The setting that decides which way the access field on every record is read.
124///
125/// It is on its own rather than in [`SETTINGS`] or [`LADDER`] because it is the
126/// only writable setting that is not a number, and rather than immutable because
127/// it really moves: a client that sets it and then reads `OBJECT FREQ` expects
128/// the two to agree, which is the same argument the size ladder makes.
129///
130/// Setting it changes nothing about the keys already stored. Whatever is in
131/// their access field stays there and means something different from the moment
132/// the policy changes, which is what the `OBJECT FREQ` error text warns about.
133const MAXMEMORY_POLICY: &str = "maxmemory-policy";
134
135/// How many threads are running commands, which is whatever the server was
136/// started with.
137///
138/// Immutable like the settings in [`SETTINGS`] and read from the server rather
139/// than written down next to them, which is the whole reason it is out here: the
140/// number is decided at startup by whoever starts the threads, so the fixed `1`
141/// it used to be was a lie on every server started with more than one. A write
142/// to it is treated the way a write to a fixed setting is, so `CONFIG SET
143/// io-threads` takes the count the server already has and refuses the rest.
144///
145/// `INFO server` reports the same number under `io_threads_active`. Redis means
146/// the configured count by that field rather than the count of threads that have
147/// picked work up, and matching Redis is why the field is there at all.
148const IO_THREADS: &str = "io-threads";
149
150/// How much the server is allowed to hold before it starts evicting.
151///
152/// Also on its own, and for the third different reason. It is not immutable,
153/// it is not on the size ladder and it is the only setting whose value is not a
154/// plain integer: a client writes `maxmemory 100mb` and means a hundred and
155/// four million bytes, so it needs a parser of its own.
156///
157/// Zero means no limit, which is the default and is what makes the check in
158/// front of every write one comparison. Setting it to a number smaller than
159/// what the server is already holding is allowed and is a real thing to do: the
160/// next write that would allocate evicts until it fits or is refused, which is
161/// what the `maxmemory-policy` decides between.
162const MAXMEMORY: &str = "maxmemory";
163
164/// How much the server is allowed to keep on the file before it starts evicting.
165///
166/// The other half of the eviction inversion `14` section 4.1 describes, and the
167/// only setting here that has no counterpart in Redis. `maxmemory` is a limit on
168/// memory, and the right answer to a memory limit on a system with a file under
169/// it is to move data to the file. Throwing data away is the right answer to a
170/// limit on the file, and this is that limit.
171///
172/// Minus one is no limit and is the default, so a server that never sets this
173/// grows until the disk is full and then refuses writes, which is what a
174/// database does. Zero is a real setting and it means the file may hold nothing,
175/// so migration cannot make room and eviction is all that is left, which is
176/// Redis exactly and is the documented setting for a drop in cache.
177const MAXSTORE: &str = "maxstore";
178
179/// Where the server writes, which `BACKUP LIST` answers paths under.
180///
181/// On its own for a fourth reason: it is readable and not writable, and it is
182/// not writable in a way of its own. Redis calls it a protected config, which
183/// means `CONFIG SET dir` is refused with a sentence about protection rather
184/// than about immutability unless the server was started with protected configs
185/// enabled. That distinction is copied, because the two messages are what an
186/// operator reads when a `CONFIG SET` does not take.
187const DIR: &str = "dir";
188
189/// What `SAVE` writes, under [`DIR`].
190///
191/// Protected in the same way and for a weaker version of the same reason: a
192/// server whose file name moved under a running backup script leaves a file
193/// nothing goes looking for. Redis protects it too, so `CONFIG SET dbfilename`
194/// is refused there as well without protected configs turned on.
195const DBFILENAME: &str = "dbfilename";
196
197/// The password every connection is asked for, empty when none is.
198///
199/// Writable, and the one setting here whose value is a secret. It reads back in
200/// the clear, which is what a real server does and is not an oversight of one:
201/// an operator who can send `CONFIG GET` on this server can already read
202/// everything in it.
203const REQUIREPASS: &str = "requirepass";
204
205/// How long a sealed backup is kept before it cleans itself up.
206///
207/// Seconds, and zero is the default and means it is kept until somebody says
208/// `BACKUP CLEANUP`. Writable, since a backup taken by a script that then died
209/// is exactly the thing this is for and setting it afterwards has to work.
210const SEALED_TTL: &str = "backup-sealed-ttl";
211
212/// The file the users are read from and written back to, empty when there is
213/// none.
214///
215/// Immutable, which is Redis's rule for it and is the right one: an operator who
216/// could point a running server at a different ACL file would have a way of
217/// changing who may reach it that is invisible to everything watching the file
218/// it was started with.
219const ACLFILE: &str = "aclfile";
220
221/// How many refusals `ACL LOG` keeps, and nought keeps none.
222///
223/// Writable, because the reason to change it is that something is happening
224/// right now and the log is either too short to see it or long enough to be in
225/// the way.
226const ACLLOG_MAX_LEN: &str = "acllog-max-len";
227
228/// Whether a new selector starts out allowed every channel.
229///
230/// Writable, and writing it changes nothing that already exists: it is read at
231/// the moment a selector is made and never looked at again. Redis 6 behaved as
232/// `allchannels` and Redis 7 changed the default to `resetchannels`, which is
233/// what this setting is for, and yo starts where Redis 7 did.
234const ACL_PUBSUB_DEFAULT: &str = "acl-pubsub-default";
235
236/// The two words `acl-pubsub-default` is allowed to be, in Redis's order.
237const CHANNEL_DEFAULTS: [&str; 2] = ["allchannels", "resetchannels"];
238
239/// Whether a client's write is refused while this server follows a master.
240///
241/// Writable, and on by default, which is Redis's default and is the only safe
242/// one: a write that lands on a replica is a write the master never hears about
243/// and that the next full resync throws away. Turning it off is a real thing to
244/// do and is what a cache in front of a slow master wants.
245///
246/// The `slave` spelling is the name this had before Redis renamed it and it
247/// still answers to both, so this does too, the same way the size ladder answers
248/// to `ziplist`. Two names, one setting.
249const REPLICA_READ_ONLY: [&str; 2] = ["replica-read-only", "slave-read-only"];
250
251/// The password and user the link to a master authenticates with.
252///
253/// Writable and both empty by default, which is a master that asks for nothing.
254/// A user without a password is not a thing to send, so an empty `masterauth`
255/// means the link sends no `AUTH` at all whatever `masteruser` says. They read
256/// back in the clear for the same reason `requirepass` does.
257const MASTERAUTH: &str = "masterauth";
258/// The user half of [`MASTERAUTH`], for a master with an ACL rather than a
259/// password.
260const MASTERUSER: &str = "masteruser";
261
262/// The two words a yes or no setting is allowed to be.
263const BOOLS: [&str; 2] = ["yes", "no"];
264
265/// The two cluster settings that really move, both of them a yes or a no.
266///
267/// `cluster-require-full-coverage` decides whether a node with a hole somewhere
268/// in the cluster refuses everything or only the keys in the hole, and
269/// `cluster-allow-reads-when-down` decides whether a node that has decided the
270/// cluster is down still answers reads. Both take effect on the next command,
271/// which is what an operator digging a cluster out of a hole wants.
272const CLUSTER_COVERAGE: [&str; 2] = [
273 "cluster-require-full-coverage",
274 "cluster-allow-reads-when-down",
275];
276
277/// The four settings a slot migration runs under.
278///
279/// Each row is the name, which knob it writes, whether it reads a byte count or
280/// a plain number, the smallest value it takes, and whether it is hidden. They
281/// are here as a group rather than one at a time because they are only ever
282/// read together, by an operator working out why a move is taking as long as it
283/// is, and a group with a hole in it is worse than no group at all.
284///
285/// Hidden is Redis's word for a setting that a pattern does not find and an
286/// exact name does. It is what upstream does with the two of these that are
287/// backstops rather than things to tune, and copying it matters because a tool
288/// that dumps `CONFIG GET *` and writes the result back out as a config file
289/// would otherwise carry them along.
290const MIGRATION: [(&str, Migration, bool, i64, bool); 4] = [
291 (
292 "cluster-slot-migration-handoff-max-lag-bytes",
293 Migration::Lag,
294 true,
295 0,
296 false,
297 ),
298 (
299 "cluster-slot-migration-write-pause-timeout",
300 Migration::Pause,
301 false,
302 0,
303 false,
304 ),
305 (
306 "cluster-slot-migration-sync-buffer-drain-timeout",
307 Migration::Drain,
308 false,
309 0,
310 true,
311 ),
312 (
313 "cluster-slot-migration-max-archived-tasks",
314 Migration::Archived,
315 false,
316 1,
317 true,
318 ),
319];
320
321/// Whether this server is a cluster node, which is fixed for the life of the
322/// process and is Redis's rule.
323///
324/// A server that could be turned into a cluster node while it was holding keys
325/// would be a server whose keys were suddenly in slots it does not own, so
326/// `CONFIG SET` refuses it and the only way to set it is at startup.
327const CLUSTER_ENABLED: &str = "cluster-enabled";
328
329/// Where a cluster node writes its table, which it was given at startup.
330const CLUSTER_CONFIG_FILE: &str = "cluster-config-file";
331
332/// Which classes of keyspace change are published, and on which two channels.
333///
334/// On its own for a fifth reason: it is the only setting whose value is neither
335/// a number nor one of a fixed list of words, but a set of characters that reads
336/// back in a different spelling from the one it was written in. `CONFIG SET
337/// notify-keyspace-events KEA` reads back as `AKE`. See the `notify` module for
338/// what each character means and why the order is what it is.
339const NOTIFY: &str = "notify-keyspace-events";
340
341/// Read a byte count the way `CONFIG SET maxmemory` reads one.
342///
343/// This is Redis's `memtoull`. Digits, then an optional unit that is not case
344/// sensitive: nothing or `b` is bytes, `k` is a thousand and `kb` is a kibibyte,
345/// and the same pairing again for `m` and `g`. The two spellings meaning
346/// different numbers is a trap and it is Redis's trap, so it is repeated here
347/// rather than tidied up.
348///
349/// A unit that overflows clamps rather than failing, which is upstream's
350/// `ULLONG_MAX` arm. There is no sign: a leading minus is refused before the
351/// digits are read, so `maxmemory -1` is not a very large number.
352///
353/// Public because `yodb serve` takes the same limits on the command line that
354/// `CONFIG SET` takes at runtime, and a server that accepts `100mb` from one and
355/// not the other, or reads it as a different number, is a server that gets
356/// misconfigured. One parser, one answer.
357#[must_use]
358pub fn parse_memory(value: &[u8]) -> Option<u64> {
359 let split = value
360 .iter()
361 .position(|b| !b.is_ascii_digit())
362 .unwrap_or(value.len());
363 let (digits, unit) = value.split_at(split);
364 if digits.is_empty() {
365 return None;
366 }
367 let mul: u64 = match unit {
368 [] => 1,
369 u if u.eq_ignore_ascii_case(b"b") => 1,
370 u if u.eq_ignore_ascii_case(b"k") => 1000,
371 u if u.eq_ignore_ascii_case(b"kb") => 1024,
372 u if u.eq_ignore_ascii_case(b"m") => 1000 * 1000,
373 u if u.eq_ignore_ascii_case(b"mb") => 1024 * 1024,
374 u if u.eq_ignore_ascii_case(b"g") => 1000 * 1000 * 1000,
375 u if u.eq_ignore_ascii_case(b"gb") => 1024 * 1024 * 1024,
376 _ => return None,
377 };
378 let mut n: u64 = 0;
379 for d in digits {
380 n = n.saturating_mul(10).saturating_add(u64::from(d - b'0'));
381 }
382 Some(n.saturating_mul(mul))
383}
384
385/// Every policy name, joined the way `CONFIG SET` lists them when it refuses one.
386///
387/// This is a formatter and not a string because the error path should not touch
388/// the allocator, and it walks [`Policy::ALL`] rather than spelling the ten names
389/// out again so the two cannot drift apart. The order is the order in Redis's own
390/// enum table, which is the whole reason `Policy::ALL` is written down.
391struct PolicyNames;
392
393impl core::fmt::Display for PolicyNames {
394 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
395 for (at, policy) in Policy::ALL.iter().enumerate() {
396 if at > 0 {
397 f.write_str(", ")?;
398 }
399 f.write_str(policy.name())?;
400 }
401 Ok(())
402 }
403}
404
405/// Run one connection or server command.
406pub(super) fn execute(
407 server: &Server,
408 session: &mut Session,
409 spec: &Spec,
410 args: Args<'_>,
411 out: &mut Out,
412) -> Result<Flow> {
413 match spec.name {
414 // The arity in the table is a minimum of one, and a real server then
415 // refuses a second argument as a wrong number of them.
416 "ping" => {
417 if args.len() > 2 {
418 return Err(args::wrong_arity("ping"));
419 }
420 // A RESP2 connection in subscribe mode is answered a two element
421 // array with `pong` in front, so that everything reaching a
422 // subscribed client on RESP2 has the same shape. The one place a
423 // command in this file cares what the connection has subscribed to.
424 if super::pubsub::ping(session, args, out) {
425 return Ok(Flow::Continue);
426 }
427 if args.len() == 2 {
428 out.bulk(args.get(1));
429 } else {
430 out.simple(b"PONG");
431 }
432 }
433 "echo" => out.bulk(args.get(1)),
434 "acl" => acl::execute(server, session, args, out)?,
435 "auth" => auth::execute(server, session, args, out)?,
436 "debug" => debug::execute(server, session, args, out)?,
437 "memory" => super::memory::execute(server, session, args, out)?,
438 "replconf" => super::repl::replconf(server, session, args, out)?,
439 "psync" | "sync" => super::repl::psync(server, session, args, out)?,
440 "replicaof" | "slaveof" => super::follow::replicaof(server, args, out)?,
441 "failover" => super::failover::execute(server, args, out)?,
442 "cluster" => super::cluster::execute(server, session, args, out)?,
443 // The three connection commands cluster mode adds. `ASKING` is the one
444 // that does anything: it says the next command is allowed into a slot
445 // this node is receiving and does not own yet, which is how a client
446 // follows an `ASK` it was told.
447 //
448 // `READONLY` and `READWRITE` say whether this connection will take
449 // reads from a replica rather than being redirected to the master, and
450 // on a node that is nobody's replica, which is every node here until the
451 // bus is in, both of them are an `OK` and nothing else. That is what a
452 // real master answers too, so a client library that sends `READONLY` on
453 // connect gets the same answer from both.
454 "asking" => {
455 if !server.cluster_enabled() {
456 return Err(super::cluster::disabled());
457 }
458 session.ask_next();
459 out.ok();
460 }
461 "readonly" | "readwrite" => {
462 if !server.cluster_enabled() {
463 return Err(super::cluster::disabled());
464 }
465 out.ok();
466 }
467 "hello" => hello(server, session, args, out)?,
468 "select" => {
469 // A cluster has one database and the slots are how it is cut up, so
470 // moving to another one would be moving to a database no slot points
471 // at. Database nought is still allowed, because a client library
472 // that sends SELECT 0 on connect is asking for where it already is.
473 let n = args.int(1)?;
474 if server.cluster_enabled() && n != 0 {
475 return Err(Error::new(
476 Code::Invalid,
477 "SELECT is not allowed in cluster mode",
478 ));
479 }
480 let ok = usize::try_from(n).is_ok_and(|n| n < DATABASES);
481 if !ok {
482 return Err(Error::new(Code::Invalid, "DB index is out of range"));
483 }
484 session.db = n as usize;
485 out.ok();
486 }
487 "reset" => {
488 // Everything a connection carries goes back to what it was when it
489 // was opened, and that includes the protocol: a connection that
490 // said `HELLO 3` is speaking RESP2 again after this.
491 //
492 // The transaction and the watches go first because letting go of a
493 // watch is a change to the server and not to the connection, so
494 // clearing the list here without saying so would leave rows on the
495 // server that nobody is watching. `RESET` inside `MULTI` answers
496 // `+RESET` and leaves no transaction, which is why it is one of the
497 // six commands a transaction does not queue.
498 // The subscriptions go with them, and for the same reason: a
499 // subscription is a row on the server naming this connection, so
500 // clearing the connection's list alone would leave the server
501 // delivering into a slot that is not listening any more.
502 // And the monitor with them, which is the one way out of monitor
503 // mode short of closing the socket. `RESET` still answers `+RESET`
504 // on a connection that was one, because the reply belongs to the
505 // client the connection has just gone back to being.
506 multi::release(server, session);
507 super::pubsub::release(server, session);
508 if session.monitoring() {
509 server.watch_no_more(session.row());
510 }
511 session.reset();
512 // Including the password, which is what `RESET` means by putting
513 // the connection back the way it was accepted: on a server with a
514 // password the client has to send `AUTH` again, and on a server
515 // without one it never had to.
516 session.admit(!server.guarded());
517 out.set_proto(Proto::Resp2);
518 out.simple(b"RESET");
519 }
520 // The reply goes out before the socket closes, which is why this is a
521 // flow answer and not something the body does to the connection.
522 "quit" => {
523 out.ok();
524 return Ok(Flow::Close);
525 }
526 // Every command on the server, from here on, on this connection. The
527 // reply is `OK` once and nothing after it, and a connection that sends
528 // it twice is answered nothing at all the second time, which is a real
529 // server's behaviour and not an oversight of one.
530 "monitor" => {
531 // A transaction replaying this has been promised a reply for every
532 // command it queued, and a connection that has turned into a feed
533 // cannot give one. A real server refuses it in the same words.
534 if session.running() {
535 return Err(Error::new(
536 Code::Invalid,
537 "MONITOR isn't allowed for DENY BLOCKING client",
538 ));
539 }
540 if server.watch_all(session.row()) {
541 out.ok();
542 }
543 }
544 "client" => return super::client::execute(server, session, spec, args, out),
545 "command" => command(args, out)?,
546 "config" => config(server, args, out)?,
547 "info" => info(server, args, out),
548 // A key that is past its deadline and has not been read since is still
549 // counted, which is what Redis does too: `DBSIZE` is the size of the
550 // dictionary and not a walk over it. Redis has an active expiry cycle
551 // that takes those keys out within a tick or so and we do not yet, so
552 // the two servers disagree for as long as a dead key sits unread. That
553 // gap closes with the maintenance slice rather than with a count here,
554 // because a count here would be O(N) on a command that is O(1)
555 // everywhere else.
556 "dbsize" => out.int(server.dbs[session.db].len() as i64),
557 "flushall" => {
558 flush_mode(args)?;
559 for db in &server.dbs {
560 db.clear();
561 }
562 server.search.lock().clear();
563 server.cursors.lock().wipe();
564 out.ok();
565 }
566 // The search indexes go too, and they go whichever database this is.
567 // An index that only ever followed keys on database zero is dropped by
568 // a `FLUSHDB` on database nine, which is measured against a real server
569 // rather than reasoned about: the module hangs its callback on the
570 // flush event without looking at which database flushed.
571 "flushdb" => {
572 flush_mode(args)?;
573 server.dbs[session.db].clear();
574 server.search.lock().clear();
575 server.cursors.lock().wipe();
576 out.ok();
577 }
578 // Two databases change places and no key moves. What is in the stripes
579 // is exchanged and the databases stay where they are, so this costs two
580 // pointer sized writes per stripe whatever is in either of them, which
581 // is what makes `SWAPDB` fast and dangerous at the same time.
582 //
583 // No connection is told. A client on database zero is still on database
584 // zero and is now looking at what used to be database one, which is the
585 // whole point of the command and is why Redis calls it dangerous. A
586 // client parked in `BLPOP` remembers the database index it blocked on
587 // and not the database, so it wakes up against the swapped in one, which
588 // is Redis's behaviour and falls out of the index being what is stored.
589 "swapdb" => {
590 if server.cluster_enabled() {
591 return Err(Error::new(
592 Code::Invalid,
593 "SWAPDB is not allowed in cluster mode",
594 ));
595 }
596 let first = db_index(args.get(1), "invalid first DB index")?;
597 let second = db_index(args.get(2), "invalid second DB index")?;
598 server.striped(first).swap_with(server.striped(second));
599 out.ok();
600 }
601 "time" => time(out),
602 // The four commands about writing the dataset to a file and the one
603 // about who this server is, all in the `persist` module because a client
604 // asks them together.
605 "save" | "bgsave" | "bgrewriteaof" | "lastsave" | "role" => {
606 persist::execute(server, session, spec, args, out)?;
607 }
608 "backup" => backup::execute(server, args, out)?,
609 "shutdown" => return shutdown(server, args),
610 _ => return Err(args::unknown_command(args)),
611 }
612 Ok(Flow::Continue)
613}
614
615/// `TIME`, which is two bulk strings and not one integer.
616///
617/// Seconds first and then microseconds within that second, both written out as
618/// decimal text, which is a shape nobody would choose today and is the shape
619/// every client library parses.
620///
621/// It reads the wall clock rather than the coarse clock the keyspace uses. The
622/// coarse one is a cached millisecond that a background tick refreshes, which is
623/// the right trade for deciding whether a key has expired and the wrong one for
624/// a command whose entire job is to say what time it is. A client that calls
625/// `TIME` twice in a row and gets the same microsecond has been lied to.
626fn time(out: &mut Out) {
627 let now = SystemTime::now()
628 .duration_since(UNIX_EPOCH)
629 .unwrap_or_default();
630 out.array(2);
631 out.bulk(now.as_secs().to_string().as_bytes());
632 out.bulk(now.subsec_micros().to_string().as_bytes());
633}
634
635// ---------------------------------------------------------------- SHUTDOWN
636
637/// `SHUTDOWN [NOSAVE | SAVE] [NOW] [FORCE] [ABORT]`.
638///
639/// On success this writes nothing at all and the connection closes under the
640/// client, which is what a server that has stopped looks like from the outside
641/// and is what every client library already expects. There is no `OK`, because
642/// an `OK` would be a promise made by a process that is about to not exist.
643///
644/// `SAVE` writes the file [`persist`] writes, and it is the only word here that
645/// does anything. `NOSAVE` is the default rather than an instruction, which is
646/// the same answer `save` gets from `CONFIG GET`: this server has no save points
647/// and never will, because what durability there is belongs to the file
648/// underneath and is already on disk by the time a command returns. So there is
649/// nothing for `NOSAVE` to skip and the file `SAVE` asks for is an export
650/// somebody wants a copy of on the way down. `NOW` and `FORCE` are about not
651/// waiting for replicas and about going anyway when a save failed, and neither
652/// has anything to wait for or to fail here.
653///
654/// # Errors
655///
656/// [`Code::Invalid`] for a word that is not one of the five, for `SAVE` and
657/// `NOSAVE` in the same call, and for `ABORT` alongside any other flag, all of
658/// which is what 8.10.1 says. `ABORT` on its own gets Redis's message for a
659/// cancel with nothing to cancel, and here that is not a state that can be
660/// reached rather than one that happens to be empty: a shutdown is decided and
661/// done inside one turn of the loop, so there is never a window in which one is
662/// in progress and a second client could call it off.
663fn shutdown(server: &Server, args: Args<'_>) -> Result<Flow> {
664 let (mut save, mut nosave, mut abort, mut other) = (false, false, false, false);
665 for at in 1..args.len() {
666 let arg = args.get(at);
667 match () {
668 () if is(arg, b"save") => save = true,
669 () if is(arg, b"nosave") => nosave = true,
670 () if is(arg, b"abort") => abort = true,
671 () if is(arg, b"now") || is(arg, b"force") => other = true,
672 () => return Err(args::syntax()),
673 }
674 }
675 // Repeating one is fine and contradicting yourself is not, and `ABORT` says
676 // to do nothing so it cannot be combined with a word about how to do it.
677 if (save && nosave) || (abort && (save || nosave || other)) {
678 return Err(args::syntax());
679 }
680 if abort {
681 return Err(Error::new(Code::Invalid, "No shutdown in progress."));
682 }
683 if save {
684 persist::on_shutdown(server);
685 }
686 server.stop();
687 // Closing is what stops anything the client pipelined behind this from
688 // being answered by a server that is on its way out.
689 Ok(Flow::Close)
690}
691
692// ------------------------------------------------------------------- FLUSH
693
694/// Check the optional `ASYNC` or `SYNC` on `FLUSHALL` and `FLUSHDB`.
695///
696/// Both are accepted and neither changes anything. On a real server the choice
697/// is whether the freeing happens on the connection's thread or on the lazy
698/// free thread, and either way the keyspace is empty before the `OK` goes out.
699/// That is the whole of what a client can observe, and it is the same here,
700/// so taking the word and ignoring it is answering the question rather than
701/// pretending to.
702///
703/// # Errors
704///
705/// [`Code::Invalid`] for a third argument, or for a second that is neither
706/// word, which is what Redis says about both.
707fn flush_mode(args: Args<'_>) -> Result<()> {
708 if args.len() == 1 {
709 return Ok(());
710 }
711 if args.len() > 2 || !(is(args.get(1), b"async") || is(args.get(1), b"sync")) {
712 return Err(args::syntax());
713 }
714 Ok(())
715}
716
717/// One of `SWAPDB`'s two database indexes, with Redis's two different
718/// complaints about it.
719///
720/// A word that is not a number, or a number too big to be a database index on a
721/// server that stores the index in a C `int`, gets the caller's message, which
722/// says which of the two arguments was wrong. A number that is a plausible index
723/// and is not one of ours gets the same out of range message `SELECT` gives. The
724/// split looks arbitrary and it is Redis's, and the reason for it is that the
725/// first check happens while reading the argument and the second happens inside
726/// the swap, so only the first one knows which argument it was looking at.
727fn db_index(arg: &[u8], bad: &'static str) -> Result<usize> {
728 let n = parse_i64(arg)
729 .filter(|n| i32::try_from(*n).is_ok())
730 .ok_or_else(|| Error::new(Code::Invalid, bad))?;
731 usize::try_from(n)
732 .ok()
733 .filter(|n| *n < DATABASES)
734 .ok_or_else(|| Error::new(Code::Invalid, "DB index is out of range"))
735}
736
737// ------------------------------------------------------------------- HELLO
738
739/// `HELLO [protover [AUTH username password] [SETNAME name]]`.
740///
741/// The order of the three things that can go wrong here is the reference's and
742/// is worth writing down, because it is not the order they appear in. The
743/// protocol version is read and refused first, so `HELLO 9 AUTH default right`
744/// on a connection that has not authenticated is a `NOPROTO` and leaves the
745/// connection unauthenticated. The `AUTH` option is applied next, so a wrong
746/// password is a `WRONGPASS` and the protocol stays where it was. Only then does
747/// the connection have to be authenticated at all, which is what makes a bare
748/// `HELLO` on a server with a password a `NOAUTH` rather than a greeting.
749fn hello(server: &Server, session: &mut Session, args: Args<'_>, out: &mut Out) -> Result<()> {
750 // The version this call agreed on, if it named one. Held rather than applied
751 // where it is read, because the reply buffer must not change protocol until
752 // the password below has been asked for and answered.
753 let mut agreed = None;
754 if args.len() > 1 {
755 let v = parse_i64(args.get(1)).ok_or_else(|| {
756 Error::new(
757 Code::Invalid,
758 "Protocol version is not an integer or out of range",
759 )
760 })?;
761 let Some(proto) = Proto::from_version(v) else {
762 // `NOPROTO` rather than `ERR`, and it is the one error in this file
763 // written straight into the buffer: the prefix is part of what the
764 // client branches on, and it is the only place in the engine that
765 // needs this one.
766 out.error(b"NOPROTO unsupported protocol version");
767 return Ok(());
768 };
769 let mut i = 2;
770 while i < args.len() {
771 let o = args.get(i);
772 if is(o, b"AUTH") && i + 2 < args.len() {
773 if !acl::authenticate(server, session, args.get(i + 1), args.get(i + 2), args, out)
774 {
775 out.error(b"WRONGPASS invalid username-password pair or user is disabled.");
776 return Ok(());
777 }
778 i += 3;
779 } else if is(o, b"SETNAME") && i + 1 < args.len() {
780 session.set_name(args.get(i + 1));
781 i += 2;
782 } else {
783 return Err(yo_alloc::allow(|| {
784 Error::fmt(
785 Code::Invalid,
786 format_args!(
787 "Syntax error in HELLO option '{}'",
788 String::from_utf8_lossy(o)
789 ),
790 )
791 }));
792 }
793 }
794 agreed = Some(proto);
795 }
796
797 if server.guarded() && !session.authenticated() {
798 // Its own sentence rather than the one every other command gets, because
799 // a client that speaks RESP3 has to send `HELLO` before it can send
800 // `AUTH` and would otherwise be told to do the thing it is doing.
801 out.error(auth::HELLO_NOAUTH.as_bytes());
802 return Ok(());
803 }
804 // The reply is written in the protocol that was just agreed, not the one the
805 // request arrived in.
806 if let Some(proto) = agreed {
807 out.set_proto(proto);
808 }
809
810 let proto = out.proto().version();
811 out.map(7);
812 out.bulk(b"server");
813 out.bulk(REPORTED_SERVER.as_bytes());
814 out.bulk(b"version");
815 out.bulk(REPORTED_VERSION.as_bytes());
816 out.bulk(b"proto");
817 out.int(proto);
818 out.bulk(b"id");
819 out.int(session.id as i64);
820 out.bulk(b"mode");
821 out.bulk(b"standalone");
822 out.bulk(b"role");
823 out.bulk(b"master");
824 out.bulk(b"modules");
825 out.array(0);
826 Ok(())
827}
828
829// ----------------------------------------------------------------- COMMAND
830
831/// `COMMAND [COUNT|LIST|INFO|DOCS|GETKEYS|HELP]`.
832fn command(args: Args<'_>, out: &mut Out) -> Result<()> {
833 if args.len() == 1 {
834 out.array(table::COMMANDS.len());
835 for spec in table::COMMANDS {
836 write_spec(out, spec);
837 }
838 return Ok(());
839 }
840 let sub = args.get(1);
841 if is(sub, b"COUNT") {
842 out.int(table::COMMANDS.len() as i64);
843 } else if is(sub, b"INFO") {
844 if args.len() == 2 {
845 out.array(table::COMMANDS.len());
846 for spec in table::COMMANDS {
847 write_spec(out, spec);
848 }
849 } else {
850 out.array(args.len() - 2);
851 for i in 2..args.len() {
852 match table::lookup(args.get(i)) {
853 Some(spec) => write_spec(out, spec),
854 // A name nobody has heard of is a null in the list rather
855 // than an error, so one bad name in a batch does not cost
856 // the client the other answers. It is the plain null and
857 // not the array one, which on RESP2 is the difference
858 // between `$-1` and `*-1` and is what a real server sends.
859 None => out.nil(),
860 }
861 }
862 }
863 } else if is(sub, b"LIST") {
864 list(args, out)?;
865 } else if is(sub, b"DOCS") {
866 docs(args, out);
867 } else if is(sub, b"GETKEYS") {
868 getkeys(args, out, false)?;
869 } else if is(sub, b"GETKEYSANDFLAGS") {
870 getkeys(args, out, true)?;
871 } else if is(sub, b"HELP") {
872 help(out, COMMAND_HELP);
873 } else {
874 return Err(args::unknown_subcommand(sub, "COMMAND"));
875 }
876 Ok(())
877}
878
879/// `COMMAND LIST [FILTERBY MODULE m|ACLCAT c|PATTERN p]`.
880fn list(args: Args<'_>, out: &mut Out) -> Result<()> {
881 if args.len() == 2 {
882 out.array(table::COMMANDS.len());
883 for spec in table::COMMANDS {
884 out.bulk(spec.name.as_bytes());
885 }
886 return Ok(());
887 }
888 if args.len() != 5 || !is(args.get(2), b"FILTERBY") {
889 return Err(args::syntax());
890 }
891 let (how, what) = (args.get(3), args.get(4));
892 let keep = |spec: &Spec| {
893 if is(how, b"MODULE") {
894 // Nothing here came from a module, so every filter by one is empty.
895 false
896 } else if is(how, b"ACLCAT") {
897 spec.acl
898 .iter()
899 .any(|c| c.len() == what.len() + 1 && c.as_bytes()[1..].eq_ignore_ascii_case(what))
900 } else {
901 glob::matches(what, spec.name.as_bytes())
902 }
903 };
904 if !is(how, b"MODULE") && !is(how, b"ACLCAT") && !is(how, b"PATTERN") {
905 return Err(args::syntax());
906 }
907 out.array(table::COMMANDS.iter().filter(|s| keep(s)).count());
908 for spec in table::COMMANDS.iter().filter(|s| keep(s)) {
909 out.bulk(spec.name.as_bytes());
910 }
911 Ok(())
912}
913
914/// `COMMAND DOCS [name ...]`.
915///
916/// The arguments field a real server sends is left out. It describes the shape
917/// of every option of every command in a form nothing but `redis-cli`'s hinting
918/// reads, and getting it wrong would be worse than not sending it, since a
919/// client that finds the field trusts it.
920fn docs(args: Args<'_>, out: &mut Out) {
921 if args.len() == 2 {
922 out.map(table::COMMANDS.len());
923 for spec in table::COMMANDS {
924 write_docs(out, spec);
925 }
926 return;
927 }
928 let found = (2..args.len())
929 .filter(|&i| table::lookup(args.get(i)).is_some())
930 .count();
931 out.map(found);
932 for i in 2..args.len() {
933 if let Some(spec) = table::lookup(args.get(i)) {
934 write_docs(out, spec);
935 }
936 }
937}
938
939/// One command's documentation, as the name and then the map about it.
940fn write_docs(out: &mut Out, spec: &Spec) {
941 out.bulk(spec.name.as_bytes());
942 out.map(4);
943 out.bulk(b"summary");
944 out.bulk(spec.summary.as_bytes());
945 out.bulk(b"since");
946 out.bulk(spec.since.as_bytes());
947 out.bulk(b"group");
948 out.bulk(spec.group.as_bytes());
949 out.bulk(b"complexity");
950 out.bulk(spec.complexity.as_bytes());
951}
952
953/// `COMMAND GETKEYS <full command>` and `COMMAND GETKEYSANDFLAGS <full command>`.
954///
955/// This is how a cluster aware client routes a command it does not have a rule
956/// for, so a wrong answer here is a client that sends a write to the wrong
957/// node. The answer comes off the key specs, which is the same place the ACL
958/// reads, so the two can never drift apart.
959///
960/// The three errors are the reference's own and they mean different things. A
961/// name nobody registered is one, a command that never takes a key whatever it
962/// is sent is another, and a command that does take keys and was handed
963/// arguments the specs cannot resolve is the third. Only the last is about what
964/// was actually typed.
965fn getkeys(args: Args<'_>, out: &mut Out, flags: bool) -> Result<()> {
966 let sub = if flags { "getkeysandflags" } else { "getkeys" };
967 if args.len() < 3 {
968 return Err(args::wrong_arity_sub("command", sub));
969 }
970 let inner = args.get(2);
971 let spec = table::lookup(inner)
972 .ok_or_else(|| Error::new(Code::Unsupported, "Invalid command specified"))?;
973 if !keyspec::takes_keys(spec, args, 2) {
974 return Err(Error::new(
975 Code::Invalid,
976 "The command has no key arguments",
977 ));
978 }
979 let argc = args.len() - 2;
980 if !table::arity_ok(spec, argc) {
981 return Err(Error::new(
982 Code::Invalid,
983 "Invalid number of arguments specified for command",
984 ));
985 }
986 // Three specs at most a command and one run each, so the answer is worked
987 // out into a fixed array rather than a list that grows. A run is a first
988 // argument and a count, so a hundred keys behind a count is still one of
989 // these.
990 let mut runs = [None; 4];
991 let mut at = 0;
992 let whole = keyspec::find(spec, args, 2, &mut |run| {
993 if at < runs.len() {
994 runs[at] = Some(run);
995 at += 1;
996 }
997 });
998 let found: usize = runs.iter().flatten().map(|r| r.count).sum();
999 // A command that resolves to nothing is a syntax error, unless it is one of
1000 // the six that may honestly have no keys, which is the script family: `EVAL
1001 // body 0` is an ordinary thing to write and answers an empty list.
1002 if (!whole || found == 0) && !spec.flags.contains(&"no_mandatory_keys") {
1003 return Err(Error::new(
1004 Code::Invalid,
1005 "Invalid arguments specified for command",
1006 ));
1007 }
1008 let found = if whole { found } else { 0 };
1009 out.array(found);
1010 if found == 0 {
1011 return Ok(());
1012 }
1013 for run in runs.iter().flatten() {
1014 for i in 0..run.count {
1015 let key = args.get(run.first + i * run.step);
1016 if flags {
1017 out.array(2);
1018 out.bulk(key);
1019 out.set(run.flags.len());
1020 for f in run.flags {
1021 out.simple(f.as_bytes());
1022 }
1023 } else {
1024 out.bulk(key);
1025 }
1026 }
1027 }
1028 Ok(())
1029}
1030
1031/// One command, in the ten field shape `COMMAND INFO` has had since 7.0.
1032///
1033/// The tips and the subcommands are still empty, which is what is left of
1034/// divergence D-13. The key specs are not: they say where the keys are for
1035/// everything in this table, including the commands the triple above them
1036/// cannot describe.
1037///
1038/// Five of the ten fields are sets rather than arrays, which only shows on
1039/// RESP3 and shows there on every command. A set is what the reference sends
1040/// for all five, and it is the honest type for them: nothing in a flag list or
1041/// an acl category list is ordered or repeated.
1042fn write_spec(out: &mut Out, spec: &Spec) {
1043 out.array(10);
1044 out.bulk(spec.name.as_bytes());
1045 out.int(i64::from(spec.arity));
1046 out.set(spec.flags.len());
1047 for f in spec.flags {
1048 out.simple(f.as_bytes());
1049 }
1050 out.int(i64::from(spec.first_key));
1051 out.int(i64::from(spec.last_key));
1052 out.int(i64::from(spec.step));
1053 out.set(spec.acl.len());
1054 for a in spec.acl {
1055 out.simple(a.as_bytes());
1056 }
1057 out.set(0);
1058 out.set(spec.keys.len());
1059 for key in spec.keys {
1060 write_key_spec(out, key);
1061 }
1062 out.set(0);
1063}
1064
1065/// One key spec, as the map `COMMAND INFO` reports it.
1066///
1067/// The notes come first and only when there are any, which is why the map is
1068/// three long or four rather than always four.
1069fn write_key_spec(out: &mut Out, key: &KeySpec) {
1070 out.map(if key.notes.is_empty() { 3 } else { 4 });
1071 if !key.notes.is_empty() {
1072 out.bulk(b"notes");
1073 out.bulk(key.notes.as_bytes());
1074 }
1075 out.bulk(b"flags");
1076 out.set(key.flags.len());
1077 for f in key.flags {
1078 out.simple(f.as_bytes());
1079 }
1080 out.bulk(b"begin_search");
1081 out.map(2);
1082 out.bulk(b"type");
1083 match key.begin {
1084 Begin::At(index) => {
1085 out.bulk(b"index");
1086 out.bulk(b"spec");
1087 out.map(1);
1088 out.bulk(b"index");
1089 out.int(i64::from(index));
1090 }
1091 Begin::After(word, from) => {
1092 out.bulk(b"keyword");
1093 out.bulk(b"spec");
1094 out.map(2);
1095 out.bulk(b"keyword");
1096 out.bulk(word);
1097 out.bulk(b"startfrom");
1098 out.int(i64::from(from));
1099 }
1100 Begin::Unknown => {
1101 out.bulk(b"unknown");
1102 out.bulk(b"spec");
1103 out.map(0);
1104 }
1105 }
1106 out.bulk(b"find_keys");
1107 out.map(2);
1108 out.bulk(b"type");
1109 match key.find {
1110 Find::Range { last, step, limit } => {
1111 out.bulk(b"range");
1112 out.bulk(b"spec");
1113 out.map(3);
1114 out.bulk(b"lastkey");
1115 out.int(i64::from(last));
1116 out.bulk(b"keystep");
1117 out.int(i64::from(step));
1118 out.bulk(b"limit");
1119 out.int(i64::from(limit));
1120 }
1121 Find::Counted { count, first, step } => {
1122 out.bulk(b"keynum");
1123 out.bulk(b"spec");
1124 out.map(3);
1125 out.bulk(b"keynumidx");
1126 out.int(i64::from(count));
1127 out.bulk(b"firstkey");
1128 out.int(i64::from(first));
1129 out.bulk(b"keystep");
1130 out.int(i64::from(step));
1131 }
1132 Find::Unknown => {
1133 out.bulk(b"unknown");
1134 out.bulk(b"spec");
1135 out.map(0);
1136 }
1137 }
1138}
1139
1140// ------------------------------------------------------------------ CONFIG
1141
1142/// What a ladder setting is set to now.
1143fn read_knob(db: &Keyspace, knob: Knob) -> usize {
1144 match knob {
1145 Knob::SetIntsetEntries => db.limits().max_intset_entries,
1146 Knob::SetListpackEntries => db.limits().max_listpack_entries,
1147 Knob::SetListpackValue => db.limits().max_listpack_value,
1148 Knob::HashListpackEntries => db.hash_limits().max_listpack_entries,
1149 Knob::HashListpackValue => db.hash_limits().max_listpack_value,
1150 Knob::MaxmemorySamples => db.samples(),
1151 Knob::LfuLogFactor => db.lfu().log_factor as usize,
1152 Knob::LfuDecayTime => db.lfu().decay_minutes as usize,
1153 }
1154}
1155
1156/// Move one ladder setting on one database.
1157fn write_knob(db: &mut Keyspace, knob: Knob, n: usize) {
1158 let mut set = *db.limits();
1159 let mut hash = *db.hash_limits();
1160 let mut lfu = db.lfu();
1161 match knob {
1162 Knob::SetIntsetEntries => set.max_intset_entries = n,
1163 Knob::SetListpackEntries => set.max_listpack_entries = n,
1164 Knob::SetListpackValue => set.max_listpack_value = n,
1165 Knob::HashListpackEntries => hash.max_listpack_entries = n,
1166 Knob::HashListpackValue => hash.max_listpack_value = n,
1167 Knob::MaxmemorySamples => db.set_samples(n),
1168 // Saturating rather than wrapping, because these two are read as `u32`
1169 // and a client is free to send a number that does not fit. Redis clamps
1170 // `lfu-log-factor` and `lfu-decay-time` to the same width.
1171 Knob::LfuLogFactor => lfu.log_factor = u32::try_from(n).unwrap_or(u32::MAX),
1172 Knob::LfuDecayTime => lfu.decay_minutes = u32::try_from(n).unwrap_or(u32::MAX),
1173 }
1174 db.set_limits(set);
1175 db.set_hash_limits(hash);
1176 db.set_lfu(lfu);
1177}
1178
1179/// The two things a real server says about a number it will not take.
1180///
1181/// Both name the setting the client typed and not the one it is an alias for,
1182/// so `hash-max-ziplist-entries` comes back saying `hash-max-ziplist-entries`.
1183/// A value past the range of an `i64` is the parse complaint and not the range
1184/// one, which is upstream reading it before it checks it.
1185fn bad_setting(name: &str, parsed: bool) -> Error {
1186 if parsed {
1187 Error::fmt(
1188 Code::Invalid,
1189 format_args!(
1190 "CONFIG SET failed (possibly related to argument '{name}') - argument must be between 0 and 9223372036854775807 inclusive"
1191 ),
1192 )
1193 } else {
1194 Error::fmt(
1195 Code::Invalid,
1196 format_args!(
1197 "CONFIG SET failed (possibly related to argument '{name}') - argument couldn't be parsed into an integer"
1198 ),
1199 )
1200 }
1201}
1202
1203/// Whether a `CONFIG GET` argument is a pattern rather than a name.
1204///
1205/// Upstream's test, character for character: it looks for any of `[*?` and
1206/// takes the direct dictionary lookup when there are none. A name with none of
1207/// them in it is a name even when it would have matched nothing, and a pattern
1208/// with one of them in it is a pattern even when it would only have matched the
1209/// one setting.
1210fn is_pattern(asked: &[u8]) -> bool {
1211 asked.iter().any(|b| matches!(b, b'[' | b'*' | b'?'))
1212}
1213
1214/// Which spelling of a setting to answer under, or `None` when nothing asked
1215/// for it.
1216///
1217/// A setting spelled out is answered under the spelling the client used, and a
1218/// setting a pattern found is answered under its own name. That looks like a
1219/// quirk and is really the shape of upstream's code: it collects the matches in
1220/// a dictionary keyed by whatever it looked up with, which for the exact branch
1221/// is the client's string and for the pattern branch is the table's. So
1222/// `CONFIG GET MAXMEMORY` answers `MAXMEMORY` and `CONFIG GET MAX*` answers
1223/// `maxmemory`, and a tool comparing the name it asked for with the name it got
1224/// back only works if that is copied.
1225///
1226/// The first argument that matches wins, for the same reason: the dictionary
1227/// already holds the setting by the time the second one is looked at, and a
1228/// setting already in it is skipped.
1229///
1230/// `hidden` is upstream's flag for a setting a pattern does not find. Those are
1231/// the backstops nobody is meant to tune, and leaving them out of `CONFIG GET *`
1232/// keeps them out of anything that dumps the settings and writes them back.
1233fn asked<'a>(args: Args<'a>, name: &'a str, hidden: bool) -> Option<&'a [u8]> {
1234 (2..args.len()).find_map(|i| {
1235 let want = args.get(i);
1236 if is_pattern(want) {
1237 (!hidden && glob::matches_nocase(want, name.as_bytes(), true))
1238 .then_some(name.as_bytes())
1239 } else {
1240 is(want, name.as_bytes()).then_some(want)
1241 }
1242 })
1243}
1244
1245/// `CONFIG GET|SET|RESETSTAT|REWRITE|HELP`.
1246fn config(server: &Server, args: Args<'_>, out: &mut Out) -> Result<()> {
1247 let sub = args.get(1);
1248 if is(sub, b"GET") {
1249 if args.len() < 3 {
1250 return Err(args::wrong_arity_sub("config", "get"));
1251 }
1252 // Every one of these is the name to answer under rather than a yes or a
1253 // no, because a setting spelled out is answered under the client's
1254 // spelling. See [`asked`] for why that is upstream's rule and not an
1255 // accident of it.
1256 let wanted = |name: &'static str| asked(args, name, false);
1257 // A setting that two patterns both ask for is sent once, which is what
1258 // makes this a count of settings rather than a count of matches. The
1259 // two spellings of a ladder setting are two settings by that rule, so
1260 // `CONFIG GET hash-max-*` sends the listpack name and the ziplist name
1261 // and the same number under both, which is what a real server does.
1262 let fixed = SETTINGS.iter().filter_map(|(k, v)| Some((wanted(k)?, v)));
1263 let ladder = LADDER.iter().filter_map(|(k, n)| Some((wanted(k)?, n)));
1264 let policy = wanted(MAXMEMORY_POLICY);
1265 let threads = wanted(IO_THREADS);
1266 let limit = wanted(MAXMEMORY);
1267 let store = wanted(MAXSTORE);
1268 let where_ = wanted(DIR);
1269 let file = wanted(DBFILENAME);
1270 let pass = wanted(REQUIREPASS);
1271 let ttl = wanted(SEALED_TTL);
1272 let events = wanted(NOTIFY);
1273 let acls = wanted(ACLFILE);
1274 let logged = wanted(ACLLOG_MAX_LEN);
1275 let channels = wanted(ACL_PUBSUB_DEFAULT);
1276 // Both spellings are two settings by the same rule the ladder follows,
1277 // so `CONFIG GET *read-only*` sends the replica name and the slave name
1278 // and the same word under both.
1279 let readonly = REPLICA_READ_ONLY.map(wanted);
1280 let mauth = wanted(MASTERAUTH);
1281 let muser = wanted(MASTERUSER);
1282 // The four cluster settings, which are there on every server and not
1283 // only on a node, the same way a real server answers them: a tool asking
1284 // `CONFIG GET cluster-enabled` wants a no rather than nothing back.
1285 let coverage = CLUSTER_COVERAGE.map(wanted);
1286 let clustered = wanted(CLUSTER_ENABLED);
1287 let nodes_file = wanted(CLUSTER_CONFIG_FILE);
1288 let migration = MIGRATION.map(|(name, _, _, _, hidden)| asked(args, name, hidden));
1289 out.map(
1290 fixed.clone().count()
1291 + ladder.clone().count()
1292 + usize::from(policy.is_some())
1293 + usize::from(threads.is_some())
1294 + usize::from(limit.is_some())
1295 + usize::from(store.is_some())
1296 + usize::from(where_.is_some())
1297 + usize::from(file.is_some())
1298 + usize::from(pass.is_some())
1299 + usize::from(ttl.is_some())
1300 + usize::from(events.is_some())
1301 + usize::from(acls.is_some())
1302 + usize::from(logged.is_some())
1303 + usize::from(channels.is_some())
1304 + usize::from(readonly[0].is_some())
1305 + usize::from(readonly[1].is_some())
1306 + usize::from(mauth.is_some())
1307 + usize::from(muser.is_some())
1308 + usize::from(coverage[0].is_some())
1309 + usize::from(coverage[1].is_some())
1310 + usize::from(clustered.is_some())
1311 + usize::from(nodes_file.is_some())
1312 + migration.iter().filter(|name| name.is_some()).count(),
1313 );
1314 for (k, v) in fixed {
1315 out.bulk(k);
1316 out.bulk(v.as_bytes());
1317 }
1318 for (k, knob) in ladder {
1319 out.bulk(k);
1320 out.bulk_int(read_knob(&server.settings(), *knob) as i64);
1321 }
1322 if let Some(k) = policy {
1323 out.bulk(k);
1324 out.bulk(server.settings().policy().name().as_bytes());
1325 }
1326 if let Some(k) = threads {
1327 out.bulk(k);
1328 out.bulk_int(server.io_threads() as i64);
1329 }
1330 if let Some(k) = limit {
1331 // Back as a plain number of bytes whatever the client typed to set
1332 // it, which is what a real server does: `CONFIG SET maxmemory 1gb`
1333 // reads back as 1073741824.
1334 out.bulk(k);
1335 out.bulk_int(server.maxmemory() as i64);
1336 }
1337 if let Some(k) = store {
1338 // Minus one for no limit, and a plain number of bytes otherwise.
1339 // Zero cannot mean no limit here the way it does for `maxmemory`,
1340 // because zero is the setting that says the file holds nothing.
1341 out.bulk(k);
1342 out.bulk_int(server.maxstore().map_or(-1, |n| n as i64));
1343 }
1344 if let Some(k) = where_ {
1345 // Absolute, which is what a real server answers too: it resolves the
1346 // directory at startup and reports the resolved one, so a client can
1347 // tell where the files are without knowing where the process was
1348 // launched from.
1349 out.bulk(k);
1350 yo_alloc::allow(|| out.bulk(server.dir().to_string_lossy().as_bytes()));
1351 }
1352 if let Some(k) = file {
1353 // The name on its own and not the path, which is how a real server
1354 // answers it too: the two settings are joined by whoever reads them.
1355 out.bulk(k);
1356 out.bulk(persist::FILE.as_bytes());
1357 }
1358 if let Some(k) = pass {
1359 out.bulk(k);
1360 server.with_password(|p| out.bulk(p));
1361 }
1362 if let Some(k) = ttl {
1363 out.bulk(k);
1364 out.bulk_int(server.backup().ttl() as i64);
1365 }
1366 if let Some(k) = events {
1367 // The flags and not the string that set them, which is what a real
1368 // server answers too and is why the parser has a formatter next to
1369 // it rather than the text being kept.
1370 out.bulk(k);
1371 let (buf, len) = notify::format(server.notify_flags());
1372 out.bulk(&buf[..len]);
1373 }
1374 if let Some(k) = acls {
1375 // Exactly what the server was started with, which for nearly every
1376 // server is nothing at all. Not resolved to an absolute path the way
1377 // `dir` is, because a real server answers what it was given here.
1378 out.bulk(k);
1379 yo_alloc::allow(|| {
1380 out.bulk(
1381 server
1382 .aclfile()
1383 .map(|p| p.to_string_lossy())
1384 .unwrap_or_default()
1385 .as_bytes(),
1386 );
1387 });
1388 }
1389 if let Some(k) = logged {
1390 out.bulk(k);
1391 out.bulk_int(server.acl_log().max_len() as i64);
1392 }
1393 if let Some(k) = channels {
1394 out.bulk(k);
1395 out.bulk(CHANNEL_DEFAULTS[usize::from(!server.users().open_channels())].as_bytes());
1396 }
1397 for name in readonly.into_iter().flatten() {
1398 {
1399 out.bulk(name);
1400 out.bulk(BOOLS[usize::from(!server.replica_read_only_setting())].as_bytes());
1401 }
1402 }
1403 if let Some(k) = coverage[0] {
1404 out.bulk(k);
1405 out.bulk(BOOLS[usize::from(!server.cluster_full_coverage())].as_bytes());
1406 }
1407 if let Some(k) = coverage[1] {
1408 out.bulk(k);
1409 out.bulk(BOOLS[usize::from(!server.cluster_reads_when_down())].as_bytes());
1410 }
1411 if let Some(k) = clustered {
1412 out.bulk(k);
1413 out.bulk(BOOLS[usize::from(!server.cluster_enabled())].as_bytes());
1414 }
1415 if let Some(k) = nodes_file {
1416 out.bulk(k);
1417 yo_alloc::allow(|| out.bulk(server.cluster_file().as_bytes()));
1418 }
1419 // Always a plain number of bytes or milliseconds, whatever the client
1420 // typed to set it, the same way `maxmemory` reads back: `CONFIG SET
1421 // cluster-slot-migration-handoff-max-lag-bytes 2mb` answers 2097152.
1422 for ((_, knob, ..), name) in MIGRATION.iter().zip(migration) {
1423 if let Some(name) = name {
1424 out.bulk(name);
1425 out.bulk_int(server.migration_knob(*knob));
1426 }
1427 }
1428 if mauth.is_some() || muser.is_some() {
1429 server.with_master_auth(|user, pass| {
1430 if let Some(k) = mauth {
1431 out.bulk(k);
1432 out.bulk(pass);
1433 }
1434 if let Some(k) = muser {
1435 out.bulk(k);
1436 out.bulk(user);
1437 }
1438 });
1439 }
1440 } else if is(sub, b"SET") {
1441 // Too few is a wrong number of arguments and an odd number is a syntax
1442 // error, which is not the same sentence and is not the same rule. A
1443 // real server counts the pairs after it has decided there is at least
1444 // one, so `CONFIG SET appendonly` is an arity error and `CONFIG SET
1445 // appendonly no maxmemory` is a syntax one.
1446 if args.len() < 4 {
1447 return Err(args::wrong_arity_sub("config", "set"));
1448 }
1449 if !args.len().is_multiple_of(2) {
1450 return Err(args::syntax());
1451 }
1452 // Every pair is checked before any of them is applied, because a real
1453 // server takes the whole `CONFIG SET` or none of it. `CONFIG SET
1454 // hash-max-listpack-entries 7 set-max-listpack-entries abc` leaves the
1455 // hash setting where it was, which was checked rather than assumed.
1456 let mut writes = [None; 16];
1457 let mut count = 0;
1458 let mut policy = None;
1459 let mut limit = None;
1460 let mut store = None;
1461 let mut ttl = None;
1462 let mut events = None;
1463 let mut password = None;
1464 let mut logged = None;
1465 let mut channels = None;
1466 let mut readonly = None;
1467 let mut coverage: [Option<bool>; 2] = [None, None];
1468 let mut mauth = None;
1469 let mut muser = None;
1470 let mut migration: [Option<i64>; MIGRATION.len()] = [None; MIGRATION.len()];
1471 let mut i = 2;
1472 while i < args.len() {
1473 let (name, value) = (args.get(i), args.get(i + 1));
1474 i += 2;
1475 if is(name, MAXMEMORY.as_bytes()) {
1476 let Some(bytes) = parse_memory(value) else {
1477 return Err(Error::fmt(
1478 Code::Invalid,
1479 format_args!(
1480 "CONFIG SET failed (possibly related to argument '{MAXMEMORY}') - argument must be a memory value"
1481 ),
1482 ));
1483 };
1484 limit = Some(bytes);
1485 continue;
1486 }
1487 if is(name, MAXSTORE.as_bytes()) {
1488 // `-1` before the memory parser sees it, because that parser
1489 // refuses a sign and should keep refusing one: `maxmemory -1`
1490 // is not a very large number and never was.
1491 let parsed = if value == b"-1" {
1492 Some(None)
1493 } else {
1494 parse_memory(value).map(Some)
1495 };
1496 let Some(bytes) = parsed else {
1497 return Err(Error::fmt(
1498 Code::Invalid,
1499 format_args!(
1500 "CONFIG SET failed (possibly related to argument '{MAXSTORE}') - argument must be a memory value or -1"
1501 ),
1502 ));
1503 };
1504 store = Some(bytes);
1505 continue;
1506 }
1507 if is(name, MAXMEMORY_POLICY.as_bytes()) {
1508 // Named twice in one command, the last one wins, which is the
1509 // same rule the ladder settings follow here and is not what a
1510 // real server does with a setting repeated in a single `CONFIG
1511 // SET`. It refuses the command instead, which is D-138.
1512 let Some(p) = Policy::parse(value) else {
1513 return Err(Error::fmt(
1514 Code::Invalid,
1515 format_args!(
1516 "CONFIG SET failed (possibly related to argument '{MAXMEMORY_POLICY}') - argument(s) must be one of the following: {PolicyNames}"
1517 ),
1518 ));
1519 };
1520 policy = Some(p);
1521 continue;
1522 }
1523 // Refused whatever the value is, including the one they are already
1524 // set to, which is the one place a setting here does not take the
1525 // write that changes nothing. That is the reference's answer: a
1526 // protected config is refused before anybody looks at what was
1527 // asked for.
1528 if let Some(protected) = [DIR, DBFILENAME]
1529 .into_iter()
1530 .find(|p| is(name, p.as_bytes()))
1531 {
1532 return Err(Error::fmt(
1533 Code::Unsupported,
1534 format_args!(
1535 "CONFIG SET failed (possibly related to argument '{protected}') - can't set protected config"
1536 ),
1537 ));
1538 }
1539 // Refused whatever the value is, including the one it is already
1540 // set to, which is how a real server answers every immutable
1541 // config: the check is on the name and never reaches the value.
1542 // The names in `SETTINGS` take the value that changes nothing,
1543 // which is a difference and is registered as one.
1544 if is(name, ACLFILE.as_bytes()) {
1545 return Err(Error::fmt(
1546 Code::Unsupported,
1547 format_args!(
1548 "CONFIG SET failed (possibly related to argument '{ACLFILE}') - can't set immutable config"
1549 ),
1550 ));
1551 }
1552 if is(name, ACLLOG_MAX_LEN.as_bytes()) {
1553 let Some(n) = parse_i64(value).filter(|&n| n >= 0) else {
1554 return Err(bad_setting(ACLLOG_MAX_LEN, parse_i64(value).is_some()));
1555 };
1556 logged = Some(n as u64);
1557 continue;
1558 }
1559 if is(name, ACL_PUBSUB_DEFAULT.as_bytes()) {
1560 let Some(at) = CHANNEL_DEFAULTS
1561 .iter()
1562 .position(|w| is(value, w.as_bytes()))
1563 else {
1564 return Err(Error::fmt(
1565 Code::Invalid,
1566 format_args!(
1567 "CONFIG SET failed (possibly related to argument '{ACL_PUBSUB_DEFAULT}') - argument(s) must be one of the following: {}, {}",
1568 CHANNEL_DEFAULTS[0], CHANNEL_DEFAULTS[1]
1569 ),
1570 ));
1571 };
1572 channels = Some(at == 0);
1573 continue;
1574 }
1575 if is(name, REQUIREPASS.as_bytes()) {
1576 // Anything at all is a password, including an empty one, which
1577 // is how a password is taken off again. There is nothing to
1578 // refuse here and a real server refuses nothing either.
1579 password = Some(value);
1580 continue;
1581 }
1582 if let Some(spelling) = REPLICA_READ_ONLY.iter().find(|k| is(name, k.as_bytes())) {
1583 let Some(at) = BOOLS.iter().position(|w| is(value, w.as_bytes())) else {
1584 return Err(Error::fmt(
1585 Code::Invalid,
1586 format_args!(
1587 "CONFIG SET failed (possibly related to argument '{spelling}') - argument must be 'yes' or 'no'"
1588 ),
1589 ));
1590 };
1591 readonly = Some(at == 0);
1592 continue;
1593 }
1594 if let Some(at) = CLUSTER_COVERAGE.iter().position(|k| is(name, k.as_bytes())) {
1595 let Some(word) = BOOLS.iter().position(|w| is(value, w.as_bytes())) else {
1596 return Err(Error::fmt(
1597 Code::Invalid,
1598 format_args!(
1599 "CONFIG SET failed (possibly related to argument '{}') - argument must be 'yes' or 'no'",
1600 CLUSTER_COVERAGE[at]
1601 ),
1602 ));
1603 };
1604 coverage[at] = Some(word == 0);
1605 continue;
1606 }
1607 if is(name, CLUSTER_ENABLED.as_bytes()) || is(name, CLUSTER_CONFIG_FILE.as_bytes()) {
1608 return Err(yo_alloc::allow(|| {
1609 Error::fmt(
1610 Code::Unsupported,
1611 format_args!(
1612 "CONFIG SET failed (possibly related to argument '{}') - can't set immutable config",
1613 String::from_utf8_lossy(name).to_lowercase()
1614 ),
1615 )
1616 }));
1617 }
1618 if let Some((at, (k, knob, memory, least, _))) = MIGRATION
1619 .iter()
1620 .enumerate()
1621 .find(|(_, (k, ..))| is(name, k.as_bytes()))
1622 {
1623 // The one that counts bytes takes a unit and the three that
1624 // count something else do not, which is upstream's split
1625 // between a memory config and an integer one and is why
1626 // `write-pause-timeout 10s` is refused while
1627 // `handoff-max-lag-bytes 10mb` is taken.
1628 let parsed = if *memory {
1629 parse_memory(value).map(|n| n as i64).filter(|n| *n >= 0)
1630 } else {
1631 parse_i64(value)
1632 };
1633 let Some(n) = parsed else {
1634 if *memory {
1635 return Err(Error::fmt(
1636 Code::Invalid,
1637 format_args!(
1638 "CONFIG SET failed (possibly related to argument '{k}') - argument must be a memory value"
1639 ),
1640 ));
1641 }
1642 return Err(bad_setting(k, false));
1643 };
1644 // The archived count is the only one with a ceiling, because it
1645 // is an `int` upstream and the other three are a `long long`.
1646 // The sentence names the pair it was given rather than the pair
1647 // it happens to have, which is what a real server answers.
1648 let most = if *knob == Migration::Archived {
1649 i64::from(i32::MAX)
1650 } else {
1651 i64::MAX
1652 };
1653 if n < *least || n > most {
1654 return Err(Error::fmt(
1655 Code::Invalid,
1656 format_args!(
1657 "CONFIG SET failed (possibly related to argument '{k}') - argument must be between {least} and {most} inclusive"
1658 ),
1659 ));
1660 }
1661 migration[at] = Some(n);
1662 continue;
1663 }
1664 if is(name, MASTERAUTH.as_bytes()) {
1665 // Anything at all, including nothing, which is how the password
1666 // is taken off again. It is read at the next dial rather than
1667 // now, so setting it on a replica whose link is already up takes
1668 // effect the next time that link breaks and comes back.
1669 mauth = Some(value);
1670 continue;
1671 }
1672 if is(name, MASTERUSER.as_bytes()) {
1673 muser = Some(value);
1674 continue;
1675 }
1676 if is(name, NOTIFY.as_bytes()) {
1677 // The only setting here whose error names what was wrong with
1678 // the value rather than what the value should have been, and it
1679 // quotes the accepted characters in the reference's order.
1680 let Some(flags) = notify::parse(value) else {
1681 return Err(Error::fmt(
1682 Code::Invalid,
1683 format_args!(
1684 "CONFIG SET failed (possibly related to argument '{NOTIFY}') - Invalid event class character. Use '{}'.",
1685 notify::ACCEPTED
1686 ),
1687 ));
1688 };
1689 events = Some(flags);
1690 continue;
1691 }
1692 if is(name, SEALED_TTL.as_bytes()) {
1693 let Some(n) = parse_i64(value).filter(|&n| n >= 0) else {
1694 return Err(bad_setting(SEALED_TTL, parse_i64(value).is_some()));
1695 };
1696 ttl = Some(n as u64);
1697 continue;
1698 }
1699 if let Some((k, knob)) = LADDER.iter().find(|(k, _)| is(name, k.as_bytes())) {
1700 let Some(n) = parse_i64(value).filter(|&n| n >= 0) else {
1701 return Err(bad_setting(k, parse_i64(value).is_some()));
1702 };
1703 if count == writes.len() {
1704 // Sixteen pairs is more than the ten names there are, so
1705 // getting here means a name was given twice enough times to
1706 // fill it, and the last one would have won anyway.
1707 return Err(args::syntax());
1708 }
1709 writes[count] = Some((*knob, n as usize));
1710 count += 1;
1711 continue;
1712 }
1713 // The same rule the fixed settings follow, against a number that is
1714 // read off the server instead of written down: a write of the count
1715 // the server already has changes nothing and is taken, and anything
1716 // else is refused, including a value that is not a number at all.
1717 // The comparison is on the parsed number rather than on the text so
1718 // that nothing here has to format the count into a buffer first.
1719 if is(name, IO_THREADS.as_bytes()) {
1720 if parse_i64(value) != Some(server.io_threads() as i64) {
1721 return Err(Error::fmt(
1722 Code::Unsupported,
1723 format_args!(
1724 "CONFIG SET failed (possibly related to argument '{IO_THREADS}') - can't set immutable config"
1725 ),
1726 ));
1727 }
1728 continue;
1729 }
1730 let Some((k, v)) = SETTINGS.iter().find(|(k, _)| is(name, k.as_bytes())) else {
1731 return Err(yo_alloc::allow(|| {
1732 Error::fmt(
1733 Code::Invalid,
1734 format_args!(
1735 "Unknown option or number of arguments for CONFIG SET - '{}'",
1736 String::from_utf8_lossy(name)
1737 ),
1738 )
1739 }));
1740 };
1741 if value != v.as_bytes() {
1742 return Err(Error::fmt(
1743 Code::Unsupported,
1744 format_args!(
1745 "CONFIG SET failed (possibly related to argument '{k}') - can't set immutable config"
1746 ),
1747 ));
1748 }
1749 }
1750 // Every stripe of every database, because these are one server wide
1751 // number in Redis and the fact that a `Keyspace` carries its own copy is
1752 // ours and not the client's problem. A stripe that missed one would put
1753 // a key in a different shape from the same key on the stripe next to it,
1754 // which `OBJECT ENCODING` would then answer differently for depending on
1755 // where the key happened to land.
1756 // The whole database is held while its stripes are set rather than one
1757 // stripe at a time, for the same reason they all get the same number: a
1758 // client that read `OBJECT ENCODING` in the middle of a half done change
1759 // would be told two different things about two keys depending on nothing
1760 // it can see.
1761 for (knob, n) in writes.iter().flatten() {
1762 for at in 0..DATABASES {
1763 let db = server.striped(at);
1764 let mut held = db.hold_many(0..db.width());
1765 for i in 0..db.width() {
1766 write_knob(held.stripe_mut(i), *knob, *n);
1767 }
1768 }
1769 }
1770 if let Some(p) = policy {
1771 for at in 0..DATABASES {
1772 let db = server.striped(at);
1773 let mut held = db.hold_many(0..db.width());
1774 for i in 0..db.width() {
1775 held.stripe_mut(i).set_policy(p);
1776 }
1777 }
1778 }
1779 if let Some(seconds) = ttl {
1780 server.backup().set_ttl(seconds);
1781 }
1782 if let Some(flags) = events {
1783 server.set_notify_flags(flags);
1784 }
1785 if let Some(n) = logged {
1786 server.acl_log().set_max_len(n);
1787 }
1788 if let Some(open) = channels {
1789 server.users().set_open_channels(open);
1790 }
1791 if let Some(yes) = readonly {
1792 server.set_replica_read_only(yes);
1793 }
1794 // One at a time and in the order they were written down, because none
1795 // of the four is read together with any of the others and there is
1796 // nothing here that a half applied pair would break.
1797 for ((_, knob, ..), value) in MIGRATION.iter().zip(migration) {
1798 if let Some(n) = value {
1799 server.set_migration_knob(*knob, n);
1800 }
1801 }
1802 // One write of the pair whichever of the two was named, for the same
1803 // reason the master credentials are written together: they are read as a
1804 // pair and a set of one has to leave the other where it was.
1805 if coverage[0].is_some() || coverage[1].is_some() {
1806 server.set_cluster_coverage(
1807 coverage[0].unwrap_or_else(|| server.cluster_full_coverage()),
1808 coverage[1].unwrap_or_else(|| server.cluster_reads_when_down()),
1809 );
1810 }
1811 // One write of the pair whichever of the two was named, because they
1812 // live together and a set of one has to leave the other where it was.
1813 if mauth.is_some() || muser.is_some() {
1814 let (user, pass) =
1815 yo_alloc::allow(|| server.with_master_auth(|u, p| (u.to_vec(), p.to_vec())));
1816 server.master_auth(muser.unwrap_or(&user), mauth.unwrap_or(&pass));
1817 }
1818 if let Some(value) = password {
1819 // The connections that are already open are left where they are,
1820 // including the one that sent this. See the `auth` module for why
1821 // that is the reference's rule and not an accident of it.
1822 server.set_password(value);
1823 }
1824 // Last, so that a `CONFIG SET maxmemory 1mb maxmemory-policy allkeys-lru`
1825 // has the policy in place before the limit that will act on it. The two
1826 // in the other order would run the first eviction under whatever the
1827 // policy used to be, which for a fresh server is `noeviction` and would
1828 // refuse the next write instead of making room for it.
1829 if let Some(bytes) = store {
1830 server.set_maxstore(bytes);
1831 }
1832 if let Some(bytes) = limit {
1833 server.set_maxmemory(bytes);
1834 }
1835 out.ok();
1836 } else if is(sub, b"RESETSTAT") {
1837 server.reset_stats();
1838 out.ok();
1839 } else if is(sub, b"REWRITE") {
1840 return Err(Error::new(
1841 Code::Unsupported,
1842 "The server is running without a config file",
1843 ));
1844 } else if is(sub, b"HELP") {
1845 help(out, CONFIG_HELP);
1846 } else {
1847 return Err(args::unknown_subcommand(sub, "CONFIG"));
1848 }
1849 Ok(())
1850}
1851
1852// -------------------------------------------------------------------- INFO
1853
1854/// `INFO [section ...]`.
1855///
1856/// Every number in here is one this layer can actually answer. There is no
1857/// `rdb_last_save_time` because there is no save, and a field that is not there
1858/// is a client falling back rather than a client believing a zero.
1859///
1860/// The `CPU` section used to be missing for the same reason and is here now,
1861/// because nothing measured it and then something did. It is one `getrusage`
1862/// call in [`super::cpu`], and the reason it went in is that Redis's own
1863/// `unit/info-command` tests fail without it: a monitoring tool graphs
1864/// processor time against wall clock to decide whether a server is busy or
1865/// waiting, so an absent field there is a real hole and not a tidy omission.
1866fn info(server: &Server, args: Args<'_>, out: &mut Out) {
1867 // Redis keeps two lists: the sections a bare `INFO` hands back, and the ones
1868 // that have to be asked for by name or by `all`. `commandstats` is in the
1869 // second, along with `latencystats` and `errorstats`, because they grow with
1870 // the number of distinct commands a server has seen and a monitoring tool
1871 // polling `INFO` every second does not want them.
1872 //
1873 // `unit/info-command` is exactly this distinction written down: it asks for
1874 // `INFO default` and insists `rejected_calls` is not in the answer, then
1875 // asks for `INFO all` and insists that it is.
1876 let named = |section: &str| (1..args.len()).any(|i| is(args.get(i), section.as_bytes()));
1877 let everything = (1..args.len()).any(|i| {
1878 let a = args.get(i);
1879 is(a, b"all") || is(a, b"everything")
1880 });
1881 let by_default = args.len() == 1 || (1..args.len()).any(|i| is(args.get(i), b"default"));
1882 let want = |section: &str| by_default || everything || named(section);
1883 let extra = |section: &str| everything || named(section);
1884 // One string, built once and written once. It allocates, which is allowed
1885 // here and nowhere near the commands that count: `INFO` is a monitoring
1886 // call and it is not on the path M2 is measured on.
1887 let text = yo_alloc::allow(|| {
1888 let mut s = String::with_capacity(1024);
1889 if want("server") {
1890 let _ = write!(
1891 s,
1892 "# Server\r\nredis_version:{REPORTED_VERSION}\r\nyo_version:{}\r\n\
1893 redis_mode:{}\r\narch_bits:{}\r\nprocess_id:0\r\n\
1894 run_id:0000000000000000000000000000000000000000\r\ntcp_port:{}\r\n\
1895 uptime_in_seconds:{}\r\nio_threads_active:{}\r\n\r\n",
1896 env!("CARGO_PKG_VERSION"),
1897 if server.cluster_enabled() {
1898 "cluster"
1899 } else {
1900 "standalone"
1901 },
1902 usize::BITS,
1903 // The port the socket was actually bound to, which whoever bound
1904 // it told the server. Nought on an embedded caller that never
1905 // opened one, which is honest: there is no port.
1906 server.announced_port(),
1907 server.uptime_secs(),
1908 // The configured count, which is what Redis means by this field:
1909 // it is how many threads the server has for reading and writing
1910 // and not how many are busy at the moment the client asked.
1911 server.io_threads(),
1912 );
1913 }
1914 if want("clients") {
1915 let _ = write!(
1916 s,
1917 "# Clients\r\nconnected_clients:{}\r\nblocked_clients:{}\r\n\
1918 pubsub_clients:{}\r\ncluster_connections:0\r\n\r\n",
1919 server
1920 .totals()
1921 .clients
1922 .saturating_sub(server.replica_count()),
1923 server.parked(),
1924 server.pubsub_counts().clients,
1925 );
1926 }
1927 if want("memory") {
1928 // Both the cap and the quarter of it, because the quarter is an
1929 // empirical number and somebody surprised by it should be able to
1930 // see what it was a quarter of without reading the source. The
1931 // reasoning is written out in `cap`.
1932 let cap = crate::cap::cap();
1933 let compact = server.compaction();
1934 // Read out of its stripe before the write, because an argument list
1935 // keeps every temporary in it alive until the whole call is over
1936 // and one of the other arguments walks that same stripe.
1937 let policy = server.settings().policy().name();
1938 let _ = write!(
1939 s,
1940 "# Memory\r\nused_memory:{}\r\nused_memory_dataset:{}\r\n\
1941 used_memory_overhead:{}\r\nmem_arena_bytes:{}\r\n\
1942 mem_arena_segments:{}\r\nmem_arena_listed:{}\r\n\
1943 mem_compact_walked:{}\r\n\
1944 mem_compact_moved:{}\r\nmem_compact_bytes:{}\r\n\
1945 mem_index_bytes:{}\r\n\
1946 mem_client_buffers:{}\r\ntotal_system_memory:{}\r\n\
1947 mem_cgroup_limit:{}\r\nmem_limit:{}\r\nmem_budget:{}\r\n\
1948 maxmemory:{}\r\nmaxmemory_policy:{}\r\n\
1949 maxstore:{}\r\nyo_store_bytes:{}\r\nyo_memory_regime:{}\r\n\r\n",
1950 server.memory_bytes(),
1951 server.dataset_bytes(),
1952 server.memory_bytes() - server.dataset_bytes(),
1953 server.arena_bytes(),
1954 server.segment_count(),
1955 server.listed_runs(),
1956 compact.walked,
1957 compact.moved,
1958 compact.bytes,
1959 server.index_bytes(),
1960 server.conn_bytes(),
1961 cap.host.unwrap_or(0),
1962 cap.cgroup.unwrap_or(0),
1963 cap.limit().unwrap_or(0),
1964 cap.budget(),
1965 server.maxmemory(),
1966 policy,
1967 server.maxstore().map_or(-1, |n| n as i64),
1968 server.store_bytes(),
1969 server.regime(),
1970 );
1971 }
1972 if want("persistence") {
1973 persist::info(server, &mut s);
1974 }
1975 if want("stats") {
1976 // The cold counters live here and not in the memory section,
1977 // because they are totals since the server started and everything
1978 // in that section is a level right now. `yo_cold_faults` over the
1979 // point reads a run issued is the ratio G9 is a gate on, and it
1980 // cannot be worked out from outside the server.
1981 let cold = server.cold_stats();
1982 let totals = server.totals();
1983 let subs = server.pubsub_counts();
1984 // The five ACL counters last, which is where a real server puts them
1985 // too: they are appended after the rest of the section rather than
1986 // written with it.
1987 let denied = server.acl_log().counters();
1988 let _ = write!(
1989 s,
1990 "# Stats\r\ntotal_connections_received:{}\r\n\
1991 total_commands_processed:{}\r\nexpired_subkeys:{}\r\n\
1992 expired_subkeys_active:{}\r\nexpired_keys:{}\r\n\
1993 evicted_keys:{}\r\nkeyspace_hits:{}\r\nkeyspace_misses:{}\r\n\
1994 yo_cold_demoted:{}\r\nyo_cold_promoted:{}\r\n\
1995 yo_cold_faults:{}\r\nyo_cold_served:{}\r\nyo_cold_bytes_out:{}\r\n\
1996 yo_cold_bytes_in:{}\r\npubsub_channels:{}\r\n\
1997 pubsub_patterns:{}\r\npubsubshard_channels:{}\r\n\
1998 acl_access_denied_auth:{}\r\nacl_access_denied_cmd:{}\r\n\
1999 acl_access_denied_key:{}\r\nacl_access_denied_channel:{}\r\n\
2000 acl_access_denied_tls_cert:{}\r\n\r\n",
2001 totals.connections,
2002 totals.commands,
2003 server.expired_fields(),
2004 server.expired_fields_active(),
2005 server.expired_keys(),
2006 server.evicted_keys(),
2007 server.keyspace_hits(),
2008 server.keyspace_misses(),
2009 cold.demoted,
2010 cold.promoted,
2011 cold.faults,
2012 cold.served,
2013 cold.bytes_out,
2014 cold.bytes_in,
2015 subs.channels,
2016 subs.patterns,
2017 subs.shard,
2018 denied[0],
2019 denied[1],
2020 denied[2],
2021 denied[3],
2022 denied[4],
2023 );
2024 }
2025 if want("cpu") {
2026 // Two of Redis's six are not here. `used_cpu_sys_main_thread` and
2027 // `used_cpu_user_main_thread` need `RUSAGE_THREAD`, which is Linux
2028 // only, and reporting the process totals under a name that says
2029 // main thread would be right on a single threaded server and wrong
2030 // on the one this becomes.
2031 if let Some(u) = cpu::usage() {
2032 let _ = write!(
2033 s,
2034 "# CPU\r\nused_cpu_sys:{:.6}\r\nused_cpu_user:{:.6}\r\n\
2035 used_cpu_sys_children:{:.6}\r\nused_cpu_user_children:{:.6}\r\n\r\n",
2036 u.sys, u.user, u.sys_children, u.user_children,
2037 );
2038 }
2039 }
2040 if want("replication") {
2041 super::repl::info(server, &mut s);
2042 }
2043 if want("cluster") {
2044 // One field, which is the one every client library reads on connect
2045 // to decide whether it needs a slot map at all.
2046 let _ = write!(
2047 s,
2048 "# Cluster\r\ncluster_enabled:{}\r\n\r\n",
2049 u8::from(server.cluster_enabled()),
2050 );
2051 }
2052 if extra("threads") {
2053 // An extra rather than a default section for the reason above: it
2054 // grows with the thread count, and a tool polling `INFO` every
2055 // second on a thirty two thread server does not want thirty two
2056 // more lines every time.
2057 //
2058 // The three numbers are the three questions worth asking of a
2059 // server where a connection belongs to the thread that accepted it.
2060 // `clients` says whether the connections open right now are shared
2061 // out. `connections` says whether they were shared out as they
2062 // arrived, which is a different question, because a split that was
2063 // fair at the start and is unfair now is clients hanging up rather
2064 // than an accept race. `commands` says whether an even split of
2065 // connections turned into an even split of work, which it does not
2066 // when the clients are not all asking for the same thing.
2067 let per = server.per_thread();
2068 let _ = write!(s, "# Threads\r\nio_threads:{}\r\n", per.len());
2069 for (at, thread) in per.iter().enumerate() {
2070 let _ = write!(
2071 s,
2072 "thread_{at}:clients={},connections={},commands={}\r\n",
2073 thread.clients, thread.connections, thread.commands,
2074 );
2075 }
2076 s.push_str("\r\n");
2077 }
2078 if extra("commandstats") {
2079 s.push_str("# Commandstats\r\n");
2080 for (name, row) in server.command_stats() {
2081 let _ = write!(
2082 s,
2083 "cmdstat_{name}:calls={},rejected_calls={},failed_calls={}\r\n",
2084 row.calls, row.rejected, row.failed,
2085 );
2086 }
2087 s.push_str("\r\n");
2088 }
2089 if want("keyspace") {
2090 s.push_str("# Keyspace\r\n");
2091 for i in 0..DATABASES {
2092 let keys = server.dbs[i].len();
2093 if keys > 0 {
2094 // `avg_ttl` is still a zero, and Redis reports a zero there
2095 // too on a server that has never run its active expiry
2096 // cycle, because the number is a running estimate that cycle
2097 // produces rather than something anybody measures on demand.
2098 let expires = server.dbs[i].expires();
2099 let _ = write!(s, "db{i}:keys={keys},expires={expires},avg_ttl=0\r\n");
2100 }
2101 }
2102 s.push_str("\r\n");
2103 }
2104 s
2105 });
2106 out.verbatim(b"txt", text.as_bytes());
2107}
2108
2109// -------------------------------------------------------------------- help
2110
2111/// The `HELP` reply, which is an array of simple strings on both protocols.
2112pub(super) fn help(out: &mut Out, lines: &[&str]) {
2113 out.array(lines.len());
2114 for line in lines {
2115 out.simple(line.as_bytes());
2116 }
2117}
2118
2119/// What `COMMAND HELP` says.
2120const COMMAND_HELP: &[&str] = &[
2121 "COMMAND <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
2122 "(no subcommand)",
2123 " Return details about all commands.",
2124 "COUNT",
2125 " Return the total number of commands in this server.",
2126 "LIST [FILTERBY <MODULE <module-name>|ACLCAT <category>|PATTERN <pattern>>]",
2127 " Return a list of all commands in this server.",
2128 "INFO [<command-name> ...]",
2129 " Return details about multiple commands.",
2130 "DOCS [<command-name> ...]",
2131 " Return documentation details about multiple commands.",
2132 "GETKEYS <full-command>",
2133 " Return the keys from a full command.",
2134 "HELP",
2135 " Print this help.",
2136];
2137
2138/// What `CONFIG HELP` says.
2139const CONFIG_HELP: &[&str] = &[
2140 "CONFIG <subcommand> [<arg> [value] [opt] ...]. Subcommands are:",
2141 "GET <pattern>",
2142 " Return parameters matching the glob-like <pattern> and their values.",
2143 "SET <directive> <value>",
2144 " Set the configuration <directive> to <value>.",
2145 "RESETSTAT",
2146 " Reset statistics reported by the INFO command.",
2147 "REWRITE",
2148 " Rewrite the configuration file.",
2149 "HELP",
2150 " Print this help.",
2151];
2152
2153#[cfg(test)]
2154mod tests {
2155 use super::{BOOLS, REPLICA_READ_ONLY, SETTINGS};
2156
2157 /// The backlog setting is a compiled in number written out twice, and the
2158 /// two have to be the same number: a client that reads `repl-backlog-size`
2159 /// and then works out how far behind a replica may fall before a full resync
2160 /// is reading this to answer that question.
2161 #[test]
2162 fn the_backlog_setting_is_the_size_the_backlog_actually_is() {
2163 let said = SETTINGS
2164 .iter()
2165 .find(|(k, _)| *k == "repl-backlog-size")
2166 .expect("the setting is there")
2167 .1;
2168 assert_eq!(
2169 said.parse::<usize>().expect("a number"),
2170 super::super::repl::BACKLOG_BYTES
2171 );
2172 }
2173
2174 /// The two spellings are one setting and the reference answers to both, so a
2175 /// script written against either works here.
2176 #[test]
2177 fn the_read_only_setting_answers_to_both_of_its_names() {
2178 assert_eq!(REPLICA_READ_ONLY, ["replica-read-only", "slave-read-only"]);
2179 assert_eq!(BOOLS, ["yes", "no"]);
2180 }
2181}