You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iggy.apache.org by "mmodzelewski (via GitHub)" <gi...@apache.org> on 2026/09/28 15:45:22 UTC
[PR] feat(server): guard against running out of file descriptors [iggy]
mmodzelewski opened a new pull request, #4318:
URL: https://github.com/apache/iggy/pull/4318
The server did not raise its open-file limit. If a storage open
failed with EMFILE or ENFILE, the shard kept serving and failed each
later write. Accept loops retried at once and spun the shard at full
CPU, because the kernel keeps the connection in the backlog.
At startup, the server now raises the soft RLIMIT_NOFILE to the hard
limit. On macOS, it uses OPEN_MAX if the hard limit is higher.
If a storage open fails with EMFILE or ENFILE, the process now stops
with exit status 4. Every later open fails too, so a supervisor
restart is the repair. fatal() moves to server_common and writes to
stderr, because exit stops the log appenders before they flush.
Accept loops wait one second after EMFILE or ENFILE. They do not
stop the process, because a client with many sockets can then stop
the node.
The new [metadata] partitions_max limits the partitions of a node.
CreateTopic and CreatePartitions past the limit fail before
consensus with PartitionsLimitReached (2022). The limit is soft,
because concurrent creates can go over it. 0 means no limit.
Shard 0 logs process and host usage, with open descriptors, every
logging.sysinfo_print_interval (10 s by default, 0 disables it).
Partition groups log the restored-view line at debug, because one
INFO line per partition flooded the boot log.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #4318:
URL: https://github.com/apache/iggy/pull/4318#issuecomment-5875734973
## [Codecov](https://app.codecov.io/gh/apache/iggy/pull/4318?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `50.00000%` with `5 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 87.42%. Comparing base ([`6cf56d6`](https://app.codecov.io/gh/apache/iggy/commit/6cf56d6314441adcd00df694c08feb733b931739?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`2370578`](https://app.codecov.io/gh/apache/iggy/commit/2370578fd9586271aee0ee2e35fbbdfeb66e7b9f?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 1 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/iggy/pull/4318?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [foreign/go/errors/errors\_gen.go](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=foreign%2Fgo%2Ferrors%2Ferrors_gen.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Zm9yZWlnbi9nby9lcnJvcnMvZXJyb3JzX2dlbi5nbw==) | 50.00% | [5 Missing :warning: ](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #4318 +/- ##
============================================
- Coverage 87.79% 87.42% -0.37%
Complexity 1575 1575
============================================
Files 1290 1290
Lines 227420 227393 -27
Branches 190783 190746 -37
============================================
- Hits 199656 198791 -865
- Misses 23063 23956 +893
+ Partials 4701 4646 -55
```
| [Components](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=components&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [Rust Core](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `88.91% <ø> (+<0.01%)` | :arrow_up: |
| [Java SDK](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `68.68% <ø> (ø)` | |
| [C# SDK](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `77.42% <ø> (ø)` | |
| [Python SDK](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `90.97% <ø> (ø)` | |
| [PHP SDK](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `85.67% <ø> (ø)` | |
| [Node SDK](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `96.43% <ø> (ø)` | |
| [Go SDK](https://app.codecov.io/gh/apache/iggy/pull/4318/components?src=pr&el=component&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `57.54% <50.00%> (-12.51%)` | :arrow_down: |
| [Files with missing lines](https://app.codecov.io/gh/apache/iggy/pull/4318?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [core/common/src/error/iggy\_error.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fcommon%2Fsrc%2Ferror%2Figgy_error.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb21tb24vc3JjL2Vycm9yL2lnZ3lfZXJyb3IucnM=) | `100.00% <ø> (ø)` | |
| [core/configs/src/common/defaults.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fdefaults.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vZGVmYXVsdHMucnM=) | `100.00% <ø> (ø)` | |
| [core/configs/src/common/displays.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fdisplays.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vZGlzcGxheXMucnM=) | `100.00% <ø> (ø)` | |
| [core/configs/src/common/system.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fcommon%2Fsystem.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9jb21tb24vc3lzdGVtLnJz) | `100.00% <ø> (ø)` | |
| [core/configs/src/server\_config/defaults.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fserver_config%2Fdefaults.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9zZXJ2ZXJfY29uZmlnL2RlZmF1bHRzLnJz) | `100.00% <ø> (ø)` | |
| [core/configs/src/server\_config/displays.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fserver_config%2Fdisplays.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9zZXJ2ZXJfY29uZmlnL2Rpc3BsYXlzLnJz) | `100.00% <ø> (ø)` | |
| [core/configs/src/server\_config/metadata.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconfigs%2Fsrc%2Fserver_config%2Fmetadata.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25maWdzL3NyYy9zZXJ2ZXJfY29uZmlnL21ldGFkYXRhLnJz) | `98.21% <ø> (ø)` | |
| [core/consensus/src/impls.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconsensus%2Fsrc%2Fimpls.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25zZW5zdXMvc3JjL2ltcGxzLnJz) | `93.43% <ø> (-0.01%)` | :arrow_down: |
| [core/consensus/src/lib.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fconsensus%2Fsrc%2Flib.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9jb25zZW5zdXMvc3JjL2xpYi5ycw==) | `0.00% <ø> (ø)` | |
| [core/journal/src/durable\_storage.rs](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree&filepath=core%2Fjournal%2Fsrc%2Fdurable_storage.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y29yZS9qb3VybmFsL3NyYy9kdXJhYmxlX3N0b3JhZ2UucnM=) | `84.01% <ø> (+0.40%)` | :arrow_up: |
| ... and [30 more](https://app.codecov.io/gh/apache/iggy/pull/4318?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | |
... and [39 files with indirect coverage changes](https://app.codecov.io/gh/apache/iggy/pull/4318/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
</details>
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "mmodzelewski (via GitHub)" <gi...@apache.org>.
mmodzelewski merged PR #4318:
URL: https://github.com/apache/iggy/pull/4318
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4136702515
##########
core/server/src/sysinfo_probe.rs:
##########
@@ -105,32 +117,52 @@ pub fn stats_disk_space() -> (u64, u64) {
})
}
+/// Count open descriptors, scanning where the kernel keeps no count, and
+/// publish the result for [`probe_system_stats`].
+///
+/// Only the sysinfo printer calls this, once per interval. The scan cost
+/// grows with the count, so `GetStats` reads the published value instead of
+/// scanning on the request path. The value is as old as the printer interval,
+/// and stays 0 while the printer is disabled.
+pub fn publish_open_files_count() {
+ PUBLISHED_OPEN_FILES_COUNT.store(count_open_files().unwrap_or(0), Ordering::Relaxed);
+}
+
+/// Probe through this thread's [`SYSINFO`], the `GetStats` path.
pub fn probe_system_stats() -> SystemStats {
- let host = HOST_IDENTITY.get_or_init(HostIdentity::probe);
- let probe = SYSINFO.with_borrow_mut(|slot| {
- let sys = slot.get_or_insert_with(SysinfoSystem::new);
- SystemProbe::capture(sys)
- });
-
- SystemStats {
- process_id: probe.process_id,
- cpu_usage: probe.cpu_usage,
- total_cpu_usage: probe.total_cpu_usage,
- memory_usage: probe.memory_usage,
- total_memory: probe.total_memory,
- available_memory: probe.available_memory,
- // sysinfo reports whole seconds; the wire fields are micros (the
- // SDK decodes them via `IggyDuration` / `IggyTimestamp::from`, both
- // micro-based).
- run_time: probe.run_time_secs.saturating_mul(1_000_000),
- start_time: probe.start_time_secs.saturating_mul(1_000_000),
- read_bytes: probe.read_bytes,
- written_bytes: probe.written_bytes,
- threads_count: probe.threads_count,
- hostname: host.hostname.clone(),
- os_name: host.os_name.clone(),
- os_version: host.os_version.clone(),
- kernel_version: host.kernel_version.clone(),
+ SYSINFO
+ .with_borrow_mut(|slot| SystemStats::capture(slot.get_or_insert_with(SysinfoSystem::new)))
+}
+
+impl SystemStats {
+ /// Probe through `sys`. A caller that keeps its own `sys` gets CPU deltas
+ /// over its own interval, and does not reset the window of `GetStats`.
+ pub fn capture(sys: &mut SysinfoSystem) -> Self {
+ let host = HOST_IDENTITY.get_or_init(HostIdentity::probe);
+ let probe = SystemProbe::capture(sys);
+ Self {
+ process_id: probe.process_id,
+ cpu_usage: probe.cpu_usage,
+ total_cpu_usage: probe.total_cpu_usage,
+ memory_usage: probe.memory_usage,
+ total_memory: probe.total_memory,
+ available_memory: probe.available_memory,
+ // sysinfo reports whole seconds; the wire fields are micros (the
+ // SDK decodes them via `IggyDuration` / `IggyTimestamp::from`, both
+ // micro-based).
+ run_time: probe.run_time_secs.saturating_mul(1_000_000),
+ start_time: probe.start_time_secs.saturating_mul(1_000_000),
+ read_bytes: probe.read_bytes,
+ written_bytes: probe.written_bytes,
+ threads_count: probe.threads_count,
+ open_files_count: count_open_files_without_scan()
+ .unwrap_or_else(|| PUBLISHED_OPEN_FILES_COUNT.load(Ordering::Relaxed)),
+ open_files_limit: getrlimit(Resource::RLIMIT_NOFILE).map_or(0, |(soft, _)| soft),
Review Comment:
warning: remove `open_files_limit` from stats - it's set once at boot and static for the whole runtime, so there's no sense in having it there. drop it before the SDKs ship the 16-byte tail, or removing it later breaks clients.
##########
core/metadata/src/impls/metadata.rs:
##########
@@ -2220,6 +2236,61 @@ where
}
}
+ /// Node-wide `[metadata] partitions_max` admission for a `CreateTopic` or
+ /// `CreatePartitions`. Other operations pass.
+ ///
+ /// A soft cap: the apply must not branch on node config, so this counts
+ /// the partitions this primary has committed, and creates in flight
+ /// together can overshoot it. A body that does not decode passes here,
+ /// and `prepare_request` evicts the session for it. A create that the
+ /// gated apply refuses, for a missing target or a missing grant, also
+ /// passes, so it gets that error and not the cap's.
+ fn admit_partitions(&self, message: &Message<RoutedRequestHeader>) -> Result<(), IggyError> {
+ let partitions_max = self.partitions_max.get();
+ if partitions_max == 0 {
+ return Ok(());
+ }
+ let header = message.header();
+ let body = &message.as_slice()[size_of::<RoutedRequestHeader>()..header.size as usize];
+ let (requested, stream_id, topic_id) = match header.operation {
+ Operation::CreateTopic => match WireCreateTopicRequest::decode_from(body) {
+ Ok(request) => (request.partitions_count, request.stream_id, None),
+ Err(_) => return Ok(()),
+ },
+ Operation::CreatePartitions => match WireCreatePartitionsRequest::decode_from(body) {
+ Ok(request) => (
+ request.partitions_count,
+ request.stream_id,
+ Some(request.topic_id),
+ ),
+ Err(_) => return Ok(()),
+ },
+ _ => return Ok(()),
+ };
+ let admitted = validate_partitions_limit(partitions_max, requested, || {
Review Comment:
warning: this compares each create against committed partitions only, so in-flight creates don't add up - 96 queued creates of 1000 partitions each can all pass. count queued creates too, or state the real bound in `config.toml` instead of "slightly".
##########
core/server/config.toml:
##########
@@ -407,6 +407,11 @@ rotation_check_interval = "1 h"
# Time to retain log files before deletion. Avoid less than 1s, too.
retention = "7 days"
+# Interval for printing process and host usage (CPU, memory, disk, clients,
Review Comment:
warning: on kernels before 6.2 and on macOS only the printer publishes `open_files_count`, so `sysinfo_print_interval = "0 s"` silently pins it at 0 in `GetStats`. document that here and in the SDK field docs, or publish the count on its own timer.
##########
core/server/src/sysinfo_probe.rs:
##########
@@ -105,32 +117,52 @@ pub fn stats_disk_space() -> (u64, u64) {
})
}
+/// Count open descriptors, scanning where the kernel keeps no count, and
+/// publish the result for [`probe_system_stats`].
+///
+/// Only the sysinfo printer calls this, once per interval. The scan cost
+/// grows with the count, so `GetStats` reads the published value instead of
+/// scanning on the request path. The value is as old as the printer interval,
+/// and stays 0 while the printer is disabled.
+pub fn publish_open_files_count() {
+ PUBLISHED_OPEN_FILES_COUNT.store(count_open_files().unwrap_or(0), Ordering::Relaxed);
Review Comment:
nit: on kernels before 6.2 the scan needs a free fd, so right at exhaustion it fails and this stores 0, which reads as "unknown". keep the previous count when `count_open_files()` returns `None`.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,163 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// A storage open for a write or a sync failed because the process
+ /// (`EMFILE`) or the host (`ENFILE`) has no free file descriptor. The shard
+ /// cannot persist that write, and serving on only fails each later write in
+ /// turn.
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
+ tracing::error!(
+ target: "iggy.fatal.diag",
+ reason = ?reason,
+ exit_status = reason.exit_status(),
+ "{message}"
+ );
+ let _ = writeln!(
+ std::io::stderr().lock(),
+ "iggy fatal: reason={reason:?} exit_status={}: {message}",
+ reason.exit_status()
+ );
+ std::process::exit(i32::from(reason.exit_status()));
+}
+
+/// Storage results that stop the process when no file descriptor is free.
+///
+/// Only for opens that write, create, truncate or sync, and for read-only
+/// opens that are one step of such a write: the existence probes of segment
+/// setup, or an open that exists only to sync. A failure there leaves the
+/// write half done. Other reads keep their own error path: a failed read fails
+/// only its request, and the descriptors that fill the table can be client
+/// sockets or other reads that close again soon.
+/// Accept loops never stop here, see `message_bus::accept`.
+pub trait ExitOnDescriptorExhaustion: Sized {
+ /// Pass the result through, unless it failed with `EMFILE` or `ENFILE`: then
+ /// stop the process with [`FatalReason::DescriptorsExhausted`]. `operation`
+ /// names what was being opened, for the fatal message.
+ #[must_use]
+ fn exit_on_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self;
+}
+
+impl<T> ExitOnDescriptorExhaustion for io::Result<T> {
+ fn exit_on_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self {
+ if let Err(error) = &self
+ && is_descriptor_exhaustion(error)
+ {
+ exit_descriptors_exhausted(error, &operation());
Review Comment:
critical: exiting here skips the shutdown flush `FatalCommit` used to run - `EMFILE` doesn't stop writes to open fds, so under the default replicated/replicated policy we drop acked messages that could be flushed. return the error and exit 4 after the shutdown flush.
##########
core/metadata/src/impls/metadata.rs:
##########
@@ -4260,19 +4343,44 @@ fn unreplayable_secret_refusal(
)
}
+/// `requested` more partitions on top of the `committed` count against the
+/// `partitions_max` cap. Zero is no cap, and `committed` is read only when a
+/// cap is set. A create of zero partitions adds nothing, so it passes also
+/// on a node already past the cap, for example after the cap was lowered.
+fn validate_partitions_limit(
+ partitions_max: u32,
+ requested: u32,
+ committed: impl FnOnce() -> usize,
+) -> Result<(), IggyError> {
+ if partitions_max == 0 || requested == 0 {
Review Comment:
simplification: the `partitions_max == 0` return repeats line 2250, and the lazy closure buys nothing on this cold path. keep that check at 2250 only and pass the count as a plain `usize`.
##########
core/message_bus/src/connection_cap.rs:
##########
@@ -0,0 +1,166 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Node-wide cap on open client sockets.
+//!
+//! Shard 0 accepts every client socket, but the owning shard closes it. Each
+//! socket therefore carries a [`ConnectionPermit`] to its owning shard, and
+//! the permit frees its slot on drop.
+//!
+//! The count is a process-wide static, because one node runs per process. A
+//! permit that pointed at its count would add 16 bytes to the client setup
+//! frames, and every slot of every shard inbox pays for the largest frame.
+
+use std::cell::Cell;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::{Duration, Instant};
+use tracing::warn;
+
+/// Shortest interval between two refusal warnings. A client that reconnects
+/// in a loop would otherwise log one line per attempt.
+const REFUSAL_LOG_INTERVAL: Duration = Duration::from_secs(10);
+
+static LIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
+
+/// The open client sockets of the node, capped at `max`.
+///
+/// Owned by shard 0, where every client accept runs.
+#[derive(Debug)]
+pub struct ConnectionCap {
+ max: Option<usize>,
+ last_refusal_log: Cell<Option<Instant>>,
+ refused_since_log: Cell<u64>,
+}
+
+impl ConnectionCap {
+ /// A cap of `max` open sockets. `None` counts sockets and refuses none.
+ #[must_use]
+ pub const fn new(max: Option<usize>) -> Self {
+ Self {
+ max,
+ last_refusal_log: Cell::new(None),
+ refused_since_log: Cell::new(0),
+ }
+ }
+
+ #[must_use]
+ pub const fn max(&self) -> Option<usize> {
Review Comment:
simplification: `ConnectionCap::max()` has no callers, tests included. drop it.
##########
core/server_common/src/segment_storage/messages_writer.rs:
##########
@@ -56,6 +57,7 @@ impl MessagesWriter {
let file = opts
.open(file_path)
.await
+ .exit_on_descriptor_exhaustion(|| format!("opening {file_path}"))
Review Comment:
warning: a create that crosses the fd limit commits on every replica, then this open exits all of them and the cluster loses quorum. derive a nonzero `partitions_max` default from the soft limit, or keep the old reconciler error here.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,163 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// A storage open for a write or a sync failed because the process
+ /// (`EMFILE`) or the host (`ENFILE`) has no free file descriptor. The shard
+ /// cannot persist that write, and serving on only fails each later write in
+ /// turn.
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
+ tracing::error!(
+ target: "iggy.fatal.diag",
Review Comment:
nit: this renames the fatal log target from `iggy.consensus.diag` (what 0.9.0 ships) to `iggy.fatal.diag`, so existing log filters stop matching. keep the old target or call out the rename in the release notes.
##########
core/server/src/sysinfo_printer.rs:
##########
@@ -0,0 +1,205 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Periodic one-line log of process and host usage.
+//!
+//! Spawned on shard 0 only: the numbers describe the whole process, so one
+//! line per node is enough, and the client count is already a cross-shard
+//! gather.
+
+use crate::responses::{StatsTotals, stats_totals};
+use crate::shell::ServerShard;
+use crate::sysinfo_probe::{SystemStats, publish_open_files_count, stats_disk_space};
+use iggy_common::IggyByteSize;
+use shard::Receiver;
+use std::fmt;
+use std::rc::Rc;
+use std::time::Duration;
+use sysinfo::System as SysinfoSystem;
+use tracing::level_filters::LevelFilter;
+use tracing::{error, info, trace};
+
+/// Run the printer until `stop` fires, logging one line every `interval`.
+pub async fn run_sysinfo_printer(shard: Rc<ServerShard>, stop: Receiver<()>, interval: Duration) {
+ info!("System info logger is enabled, OS info will be printed every: {interval:?}");
+ // Not the shared `GetStats` sampler: a tick would reset its CPU window, and
+ // a `GetStats` on shard 0 right after a tick would show CPU near zero.
+ // Sampled once now, so the first line covers a full interval.
+ let mut system = SysinfoSystem::new();
+ SystemStats::capture(&mut system);
+ loop {
+ // `Ok(_)`: stop signalled -> exit. `Err(_)`: interval elapsed -> print.
+ match compio::time::timeout(interval, stop.recv()).await {
+ Ok(_) => break,
+ Err(_) => print_sysinfo(&shard, &mut system).await,
+ }
+ }
+ trace!(shard = shard.id, "sysinfo printer exited");
+}
+
+async fn print_sysinfo(shard: &Rc<ServerShard>, system: &mut SysinfoSystem) {
+ // `GetStats` reads this count where the kernel keeps none, so it is
+ // published also while the line itself is filtered out.
+ publish_open_files_count();
Review Comment:
warning: on kernels before 6.2 this scans `/proc/self/fd` on shard 0 every tick - a readdir over 40k fds took 13-28 ms on my box. move the scan off the shard thread, or report 0 where the kernel has no count.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,163 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// A storage open for a write or a sync failed because the process
+ /// (`EMFILE`) or the host (`ENFILE`) has no free file descriptor. The shard
+ /// cannot persist that write, and serving on only fails each later write in
+ /// turn.
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
+ tracing::error!(
+ target: "iggy.fatal.diag",
+ reason = ?reason,
+ exit_status = reason.exit_status(),
+ "{message}"
+ );
+ let _ = writeln!(
+ std::io::stderr().lock(),
+ "iggy fatal: reason={reason:?} exit_status={}: {message}",
+ reason.exit_status()
+ );
+ std::process::exit(i32::from(reason.exit_status()));
+}
+
+/// Storage results that stop the process when no file descriptor is free.
+///
+/// Only for opens that write, create, truncate or sync, and for read-only
+/// opens that are one step of such a write: the existence probes of segment
+/// setup, or an open that exists only to sync. A failure there leaves the
+/// write half done. Other reads keep their own error path: a failed read fails
+/// only its request, and the descriptors that fill the table can be client
+/// sockets or other reads that close again soon.
+/// Accept loops never stop here, see `message_bus::accept`.
+pub trait ExitOnDescriptorExhaustion: Sized {
+ /// Pass the result through, unless it failed with `EMFILE` or `ENFILE`: then
+ /// stop the process with [`FatalReason::DescriptorsExhausted`]. `operation`
+ /// names what was being opened, for the fatal message.
+ #[must_use]
+ fn exit_on_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self;
+}
+
+impl<T> ExitOnDescriptorExhaustion for io::Result<T> {
+ fn exit_on_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self {
+ if let Err(error) = &self
+ && is_descriptor_exhaustion(error)
+ {
+ exit_descriptors_exhausted(error, &operation());
+ }
+ self
+ }
+}
+
+/// `EMFILE` (this process is at its `RLIMIT_NOFILE`) or `ENFILE` (the host is
+/// at its system-wide file table limit).
+#[must_use]
+pub fn is_descriptor_exhaustion(error: &io::Error) -> bool {
+ error
+ .raw_os_error()
+ .is_some_and(|code| code == Errno::EMFILE as i32 || code == Errno::ENFILE as i32)
+}
+
+fn exit_descriptors_exhausted(error: &io::Error, operation: &str) -> ! {
+ let limits = getrlimit(Resource::RLIMIT_NOFILE).map_or_else(
+ |errno| format!("RLIMIT_NOFILE unreadable: {errno}"),
+ |(soft, hard)| format!("RLIMIT_NOFILE soft={soft} hard={hard}"),
+ );
+ fatal(
+ FatalReason::DescriptorsExhausted,
+ &format!("no free file descriptor while {operation}: {error} ({limits})"),
+ )
+}
+
+#[cfg(test)]
Review Comment:
warning: the tests only cover errno classification and pass-through - nothing proves the exit code 4 or that a restart after it recovers the data. add an integration test that lowers the hard `RLIMIT_NOFILE` and asserts both.
##########
core/partitions/src/install_backup.rs:
##########
@@ -135,9 +136,11 @@ async fn link_tree<S: DurableStorage>(
// Transfer unlinks or atomically replaces these frozen files.
// Hard links retain the old bytes without copying segment data.
storage.hard_link(&source.join(&name), &destination).await?;
+ // Read-only, but only to sync, so it stops like a write open.
storage
.open(&destination, OpenMode::Read)
- .await?
+ .await
+ .exit_on_descriptor_exhaustion(|| format!("opening {}", destination.display()))?
Review Comment:
nit: this read open exits on `EMFILE` like a write open, but `copy_file` returns `EMFILE` from its source open and exits on the destination open, so the outcome depends on which open fails first. pick one rule for read-then-write pairs.
##########
core/message_bus/src/replica/listener.rs:
##########
@@ -109,6 +110,7 @@ pub async fn run(listener: TcpListener, token: ShutdownToken, on_accepted: Accep
}
Err(e) => {
error!("Replica listener accept failed: {e}");
+ pause_after_accept_error(&e).await;
Review Comment:
nit: the doc on `run` (line 92) says the loop never awaits anything but `accept()`, but it now sleeps here after `EMFILE`/`ENFILE`. mention the pause there.
##########
core/server/config.toml:
##########
@@ -855,6 +860,12 @@ journal_slots = 1024
# it lifts both. Must be between 2 and 65536.
clients_table_max = 8192
+# Cap on partitions across all streams and topics of the node. A request to
Review Comment:
nit: this reads like a per-node cap, but only the metadata primary checks it, with its own value, for creates across the whole cluster. say that the primary enforces it, so every node needs the same value.
##########
core/configs/src/common/system.rs:
##########
@@ -44,6 +45,10 @@ pub struct LoggingConfig {
#[config_env(leaf)]
#[serde_as(as = "DisplayFromStr")]
pub retention: IggyDuration,
+ #[config_env(leaf)]
+ #[serde_as(as = "DisplayFromStr")]
+ #[serde(default = "default_sysinfo_print_interval")]
+ pub sysinfo_print_interval: IggyDuration,
Review Comment:
nit: validation floors `retention` and `rotation_check_interval` at 1 s but lets this through at any nonzero value, so `1 ms` rescans `/proc/self/fd` every millisecond on older kernels. reject nonzero values below 1 s in `LoggingConfig::validate` too.
##########
.github/actions/go/pre-merge/action.yml:
##########
@@ -85,7 +85,7 @@ runs:
if: inputs.task == 'lint'
uses: golangci/golangci-lint-action@v9
with:
- version: v2.11.3
+ version: v2.13.2
Review Comment:
nit: the PR body mentions the golangci-lint bump to v2.13.2 (six pins) but not why. if it's unrelated to fd limits, move it to its own chore commit.
##########
core/system_stats/src/lib.rs:
##########
@@ -106,6 +106,24 @@ impl SystemProbe {
}
}
+/// Descriptors the calling process holds open, or `None` where sysinfo
+/// cannot count them.
+///
+/// Kept out of [`SystemProbe::capture`] because the fallback cost grows with
+/// the count: Linux before 6.2 lists every entry of `/proc/self/fd`, and
+/// macOS copies the whole descriptor table. The Linux listing also counts
+/// the descriptor of the scan itself.
+pub fn count_open_files() -> Option<u64> {
+ count_open_files_without_scan().or_else(scan_open_files)
+}
+
+/// The open-descriptor count where the kernel keeps it, or `None` where only
+/// the scan in [`count_open_files`] can find it. Cheap enough for a request
+/// path: Linux 6.2 and later count the descriptor bitmap for one `stat`.
+pub fn count_open_files_without_scan() -> Option<u64> {
Review Comment:
simplification: `count_open_files_without_scan` only forwards to the private `kernel_open_files_count`. give the two `cfg` variants the public name and drop the wrapper.
##########
core/partitions/src/state_transfer.rs:
##########
@@ -3875,6 +3908,53 @@ impl fmt::Display for SegmentLoadError {
impl std::error::Error for SegmentLoadError {}
+/// A failed read inside a served segment, with where it failed.
+///
+/// It travels as an `io::Error` of the read's own kind and keeps the OS error
+/// as its source, so [`SegmentLoadError::classify`] still tells a dying disk
+/// from a stale offer. A message-only rewrap hid `EIO` behind `Other`.
+#[derive(Debug)]
+struct SegmentReadError {
Review Comment:
simplification: `SegmentReadError` only adds the read position to the OS error, at the cost of a struct and three trait impls. return the raw `io::Error` from the read at line 3801 and log the position there.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "mmodzelewski (via GitHub)" <gi...@apache.org>.
mmodzelewski commented on PR #4318:
URL: https://github.com/apache/iggy/pull/4318#issuecomment-5910797976
/ready
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "mmodzelewski (via GitHub)" <gi...@apache.org>.
mmodzelewski commented on PR #4318:
URL: https://github.com/apache/iggy/pull/4318#issuecomment-5898568644
/ready
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4136718752
##########
core/server/src/sysinfo_printer.rs:
##########
@@ -0,0 +1,205 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Periodic one-line log of process and host usage.
+//!
+//! Spawned on shard 0 only: the numbers describe the whole process, so one
+//! line per node is enough, and the client count is already a cross-shard
+//! gather.
+
+use crate::responses::{StatsTotals, stats_totals};
+use crate::shell::ServerShard;
+use crate::sysinfo_probe::{SystemStats, publish_open_files_count, stats_disk_space};
+use iggy_common::IggyByteSize;
+use shard::Receiver;
+use std::fmt;
+use std::rc::Rc;
+use std::time::Duration;
+use sysinfo::System as SysinfoSystem;
+use tracing::level_filters::LevelFilter;
+use tracing::{error, info, trace};
+
+/// Run the printer until `stop` fires, logging one line every `interval`.
+pub async fn run_sysinfo_printer(shard: Rc<ServerShard>, stop: Receiver<()>, interval: Duration) {
+ info!("System info logger is enabled, OS info will be printed every: {interval:?}");
+ // Not the shared `GetStats` sampler: a tick would reset its CPU window, and
+ // a `GetStats` on shard 0 right after a tick would show CPU near zero.
+ // Sampled once now, so the first line covers a full interval.
+ let mut system = SysinfoSystem::new();
+ SystemStats::capture(&mut system);
+ loop {
+ // `Ok(_)`: stop signalled -> exit. `Err(_)`: interval elapsed -> print.
+ match compio::time::timeout(interval, stop.recv()).await {
+ Ok(_) => break,
+ Err(_) => print_sysinfo(&shard, &mut system).await,
+ }
+ }
+ trace!(shard = shard.id, "sysinfo printer exited");
+}
+
+async fn print_sysinfo(shard: &Rc<ServerShard>, system: &mut SysinfoSystem) {
+ // `GetStats` reads this count where the kernel keeps none, so it is
+ // published also while the line itself is filtered out.
+ publish_open_files_count();
Review Comment:
about this: please figure out something async so that its nonblocking. (+ maybe separate compio task for sysinfo printer?)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4136718752
##########
core/server/src/sysinfo_printer.rs:
##########
@@ -0,0 +1,205 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Periodic one-line log of process and host usage.
+//!
+//! Spawned on shard 0 only: the numbers describe the whole process, so one
+//! line per node is enough, and the client count is already a cross-shard
+//! gather.
+
+use crate::responses::{StatsTotals, stats_totals};
+use crate::shell::ServerShard;
+use crate::sysinfo_probe::{SystemStats, publish_open_files_count, stats_disk_space};
+use iggy_common::IggyByteSize;
+use shard::Receiver;
+use std::fmt;
+use std::rc::Rc;
+use std::time::Duration;
+use sysinfo::System as SysinfoSystem;
+use tracing::level_filters::LevelFilter;
+use tracing::{error, info, trace};
+
+/// Run the printer until `stop` fires, logging one line every `interval`.
+pub async fn run_sysinfo_printer(shard: Rc<ServerShard>, stop: Receiver<()>, interval: Duration) {
+ info!("System info logger is enabled, OS info will be printed every: {interval:?}");
+ // Not the shared `GetStats` sampler: a tick would reset its CPU window, and
+ // a `GetStats` on shard 0 right after a tick would show CPU near zero.
+ // Sampled once now, so the first line covers a full interval.
+ let mut system = SysinfoSystem::new();
+ SystemStats::capture(&mut system);
+ loop {
+ // `Ok(_)`: stop signalled -> exit. `Err(_)`: interval elapsed -> print.
+ match compio::time::timeout(interval, stop.recv()).await {
+ Ok(_) => break,
+ Err(_) => print_sysinfo(&shard, &mut system).await,
+ }
+ }
+ trace!(shard = shard.id, "sysinfo printer exited");
+}
+
+async fn print_sysinfo(shard: &Rc<ServerShard>, system: &mut SysinfoSystem) {
+ // `GetStats` reads this count where the kernel keeps none, so it is
+ // published also while the line itself is filtered out.
+ publish_open_files_count();
Review Comment:
about this: please figure out something async so that its nonblocking.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4133165876
##########
foreign/node/src/wire/system/get-stats.command.ts:
##########
@@ -91,6 +99,24 @@ const deserializeGetStats = (b: Buffer) => {
position + 4,
position + 4 + kernelVersionLength
).toString();
+ position += 4 + kernelVersionLength;
+
+ // iggy_server_version, iggy_server_semver
+ const iggyServerVersionLength = b.readUInt32LE(position);
+ position += 4 + iggyServerVersionLength + 4;
+
+ const cacheMetricsCount = b.readUInt32LE(position);
+ position += 4 + cacheMetricsCount * CACHE_METRIC_SIZE + THREADS_AND_DISK_SIZE;
+ if (position > b.length)
+ deserializeError('stats', position, b.length);
+
+ // Servers that predate the open-files fields end the reply here.
+ let openFilesCount = 0n;
+ let openFilesLimit = 0n;
+ if (b.length > position) {
Review Comment:
nit: `deserializeGetStats` reads the 16 open-files tail bytes whenever any byte remains, so a reply truncated mid-tail throws a raw `RangeError`. Guard the tail length and call `deserializeError`, as line 110 does.
##########
core/server_common/src/segment_storage/messages_reader.rs:
##########
@@ -37,6 +39,7 @@ impl MessagesReader {
.read(true)
.open(file_path)
.await
+ .exit_on_descriptor_exhaustion(|| format!("opening {file_path}"))
Review Comment:
warning: `MessagesReader::new` and `IndexReader::new` at `core/server_common/src/segment_storage/index_reader.rs:41` open read-only to prove a file exists, yet the added guards exit the process on `EMFILE`. `core/server_common/src/fatal.rs:83` reserves that exit for opens that write, create, truncate or sync. Remove both guards, or comment why these probes must stop the node.
##########
core/metadata/src/impls/metadata.rs:
##########
@@ -2220,6 +2235,33 @@ where
}
}
+ /// Node-wide `[metadata] partitions_max` admission for a `CreateTopic` or
+ /// `CreatePartitions`. Other operations pass.
+ ///
+ /// A soft cap: the apply must not branch on node config, so this counts
+ /// the partitions this primary has committed, and creates in flight
+ /// together can overshoot it. A body that does not decode passes here,
+ /// and `prepare_request` evicts the session for it.
+ fn admit_partitions(&self, message: &Message<RoutedRequestHeader>) -> Result<(), IggyError> {
Review Comment:
simplification: `admit_partitions` decodes the create body before `validate_partitions_limit` checks `partitions_max == 0`, so the default configuration parses every create for a count it discards. Return `Ok(())` when the cap is zero, before the decode.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "mmodzelewski (via GitHub)" <gi...@apache.org>.
mmodzelewski commented on PR #4318:
URL: https://github.com/apache/iggy/pull/4318#issuecomment-5889564072
/skill team-review-slim
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "mmodzelewski (via GitHub)" <gi...@apache.org>.
mmodzelewski commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4138060916
##########
core/server/src/sysinfo_probe.rs:
##########
@@ -105,32 +117,52 @@ pub fn stats_disk_space() -> (u64, u64) {
})
}
+/// Count open descriptors, scanning where the kernel keeps no count, and
+/// publish the result for [`probe_system_stats`].
+///
+/// Only the sysinfo printer calls this, once per interval. The scan cost
+/// grows with the count, so `GetStats` reads the published value instead of
+/// scanning on the request path. The value is as old as the printer interval,
+/// and stays 0 while the printer is disabled.
+pub fn publish_open_files_count() {
+ PUBLISHED_OPEN_FILES_COUNT.store(count_open_files().unwrap_or(0), Ordering::Relaxed);
+}
+
+/// Probe through this thread's [`SYSINFO`], the `GetStats` path.
pub fn probe_system_stats() -> SystemStats {
- let host = HOST_IDENTITY.get_or_init(HostIdentity::probe);
- let probe = SYSINFO.with_borrow_mut(|slot| {
- let sys = slot.get_or_insert_with(SysinfoSystem::new);
- SystemProbe::capture(sys)
- });
-
- SystemStats {
- process_id: probe.process_id,
- cpu_usage: probe.cpu_usage,
- total_cpu_usage: probe.total_cpu_usage,
- memory_usage: probe.memory_usage,
- total_memory: probe.total_memory,
- available_memory: probe.available_memory,
- // sysinfo reports whole seconds; the wire fields are micros (the
- // SDK decodes them via `IggyDuration` / `IggyTimestamp::from`, both
- // micro-based).
- run_time: probe.run_time_secs.saturating_mul(1_000_000),
- start_time: probe.start_time_secs.saturating_mul(1_000_000),
- read_bytes: probe.read_bytes,
- written_bytes: probe.written_bytes,
- threads_count: probe.threads_count,
- hostname: host.hostname.clone(),
- os_name: host.os_name.clone(),
- os_version: host.os_version.clone(),
- kernel_version: host.kernel_version.clone(),
+ SYSINFO
+ .with_borrow_mut(|slot| SystemStats::capture(slot.get_or_insert_with(SysinfoSystem::new)))
+}
+
+impl SystemStats {
+ /// Probe through `sys`. A caller that keeps its own `sys` gets CPU deltas
+ /// over its own interval, and does not reset the window of `GetStats`.
+ pub fn capture(sys: &mut SysinfoSystem) -> Self {
+ let host = HOST_IDENTITY.get_or_init(HostIdentity::probe);
+ let probe = SystemProbe::capture(sys);
+ Self {
+ process_id: probe.process_id,
+ cpu_usage: probe.cpu_usage,
+ total_cpu_usage: probe.total_cpu_usage,
+ memory_usage: probe.memory_usage,
+ total_memory: probe.total_memory,
+ available_memory: probe.available_memory,
+ // sysinfo reports whole seconds; the wire fields are micros (the
+ // SDK decodes them via `IggyDuration` / `IggyTimestamp::from`, both
+ // micro-based).
+ run_time: probe.run_time_secs.saturating_mul(1_000_000),
+ start_time: probe.start_time_secs.saturating_mul(1_000_000),
+ read_bytes: probe.read_bytes,
+ written_bytes: probe.written_bytes,
+ threads_count: probe.threads_count,
+ open_files_count: count_open_files_without_scan()
+ .unwrap_or_else(|| PUBLISHED_OPEN_FILES_COUNT.load(Ordering::Relaxed)),
+ open_files_limit: getrlimit(Resource::RLIMIT_NOFILE).map_or(0, |(soft, _)| soft),
Review Comment:
I'd keep it as there is no other function that reports it. Other stats like total memory, os name or os version also do not change, yet we report them for completeness.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "spetz (via GitHub)" <gi...@apache.org>.
spetz commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4138304848
##########
foreign/swift/Tests/IggyTests/Fixtures/golden.json:
##########
@@ -982,7 +983,7 @@
"response.raw_personal_access_token": "167261772d7365637265742d746f6b656e2d76616c7565",
"response.send_messages": "0200000001000000020000000300000004000000000000000100000002000000000000002a00000000000000",
"response.send_messages.empty": "00000000",
- "response.stats": "d20400000000cc4100004842000000400000000000000000020000000000000001000000100e00000000000000e090663c13060040420f000000000020a107000000000080841e0000000000030000000a0000001e0000005a00000050c30000000000000500000002000000060000006e6f64652d31050000004c696e757803000000362e3105000000362e312e3006000000302e31312e30002c000001000000010000000100000000000000e80300000000000032000000000000003dcf733f1000000000000000190000000060253c77000000",
+ "response.stats": "d20400000000cc4100004842000000400000000000000000020000000000000001000000100e00000000000000e090663c13060040420f000000000020a107000000000080841e0000000000030000000a0000001e0000005a00000050c30000000000000500000002000000060000006e6f64652d31050000004c696e757803000000362e3105000000362e312e3006000000302e31312e30002c000001000000010000000100000000000000e80300000000000032000000000000003dcf733f1000000000000000190000000060253c7700000080000000000000000028000000000000",
Review Comment:
`response.stats` gained the 16-byte tail here, but `Stats` in `foreign/swift/Sources/Iggy/Models/Resources.swift:448` has no `openFilesCount` / `openFilesLimit`, and no Swift test consumes this vector. The PR body says the CLI and all SDKs show the two fields. Either add them to the Swift model now, while the vector is being regenerated, or drop Swift from that claim.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,193 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+use std::sync::atomic::{AtomicBool, Ordering};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// The server stopped on an error after a storage open for a write or a
+ /// sync failed because the process (`EMFILE`) or the host (`ENFILE`) had no
+ /// free file descriptor. The exit comes after the ordinary shutdown, so the
+ /// shards flushed what they could. See [`NoteDescriptorExhaustion`].
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// The target that 0.9.0 shipped for the fatal log line, so existing log
+/// filters keep matching.
+const FATAL_LOG_TARGET: &str = "iggy.consensus.diag";
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
Review Comment:
`fatal()` never consults `descriptors_exhausted()`, so the exit-4 contract only holds on the shard-join path in `main.rs`. An `EMFILE` on the WAL `.tmp` create in `PrepareJournal::truncate_from` (`core/journal/src/prepare_journal.rs:851`) or `drain` (`:1030`) records the note, poisons the journal, and `core/metadata/src/impls/metadata.rs:1054` then calls `fatal(UnreconcilableLogFrontier)`, which exits 2. Same for `SuperblockWedged` at exit 3. The PR body says descriptor exhaustion exits 4 because only a restart repairs it. Either have `fatal()` log the recorded exhaustion alongside the reason it was given, or state in the body and in the `FatalReason` docs that exits 2 and 3 can also be caused by a full descriptor table.
##########
core/server/src/boot/fd_limit.rs:
##########
@@ -0,0 +1,191 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! The process's own `RLIMIT_NOFILE`, raised once at startup, and the client
+//! connection cap sized from it.
+
+use message_bus::ConnectionCap;
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit, setrlimit};
+use thiserror::Error;
+use tracing::{info, warn};
+
+/// `OPEN_MAX` from `<sys/syslimits.h>`, which `libc` does not export. The
+/// macOS hard limit is usually `RLIM_INFINITY`, and `setrlimit(2)` rejects
+/// that as a soft `RLIMIT_NOFILE` with `EINVAL`, so the man page's recipe is
+/// `min(OPEN_MAX, rlim_max)`.
+#[cfg(target_vendor = "apple")]
+const APPLE_OPEN_MAX: u64 = 10_240;
+
+/// `RLIMIT_NOFILE` around [`raise_open_file_limit`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct OpenFileLimit {
+ pub soft_before: u64,
+ pub soft: u64,
+ pub hard: u64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
+pub enum OpenFileLimitError {
+ #[error("cannot read RLIMIT_NOFILE: {0}")]
+ Read(Errno),
+ #[error(
+ "cannot raise the RLIMIT_NOFILE soft limit from {soft} to {target} (hard {hard}): {errno}"
+ )]
+ Raise {
+ errno: Errno,
+ soft: u64,
+ hard: u64,
+ target: u64,
+ },
+}
+
+/// Raise the soft `RLIMIT_NOFILE` to the hard limit (clamped on macOS).
+/// A soft limit already at or above the target is left as it is.
+///
+/// # Errors
+///
+/// [`OpenFileLimitError::Read`] if the limit cannot be read, and
+/// [`OpenFileLimitError::Raise`] if `setrlimit` rejects the new soft limit.
+pub fn raise_open_file_limit() -> Result<OpenFileLimit, OpenFileLimitError> {
Review Comment:
The soft `RLIMIT_NOFILE` is raised to the hard limit unconditionally. An operator who set a lower soft limit on purpose (bounding io_uring registered files, or memory) loses it with one info line and no knob. Acceptable as the default, but the only user-facing mention is one clause in the `connections_max` comment at `core/server/config.toml:1136`. Say there, or in a short `[server]` note, that the raise always happens and cannot be turned off.
##########
core/server/src/main.rs:
##########
@@ -99,6 +116,13 @@ fn main() -> Result<(), ServerError> {
if let Err(error) = &joined {
server::boot::systemd::notify_shutdown_failure(error);
}
+ if let Err(error) = &joined
+ && descriptors_exhausted()
Review Comment:
`DESCRIPTORS_EXHAUSTED` is set once and never cleared. A transient `EMFILE` burst the server survives, followed hours later by an unrelated shutdown error such as `ShardPumpDrainTimedOut`, still exits 4 here and points the operator at the wrong cause. The `NoteDescriptorExhaustion` doc says the record lasts for the life of the process but not that it can label an unrelated exit. Either say so there, or include the time of the first noted `EMFILE` in the fatal stderr line so the two events can be told apart.
##########
foreign/node/src/wire/system/get-stats.command.ts:
##########
@@ -91,6 +101,26 @@ const deserializeGetStats = (b: Buffer) => {
position + 4,
position + 4 + kernelVersionLength
).toString();
+ position += 4 + kernelVersionLength;
+
+ // iggy_server_version, iggy_server_semver
+ const iggyServerVersionLength = b.readUInt32LE(position);
Review Comment:
The `readUInt32LE` for `iggy_server_version` length (line 107) and `cache_metrics_count` (line 110) run before the new `position > b.length` guard on line 112, so a reply cut inside those eight bytes still throws a raw `RangeError` rather than the `DeserializeError` the tail now gets. Same class of defect as the tail fix, one guard higher.
##########
core/message_bus/src/client_listener/tcp.rs:
##########
@@ -77,6 +78,7 @@ pub async fn run(listener: TcpListener, token: ShutdownToken, on_accepted: Accep
}
Err(e) => {
error!("Client listener (TCP) accept failed: {e}");
+ pause_after_accept_error(&e).await;
Review Comment:
The 1 s pause runs inside the `accept()` arm of the `select!` at line 73, so the shutdown token is not polled while it sleeps. Same in the TCP-TLS, WS, WSS, replica and HTTPS loops. A shutdown that lands during an `EMFILE` burst waits up to one extra second per listener. Either race the sleep against the token inside `pause_after_accept_error`, or note the added latency in its doc at `core/message_bus/src/accept.rs:41`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4144655584
##########
foreign/swift/Sources/Iggy/Models/Resources.swift:
##########
@@ -474,13 +474,17 @@ public struct Stats: Sendable, Hashable {
public var threadsCount: UInt32
public var freeDiskSpace: UInt64
public var totalDiskSpace: UInt64
+ /// The number of file descriptors the server process holds open, 0 when unknown.
+ public var openFilesCount: UInt64
+ /// The soft limit on open file descriptors (`RLIMIT_NOFILE`) of the server process, 0 when unknown.
+ public var openFilesLimit: UInt64
public init(
processID: UInt32, cpuUsage: Float, totalCPUUsage: Float, memoryUsage: UInt64, totalMemory: UInt64, availableMemory: UInt64, runTime: Duration,
startTime: IggyTimestamp, readBytes: UInt64, writtenBytes: UInt64, messagesSizeBytes: UInt64, streamsCount: UInt32, topicsCount: UInt32,
partitionsCount: UInt32, segmentsCount: UInt32, messagesCount: UInt64, clientsCount: UInt32, consumerGroupsCount: UInt32, hostname: String,
osName: String, osVersion: String, kernelVersion: String, iggyServerVersion: String, iggyServerSemver: UInt32?, cacheMetrics: [CacheMetrics],
- threadsCount: UInt32, freeDiskSpace: UInt64, totalDiskSpace: UInt64
+ threadsCount: UInt32, freeDiskSpace: UInt64, totalDiskSpace: UInt64, openFilesCount: UInt64 = 0, openFilesLimit: UInt64 = 0
Review Comment:
nit: only `openFilesCount` and `openFilesLimit` get a `= 0` default, so a future decoder can skip the tail and silently report 0. drop the two defaults to match the other 28 parameters.
##########
core/message_bus/src/installer/mod.rs:
##########
@@ -99,8 +100,16 @@ pub trait ConnectionInstaller {
/// Same for an SDK client connection. The owning shard is already
/// encoded in the top 16 bits of `meta.client_id`. `meta` is stored
/// on the bus and exposed via [`IggyMessageBus::client_meta`] for
- /// the lifetime of the connection.
- fn install_client_fd(&self, fd: DupedFd, meta: ClientConnMeta, on_request: RequestHandler);
+ /// the lifetime of the connection. `permit` is the socket's slot in
+ /// the node's connection cap, and the install holds it until the socket
+ /// closes.
+ fn install_client_fd(
+ &self,
+ fd: DupedFd,
+ meta: ClientConnMeta,
+ permit: Option<ConnectionPermit>,
Review Comment:
nit: `Option<ConnectionPermit>` lets a new caller pass `None` and install an uncounted client socket, though production always passes `Some`. take `ConnectionPermit` in the four client fd methods and build test permits like `test_permit` in `shard/src/coordinator.rs`.
##########
core/binary_protocol/src/responses/system/get_stats.rs:
##########
@@ -55,6 +55,8 @@ impl CacheMetricEntry {
/// [threads_count:4]
/// [free_disk_space:8]
/// [total_disk_space:8]
+/// [open_files_count:8]
Review Comment:
nit: this lists `open_files_count` and `open_files_limit` as always present, but `decode` treats them as an optional tail. say that an older server ends the reply at `total_disk_space` and a partial tail fails.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,243 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use iggy_common::IggyTimestamp;
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+use std::sync::atomic::{AtomicU64, Ordering};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// The server stopped on an error after a storage open for a write or a
+ /// sync failed because the process (`EMFILE`) or the host (`ENFILE`) had no
+ /// free file descriptor. The exit comes after the ordinary shutdown, so the
+ /// shards flushed what they could. See [`NoteDescriptorExhaustion`].
+ ///
+ /// The other reasons keep their own status after such a failure, for
+ /// example a superblock that stays unwritable for lack of a descriptor
+ /// exits 3. Their exit line then gives the time of the first one.
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// The target that 0.9.0 shipped for the fatal log line, so existing log
+/// filters keep matching.
+const FATAL_LOG_TARGET: &str = "iggy.consensus.diag";
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+///
+/// If a storage open found no free file descriptor earlier, the line gives the
+/// time of the first one, whatever the reason. See [`NoteDescriptorExhaustion`].
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
+ fatal_with_log_flush(reason, message, || {});
+}
+
+/// [`fatal`] for the owner of the log appenders. `flush_logs` runs after the
+/// log event and before the exit, so the event reaches the log files too.
+pub fn fatal_with_log_flush(reason: FatalReason, message: &str, flush_logs: impl FnOnce()) -> ! {
+ let exhaustion = first_descriptor_exhaustion()
+ .map(|at| format!("; a storage open first found no free file descriptor at {at} UTC"))
+ .unwrap_or_default();
+ tracing::error!(
+ target: FATAL_LOG_TARGET,
+ reason = ?reason,
+ exit_status = reason.exit_status(),
+ "{message}{exhaustion}"
+ );
+ flush_logs();
+ let _ = writeln!(
+ std::io::stderr().lock(),
+ "iggy fatal: reason={reason:?} exit_status={}: {message}{exhaustion}",
+ reason.exit_status()
+ );
+ std::process::exit(i32::from(reason.exit_status()));
+}
+
+/// Storage results that record a missing file descriptor for the exit status.
+///
+/// Only for opens that write, create, truncate or sync, and for read-only
+/// opens that are one step of such a write: the existence probes of segment
+/// setup, or an open that exists only to sync. The error still goes to the
+/// caller, whose own handling decides what happens. A failed partition write
+/// fences the partition and stops the server through the shutdown flush, and a
+/// failed partition build retries. Stopping at the open instead would skip that
Review Comment:
nit: this says a failed partition build retries, but at boot `boot/recovery.rs:240` returns the error and stops the server - only `PartitionOffsetReservationClaim` goes to the reconciler. reword it to match.
##########
core/server_common/src/segment_storage/mod.rs:
##########
@@ -101,31 +106,22 @@ impl SegmentStorage {
indexes_size: u64,
file_exists: bool,
) -> Result<Self, IggyError> {
- let size = Rc::new(std::sync::atomic::AtomicU64::new(messages_size));
- let indexes_size = Rc::new(std::sync::atomic::AtomicU64::new(indexes_size));
- let messages_writer = Rc::new(MessagesWriter::new(messages_path, size, file_exists).await?);
-
- let index_writer = Rc::new(IndexWriter::new(index_path, indexes_size, file_exists).await?);
-
- if file_exists {
- messages_writer.fsync().await?;
- index_writer.fsync().await?;
- }
-
+ prepare_for_writes(messages_path, "messages", messages_size, file_exists).await?;
+ prepare_for_writes(index_path, "index", indexes_size, file_exists).await?;
let messages_reader = Rc::new(MessagesReader::new(messages_path).await?);
Review Comment:
simplification: `prepare_for_writes` just opened both files, so these reader opens only prove they exist. add `read(true)` at line 147, give `IndexReader` a `from_validated_path` like `MessagesReader`, and skip the second open.
also at line 98.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,243 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use iggy_common::IggyTimestamp;
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+use std::sync::atomic::{AtomicU64, Ordering};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// The server stopped on an error after a storage open for a write or a
+ /// sync failed because the process (`EMFILE`) or the host (`ENFILE`) had no
+ /// free file descriptor. The exit comes after the ordinary shutdown, so the
+ /// shards flushed what they could. See [`NoteDescriptorExhaustion`].
+ ///
+ /// The other reasons keep their own status after such a failure, for
+ /// example a superblock that stays unwritable for lack of a descriptor
+ /// exits 3. Their exit line then gives the time of the first one.
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// The target that 0.9.0 shipped for the fatal log line, so existing log
+/// filters keep matching.
+const FATAL_LOG_TARGET: &str = "iggy.consensus.diag";
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+///
+/// If a storage open found no free file descriptor earlier, the line gives the
+/// time of the first one, whatever the reason. See [`NoteDescriptorExhaustion`].
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
+ fatal_with_log_flush(reason, message, || {});
+}
+
+/// [`fatal`] for the owner of the log appenders. `flush_logs` runs after the
+/// log event and before the exit, so the event reaches the log files too.
+pub fn fatal_with_log_flush(reason: FatalReason, message: &str, flush_logs: impl FnOnce()) -> ! {
+ let exhaustion = first_descriptor_exhaustion()
+ .map(|at| format!("; a storage open first found no free file descriptor at {at} UTC"))
+ .unwrap_or_default();
+ tracing::error!(
+ target: FATAL_LOG_TARGET,
+ reason = ?reason,
+ exit_status = reason.exit_status(),
+ "{message}{exhaustion}"
+ );
+ flush_logs();
+ let _ = writeln!(
+ std::io::stderr().lock(),
+ "iggy fatal: reason={reason:?} exit_status={}: {message}{exhaustion}",
+ reason.exit_status()
+ );
+ std::process::exit(i32::from(reason.exit_status()));
+}
+
+/// Storage results that record a missing file descriptor for the exit status.
+///
+/// Only for opens that write, create, truncate or sync, and for read-only
+/// opens that are one step of such a write: the existence probes of segment
+/// setup, or an open that exists only to sync. The error still goes to the
+/// caller, whose own handling decides what happens. A failed partition write
+/// fences the partition and stops the server through the shutdown flush, and a
+/// failed partition build retries. Stopping at the open instead would skip that
+/// flush and lose committed messages that are not yet in a segment.
+///
+/// If the server then stops on an error, it exits with
+/// [`FatalReason::DescriptorsExhausted`] instead of 1. A stop through
+/// [`fatal`] keeps the status of its own reason. A failed read fails only its
+/// own request, so reads do not record it, and accept loops do not either, see
+/// `message_bus::accept`.
+///
+/// The record lasts for the life of the process. An exhaustion that the server
+/// recovers from, such as a superblock write that succeeds on a retry, therefore
+/// also sets the status of a later stop on an unrelated error. The exit line
+/// gives the time of the first exhaustion, so the two can be told apart.
+pub trait NoteDescriptorExhaustion: Sized {
+ /// Pass the result through. If it failed with `EMFILE` or `ENFILE`, record
+ /// that for [`descriptors_exhausted`], and log the first one with the
+ /// limits. `operation` names what was being opened, for that log line.
+ #[must_use]
+ fn note_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self;
+}
+
+/// Microseconds since the Unix epoch of the first noted exhaustion, or 0 for
+/// none.
+static FIRST_DESCRIPTOR_EXHAUSTION: AtomicU64 = AtomicU64::new(0);
Review Comment:
simplification: a `OnceLock<IggyTimestamp>` does the same job without the 0 sentinel, `.max(1)` and `compare_exchange` - `set(IggyTimestamp::now()).is_ok()` keeps the first-writer rule and `get().copied()` replaces the load.
##########
core/partitions/src/state_transfer.rs:
##########
@@ -645,6 +646,24 @@ const fn validate_consumer_offset_transfer_count(
mod tests {
use super::*;
+ #[test]
+ fn given_segment_read_error_when_classifying_should_tell_local_faults_from_stale_offers() {
Review Comment:
nit: this only calls `classify`, which the PR did not change, so it passes without the `hash_segment_range` fix at line 3791. drive it through `load_verified_segment_artifact` with a directory path and assert `Stale` with `raw_os_error().is_some()`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on PR #4318:
URL: https://github.com/apache/iggy/pull/4318#issuecomment-5873530182
/skill team-review-slim
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "mmodzelewski (via GitHub)" <gi...@apache.org>.
mmodzelewski commented on PR #4318:
URL: https://github.com/apache/iggy/pull/4318#issuecomment-5891334748
/ready
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(server): guard against running out of file descriptors [iggy]
Posted by "hubcio (via GitHub)" <gi...@apache.org>.
hubcio commented on code in PR #4318:
URL: https://github.com/apache/iggy/pull/4318#discussion_r4138942574
##########
core/server/src/partition_helpers.rs:
##########
@@ -340,6 +341,15 @@ pub async fn load_partition_or_fence(
.await
.map(Some)
}
+ // No free file descriptor says nothing about the record, so the load
+ // fails like any other: the reconciler retries it with backoff, and a
Review Comment:
nit: at boot this `Err` stops the node through `boot/recovery.rs:240` with exit 1, because the superblock read is not noted, and no reconciler retries it. document the boot stop and note this read so the exit is 4.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,193 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+use std::sync::atomic::{AtomicBool, Ordering};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// The server stopped on an error after a storage open for a write or a
+ /// sync failed because the process (`EMFILE`) or the host (`ENFILE`) had no
+ /// free file descriptor. The exit comes after the ordinary shutdown, so the
+ /// shards flushed what they could. See [`NoteDescriptorExhaustion`].
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// The target that 0.9.0 shipped for the fatal log line, so existing log
+/// filters keep matching.
+const FATAL_LOG_TARGET: &str = "iggy.consensus.diag";
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
+ tracing::error!(
+ target: FATAL_LOG_TARGET,
+ reason = ?reason,
+ exit_status = reason.exit_status(),
+ "{message}"
+ );
+ let _ = writeln!(
+ std::io::stderr().lock(),
+ "iggy fatal: reason={reason:?} exit_status={}: {message}",
+ reason.exit_status()
+ );
+ std::process::exit(i32::from(reason.exit_status()));
+}
+
+/// Storage results that record a missing file descriptor for the exit status.
+///
+/// Only for opens that write, create, truncate or sync, and for read-only
+/// opens that are one step of such a write: the existence probes of segment
+/// setup, or an open that exists only to sync. The error still goes to the
+/// caller, whose own handling decides what happens. A failed partition write
+/// fences the partition and stops the server through the shutdown flush, and a
+/// failed partition build retries. Stopping at the open instead would skip that
+/// flush and lose committed messages that are not yet in a segment.
+///
+/// If the server then stops on an error, it exits with
+/// [`FatalReason::DescriptorsExhausted`] instead of 1. The record lasts for the
+/// life of the process. A failed read fails only its own request, so reads do
+/// not record it, and accept loops do not either, see `message_bus::accept`.
+pub trait NoteDescriptorExhaustion: Sized {
+ /// Pass the result through. If it failed with `EMFILE` or `ENFILE`, record
+ /// that for [`descriptors_exhausted`], and log the first one with the
+ /// limits. `operation` names what was being opened, for that log line.
+ #[must_use]
+ fn note_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self;
+}
+
+static DESCRIPTORS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
+
+impl<T> NoteDescriptorExhaustion for io::Result<T> {
+ fn note_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self {
+ if let Err(error) = &self
+ && is_descriptor_exhaustion(error)
+ && !DESCRIPTORS_EXHAUSTED.swap(true, Ordering::Relaxed)
Review Comment:
warning: nothing clears this flag, so after a recovered `EMFILE`, for example a superblock persist that succeeds on retry, a later `ENOSPC` fence or any other error that reaches `main` exits 4. carry the exhaustion in the stop cause instead.
##########
core/metadata/src/stm/authz.rs:
##########
@@ -345,6 +345,38 @@ pub(crate) fn authorize(
}
}
+/// Whether `authorize` lets a `CreateTopic`, or a `CreatePartitions` when
+/// `topic_id` is set, reach its apply: the ids resolve and `user_id` holds the
+/// grant. The primary asks before it denies a create for `[metadata]
+/// partitions_max`, so apply answers `NotFound` or `Unauthorized` first and a
+/// user who cannot create learns nothing about the cap.
+pub(crate) fn admits_partitions_create(
+ users: &Users,
+ streams: &Streams,
+ user_id: u32,
+ stream_id: &WireIdentifier,
+ topic_id: Option<&WireIdentifier>,
+) -> bool {
+ let Some(topic_id) = topic_id else {
+ return streams
Review Comment:
warning: when a `CreateTopic` for an existing name exceeds `partitions_max`, clients get `PartitionsLimitReached`, not `TopicNameAlreadyExists`, and Kafka clients get POLICY_VIOLATION. if the stream holds the name, skip the cap.
##########
core/partitions/src/state_transfer.rs:
##########
@@ -3054,6 +3076,11 @@ where
source,
})?,
};
+ // The open fsyncs the installed files, and then a sealed segment
+ // gives its writer descriptors back.
+ if index + 1 < staged.len() {
Review Comment:
nit: no test asserts that install closes sealed writers, so a leak here stays silent, and every unit install test stages at most one segment. add a multi-segment install test that asserts every storage but the last has no `index_writer`.
##########
core/server/src/sysinfo_printer.rs:
##########
@@ -0,0 +1,202 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Periodic one-line log of process and host usage.
+//!
+//! Spawned on shard 0 only: the numbers describe the whole process, so one
+//! line per node is enough, and the client count is already a cross-shard
+//! gather.
+
+use crate::responses::{StatsTotals, stats_totals};
+use crate::shell::ServerShard;
+use crate::sysinfo_probe::{SystemStats, stats_disk_space};
+use iggy_common::IggyByteSize;
+use shard::Receiver;
+use std::fmt;
+use std::rc::Rc;
+use std::time::Duration;
+use sysinfo::System as SysinfoSystem;
+use tracing::level_filters::LevelFilter;
+use tracing::{error, info, trace};
+
+/// Run the printer until `stop` fires, logging one line every `interval`.
+pub async fn run_sysinfo_printer(shard: Rc<ServerShard>, stop: Receiver<()>, interval: Duration) {
+ info!("System info logger is enabled, OS info will be printed every: {interval:?}");
+ // Not the shared `GetStats` sampler: a tick would reset its CPU window, and
+ // a `GetStats` on shard 0 right after a tick would show CPU near zero.
+ // Sampled once now, so the first line covers a full interval.
+ let mut system = SysinfoSystem::new();
+ SystemStats::capture(&mut system);
+ loop {
+ // `Ok(_)`: stop signalled -> exit. `Err(_)`: interval elapsed -> print.
+ match compio::time::timeout(interval, stop.recv()).await {
+ Ok(_) => break,
+ Err(_) => print_sysinfo(&shard, &mut system).await,
+ }
+ }
+ trace!(shard = shard.id, "sysinfo printer exited");
+}
+
+async fn print_sysinfo(shard: &Rc<ServerShard>, system: &mut SysinfoSystem) {
+ // The global max level, not `tracing::enabled!`: the logger's idle
+ // OpenTelemetry layers veto every `enabled` query, so that is always false.
+ if LevelFilter::current() < LevelFilter::INFO {
+ return;
+ }
+ let clients_count = shard.list_all_clients().await.len();
+ let totals = match stats_totals(shard) {
Review Comment:
simplification: the line reads only two `StatsTotals` fields, the message sums, but each tick runs the full walk with one `StatsRegistry` lock per partition. summing `stream.stats` here gives the same numbers and makes the `stats_totals` extraction unnecessary.
##########
core/message_bus/src/connection_cap.rs:
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Node-wide cap on open client sockets.
+//!
+//! Shard 0 accepts every client socket, but the owning shard closes it. Each
+//! socket therefore carries a [`ConnectionPermit`] to its owning shard, and
+//! the permit frees its slot on drop.
+//!
+//! The count is a process-wide static, because one node runs per process. A
+//! permit that pointed at its count would add 16 bytes to the client setup
+//! frames, and every slot of every shard inbox pays for the largest frame.
+
+use std::cell::Cell;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::{Duration, Instant};
+use tracing::warn;
+
+/// Shortest interval between two refusal warnings. A client that reconnects
+/// in a loop would otherwise log one line per attempt.
+const REFUSAL_LOG_INTERVAL: Duration = Duration::from_secs(10);
+
+static LIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
+
+/// The open client sockets of the node, capped at `max`.
+///
+/// Owned by shard 0, where every client accept runs.
+#[derive(Debug)]
+pub struct ConnectionCap {
+ max: Option<usize>,
+ last_refusal_log: Cell<Option<Instant>>,
+ refused_since_log: Cell<u64>,
+}
+
+impl ConnectionCap {
+ /// A cap of `max` open sockets. `None` counts sockets and refuses none.
+ #[must_use]
+ pub const fn new(max: Option<usize>) -> Self {
Review Comment:
nit: `ConnectionCap::new(Some(0))` refuses every socket while `connections_max = 0` means no cap, so zero means opposite things in the configuration and here. take `Option<NonZeroUsize>` - `resolve_connections_max` already maps zero to `None`.
##########
core/metadata/src/impls/metadata.rs:
##########
@@ -2220,6 +2237,66 @@ where
}
}
+ /// `[metadata] partitions_max` admission for a `CreateTopic` or
+ /// `CreatePartitions`. Other operations pass.
+ ///
+ /// A soft cap: the apply must not branch on node config, so this counts
+ /// the partitions this primary has committed. The creates in flight, up to
+ /// a full prepare queue and request queue of them, each pass it on their
+ /// own, so together they can overshoot it by up to 1000 partitions each.
+ ///
+ /// A body that does not decode passes here, and `prepare_request` evicts
+ /// the session for it. A create that the gated apply refuses, for a
+ /// missing target or a missing grant, also passes, so it gets that error
+ /// and not the cap's.
+ fn admit_partitions(&self, message: &Message<RoutedRequestHeader>) -> Result<(), IggyError> {
Review Comment:
nit: a binary-protocol create that `admit_partitions` denies leaves no server log line or metric, and the HTTP `error!` carries no counts. log a warning with `partitions_max`, the committed count and the requested count.
##########
foreign/node/src/wire/system/get-stats.command.ts:
##########
@@ -91,6 +101,26 @@ const deserializeGetStats = (b: Buffer) => {
position + 4,
position + 4 + kernelVersionLength
).toString();
+ position += 4 + kernelVersionLength;
+
+ // iggy_server_version, iggy_server_semver
+ const iggyServerVersionLength = b.readUInt32LE(position);
+ position += 4 + iggyServerVersionLength + 4;
+
+ const cacheMetricsCount = b.readUInt32LE(position);
+ position += 4 + cacheMetricsCount * CACHE_METRIC_SIZE + THREADS_AND_DISK_SIZE;
Review Comment:
nit: the parser now walks past the server version and semver, cache metrics, thread count and disk fields, but `Stats` returns none of them. read them at the positions the parser already tracks and add them to `Stats`.
##########
core/server_common/src/fatal.rs:
##########
@@ -0,0 +1,193 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Stopping the process on an environmental failure that has no in-process answer.
+
+use nix::errno::Errno;
+use nix::sys::resource::{Resource, getrlimit};
+use std::io::{self, Write};
+use std::sync::atomic::{AtomicBool, Ordering};
+
+/// Why the process is stopping. The discriminant is the exit status, one per
+/// condition; `1` stays the binary's generic startup failure.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FatalReason {
+ /// A prepare's WAL append failed and the op it had claimed could not be handed
+ /// back. The durable log is intact up to the previous op, so recovery re-derives
+ /// the frontier and restarting is the repair.
+ UnreconcilableLogFrontier = 2,
+ /// The superblock stayed unwritable past the configured fail-stop window.
+ /// The replica was already fenced quorum-invisible, so exiting hands the
+ /// wedge to a supervisor instead of a log reader.
+ SuperblockWedged = 3,
+ /// The server stopped on an error after a storage open for a write or a
+ /// sync failed because the process (`EMFILE`) or the host (`ENFILE`) had no
+ /// free file descriptor. The exit comes after the ordinary shutdown, so the
+ /// shards flushed what they could. See [`NoteDescriptorExhaustion`].
+ DescriptorsExhausted = 4,
+}
+
+impl FatalReason {
+ #[must_use]
+ pub const fn exit_status(self) -> u8 {
+ self as u8
+ }
+}
+
+/// The target that 0.9.0 shipped for the fatal log line, so existing log
+/// filters keep matching.
+const FATAL_LOG_TARGET: &str = "iggy.consensus.diag";
+
+/// Log `message` and terminate the process.
+///
+/// For an environmental failure where stopping IS the answer, rather than an error
+/// threaded up a stack whose top knows less than this leaf does. Not for bugs in
+/// this process, which are `assert!` / `panic!` and say so.
+///
+/// `exit`, not `panic!`: a panic unwinds one shard of a thread-per-core runtime and
+/// leaves its siblings serving, which is the half-alive state this exists to avoid.
+/// Skipping destructors is wanted here, since the reason for stopping is that
+/// further writes cannot be trusted.
+///
+/// The reason also goes straight to stderr. The tracing appenders are
+/// non-blocking workers, and `exit` stops them before they flush, so without
+/// this write a supervisor's journal never learns why the process stopped. The
+/// write result is ignored because `eprintln!` would panic on a broken stderr.
+pub fn fatal(reason: FatalReason, message: &str) -> ! {
+ tracing::error!(
+ target: FATAL_LOG_TARGET,
+ reason = ?reason,
+ exit_status = reason.exit_status(),
+ "{message}"
+ );
+ let _ = writeln!(
+ std::io::stderr().lock(),
+ "iggy fatal: reason={reason:?} exit_status={}: {message}",
+ reason.exit_status()
+ );
+ std::process::exit(i32::from(reason.exit_status()));
+}
+
+/// Storage results that record a missing file descriptor for the exit status.
+///
+/// Only for opens that write, create, truncate or sync, and for read-only
+/// opens that are one step of such a write: the existence probes of segment
+/// setup, or an open that exists only to sync. The error still goes to the
+/// caller, whose own handling decides what happens. A failed partition write
+/// fences the partition and stops the server through the shutdown flush, and a
+/// failed partition build retries. Stopping at the open instead would skip that
+/// flush and lose committed messages that are not yet in a segment.
+///
+/// If the server then stops on an error, it exits with
+/// [`FatalReason::DescriptorsExhausted`] instead of 1. The record lasts for the
+/// life of the process. A failed read fails only its own request, so reads do
+/// not record it, and accept loops do not either, see `message_bus::accept`.
+pub trait NoteDescriptorExhaustion: Sized {
+ /// Pass the result through. If it failed with `EMFILE` or `ENFILE`, record
+ /// that for [`descriptors_exhausted`], and log the first one with the
+ /// limits. `operation` names what was being opened, for that log line.
+ #[must_use]
+ fn note_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self;
+}
+
+static DESCRIPTORS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
+
+impl<T> NoteDescriptorExhaustion for io::Result<T> {
+ fn note_descriptor_exhaustion(self, operation: impl FnOnce() -> String) -> Self {
+ if let Err(error) = &self
+ && is_descriptor_exhaustion(error)
+ && !DESCRIPTORS_EXHAUSTED.swap(true, Ordering::Relaxed)
+ {
+ tracing::error!(
+ target: FATAL_LOG_TARGET,
+ "no free file descriptor while {}: {error} ({}); if the server stops \
Review Comment:
nit: this log line promises exit 4, but a wedged superblock create still exits 3 through `fatal` at `shard/src/lib.rs:7752`. say here and in the doc at line 96 that `fatal` exits keep their own status.
##########
core/journal/src/prepare_journal.rs:
##########
@@ -819,7 +820,9 @@ impl Journal for PrepareJournal {
let tmp_path = wal_path.with_extension("wal.tmp");
Review Comment:
simplification: `truncate_from` and `drain` at line 987 repeat the same tmp write, rename, dir sync and reopen sequence, so every new note lands twice. pull it into one `rewrite_live(&live, label)` helper both call - about 35 lines less.
##########
core/server/src/http.rs:
##########
@@ -282,12 +292,60 @@ pub fn start(
/// `ConnectInfo<ClientAddr>` extension per connection instead. Handlers read
/// it through the `Identity` extractor's `client_ip`, which picks the
/// advertised address a client is told about - never authorization.
-#[derive(Debug, Clone, Copy)]
-pub struct ClientAddr(pub SocketAddr);
+///
+/// It also holds the connection's slot in the node's connection cap. The
+/// per-connection service owns this value, so the slot frees when hyper drops
+/// the connection.
+#[derive(Debug, Clone)]
+pub struct ClientAddr {
+ pub addr: SocketAddr,
+ _permit: Option<Arc<ConnectionPermit>>,
+}
+
+impl Connected<cyper_axum::IncomingStream<'_, CappedListener>> for ClientAddr {
+ fn connect_info(stream: cyper_axum::IncomingStream<'_, CappedListener>) -> Self {
+ let peer = stream.remote_addr();
+ Self {
+ addr: peer.addr,
+ _permit: peer.permit.clone(),
+ }
+ }
+}
+
+/// The plain HTTP listener behind the node's connection cap. A socket past
+/// the cap is closed at accept.
+pub struct CappedListener {
+ listener: TcpListener,
+ connections: Rc<ConnectionCap>,
+}
+
+/// The peer of an accepted plain HTTP socket and its slot in the connection
+/// cap. `permit` is `None` only for the listener's own local address.
+#[derive(Debug, Clone)]
+pub struct CappedPeer {
Review Comment:
simplification: `CappedPeer` repeats the two fields of `ClientAddr` and `connect_info` just copies them across. use `type Addr = ClientAddr` and return `stream.remote_addr().clone()` - drops the type and about 10 lines.
##########
core/message_bus/src/connection_cap.rs:
##########
@@ -0,0 +1,161 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Node-wide cap on open client sockets.
+//!
+//! Shard 0 accepts every client socket, but the owning shard closes it. Each
+//! socket therefore carries a [`ConnectionPermit`] to its owning shard, and
+//! the permit frees its slot on drop.
+//!
+//! The count is a process-wide static, because one node runs per process. A
+//! permit that pointed at its count would add 16 bytes to the client setup
+//! frames, and every slot of every shard inbox pays for the largest frame.
+
+use std::cell::Cell;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::{Duration, Instant};
+use tracing::warn;
+
+/// Shortest interval between two refusal warnings. A client that reconnects
+/// in a loop would otherwise log one line per attempt.
+const REFUSAL_LOG_INTERVAL: Duration = Duration::from_secs(10);
+
+static LIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
+
+/// The open client sockets of the node, capped at `max`.
+///
+/// Owned by shard 0, where every client accept runs.
+#[derive(Debug)]
+pub struct ConnectionCap {
+ max: Option<usize>,
+ last_refusal_log: Cell<Option<Instant>>,
+ refused_since_log: Cell<u64>,
+}
+
+impl ConnectionCap {
+ /// A cap of `max` open sockets. `None` counts sockets and refuses none.
+ #[must_use]
+ pub const fn new(max: Option<usize>) -> Self {
+ Self {
+ max,
+ last_refusal_log: Cell::new(None),
+ refused_since_log: Cell::new(0),
+ }
+ }
+
+ /// Sockets of this process that hold a permit now.
+ #[must_use]
+ pub fn live(&self) -> usize {
+ LIVE_CONNECTIONS.load(Ordering::Relaxed)
+ }
+
+ /// Take a slot for a socket that was just accepted, or `None` at the
+ /// cap. The caller closes a refused socket by dropping it.
+ pub fn try_acquire(&self) -> Option<ConnectionPermit> {
+ if let Some(max) = self.max {
+ let admitted =
+ LIVE_CONNECTIONS.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |live| {
+ (live < max).then_some(live + 1)
+ });
+ if let Err(live) = admitted {
+ self.log_refusal(live, max);
+ return None;
+ }
+ } else {
+ LIVE_CONNECTIONS.fetch_add(1, Ordering::Relaxed);
+ }
+ Some(ConnectionPermit { _private: () })
+ }
+
+ fn log_refusal(&self, live: usize, max: usize) {
+ let refused = self.refused_since_log.get() + 1;
+ let now = Instant::now();
+ if self
+ .last_refusal_log
+ .get()
+ .is_some_and(|last| now.duration_since(last) < REFUSAL_LOG_INTERVAL)
+ {
+ self.refused_since_log.set(refused);
+ return;
+ }
+ self.last_refusal_log.set(Some(now));
+ self.refused_since_log.set(0);
+ warn!(
Review Comment:
nit: this warning does not name `message_bus.connections_max`, so the operator cannot tell which setting to raise. name the key, as most boot lines in `boot/fd_limit.rs` do.
##########
core/message_bus/src/accept.rs:
##########
@@ -0,0 +1,45 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Accept-loop handling of descriptor exhaustion.
+
+use server_common::fatal::is_descriptor_exhaustion;
+use std::io;
+use std::time::Duration;
+
+/// How long an accept loop waits after `EMFILE` or `ENFILE`.
+///
+/// The kernel keeps the connection in the listen backlog, so an immediate
+/// retry fails again and spins the shard at full CPU while the descriptor
+/// table stays full.
+pub const DESCRIPTOR_EXHAUSTION_BACKOFF: Duration = Duration::from_secs(1);
+
+/// Wait [`DESCRIPTOR_EXHAUSTION_BACKOFF`] if `error` says no file descriptor
+/// is free, and return at once for any other `accept()` error.
+///
+/// An accept loop only waits. It does not record the exhaustion for the exit
+/// status as the storage write paths do, because no write failed.
+/// `[message_bus] connections_max` keeps clients below the descriptor limit,
+/// so an accept reaches `EMFILE` only when that cap is off or set too high, or
+/// when storage holds the descriptors. A process exit here would let clients
+/// stop the node in the first two cases.
+#[allow(clippy::future_not_send)]
+pub async fn pause_after_accept_error(error: &io::Error) {
+ if is_descriptor_exhaustion(error) {
Review Comment:
nit: as before this PR, a persistent `ENOMEM` or `ENOBUFS` from accept still spins shard 0 with one error line per retry. pause on those too, the memory errors that `accept(2)` documents.
##########
core/server/src/main.rs:
##########
@@ -99,6 +116,13 @@ fn main() -> Result<(), ServerError> {
if let Err(error) = &joined {
server::boot::systemd::notify_shutdown_failure(error);
}
+ if let Err(error) = &joined
+ && descriptors_exhausted()
+ {
+ // `fatal` skips destructors, and the log appenders flush on drop.
+ drop(logging);
Review Comment:
nit: `drop(logging)` runs before `fatal` emits its event, so the exit 4 reason never reaches the log file or stdout. emit the event first, then drop logging, write stderr and exit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@iggy.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org