-
Notifications
You must be signed in to change notification settings - Fork 55
Feat/events socket #352
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
GeoffChurch
wants to merge
12
commits into
shell-pool:master
Choose a base branch
from
GeoffChurch:feat/events-socket
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat/events socket #352
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
5e302b6
feat(events): define push-event JSON schema
GeoffChurch bb71939
feat(events): add EventBus and sibling events socket listener
GeoffChurch fd40940
feat(events): publish deltas from session lifecycle mutations
GeoffChurch a8e11c0
feat(events): add `shpool events` subcommand
GeoffChurch cab78b5
test(events): integration tests for the events socket
GeoffChurch a336742
fix(events): de-duplicate lifecycle deltas; clean socket on signal exit
GeoffChurch 3f38bb7
refactor(events): trim event payloads to type fields only
GeoffChurch 0b99ca0
docs(events): add EVENTS.md describing the events protocol
GeoffChurch 47ac2d8
EVENTS.md: fix main socket description and remove "Ordering" section
GeoffChurch aff5279
events: polish error contexts, naming, and module boundary
GeoffChurch 4865abd
events: add tests for bus isolation, latency, and lock ordering
GeoffChurch 8f5e08c
events: replace thread-per-subscriber writers with a single-sink poll…
GeoffChurch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| # Events | ||
|
|
||
| `shpool` exposes an event stream so that external programs can react to changes | ||
| without polling. This way, a program (e.g. a TUI) can call `shpool list` (or the | ||
| equivalent `ConnectHeader::List` request over the main socket; see the | ||
| [`shpool-protocol`](./shpool-protocol) crate) after each event so that its model | ||
| is always consistent with shpool's state. | ||
|
|
||
| ## The events socket | ||
|
|
||
| The daemon binds a sibling Unix socket next to the main shpool socket: | ||
|
|
||
| ```bash | ||
| <runtime_dir>/shpool/shpool.socket # main socket | ||
| <runtime_dir>/shpool/events.socket # events socket (this protocol) | ||
| ``` | ||
|
|
||
| A subscriber connects to `events.socket` and reads events. The daemon ignores anything written to the events socket, so for subscribers it's effectively read-only. | ||
|
|
||
| ## Event types | ||
|
|
||
| | `type` | Meaning | | ||
| | ------------------ | -------------------------------------------------------- | | ||
| | `session.created` | A new session was added to the table. | | ||
| | `session.attached` | A client attached or reattached to a session. | | ||
| | `session.detached` | A client disconnected from a still-running session. | | ||
| | `session.removed` | A session was removed (shell exited, killed, or reaped). | | ||
|
|
||
| Subscribers should ignore unknown `type` values so that future event types do | ||
| not break older consumers. | ||
|
|
||
| ## Wire format | ||
|
|
||
| The daemon writes one JSON object per line (JSONL). Each event looks like: | ||
|
|
||
| ```json | ||
| {"type":"<event-type>"} | ||
| ``` | ||
|
|
||
| There are no other fields. To learn what the event refers to (which session, | ||
| when, etc.), call `shpool list` (or use `ConnectHeader::List`). | ||
|
|
||
| The format is robust: literal newline characters only appear as delimiters | ||
| between events. Any newlines within JSON string values are automatically | ||
| escaped (as `\n`) by the daemon. | ||
|
|
||
| ## Subscribing | ||
|
|
||
| For ad-hoc use, `shpool events` connects to the events socket and prints each | ||
| event line to stdout, flushing after each line: | ||
|
|
||
| ```bash | ||
| shpool events | while read -r ev; do | ||
| echo "got: $ev" | ||
| shpool list | ||
| done | ||
|
|
||
| shpool events | jq . | ||
| ``` | ||
|
|
||
| ## Slow subscribers | ||
|
|
||
| Each subscriber has a bounded outbound queue. A subscriber that falls too far | ||
| behind is dropped by the daemon (in which case the subscriber can always reconnect). | ||
| There is no replay, so events that fired while a subscriber was disconnected are | ||
| lost. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -51,7 +51,7 @@ use crate::{ | |
| etc_environment, exit_notify::ExitNotifier, hooks, pager, pager::PagerError, prompt, shell, | ||
| show_motd, ttl_reaper, | ||
| }, | ||
| protocol, test_hooks, tty, user, | ||
| events, protocol, test_hooks, tty, user, | ||
| }; | ||
|
|
||
| const DEFAULT_INITIAL_SHELL_PATH: &str = "/usr/bin:/bin:/usr/sbin:/sbin"; | ||
|
|
@@ -76,6 +76,7 @@ pub struct Server { | |
| runtime_dir: PathBuf, | ||
| register_new_reapable_session: crossbeam_channel::Sender<(String, Instant)>, | ||
| hooks: Box<dyn hooks::Hooks + Send + Sync>, | ||
| events_bus: Arc<events::EventBus>, | ||
| daily_messenger: Arc<show_motd::DailyMessenger>, | ||
| log_level_handle: tracing_subscriber::reload::Handle< | ||
| tracing_subscriber::filter::LevelFilter, | ||
|
|
@@ -96,13 +97,17 @@ impl Server { | |
| >, | ||
| ) -> anyhow::Result<Arc<Self>> { | ||
| let shells = Arc::new(Mutex::new(HashMap::new())); | ||
| let events_bus = events::EventBus::new().context("creating events bus")?; | ||
| // buffered so that we are unlikely to block when setting up a | ||
| // new session | ||
| let (new_sess_tx, new_sess_rx) = crossbeam_channel::bounded(10); | ||
| let shells_tab = Arc::clone(&shells); | ||
| thread::spawn(move || { | ||
| if let Err(e) = ttl_reaper::run(new_sess_rx, shells_tab) { | ||
| warn!("ttl reaper exited with error: {:?}", e); | ||
| thread::spawn({ | ||
| let shells = Arc::clone(&shells); | ||
| let events_bus = Arc::clone(&events_bus); | ||
| move || { | ||
| if let Err(e) = ttl_reaper::run(new_sess_rx, shells, events_bus) { | ||
| warn!("ttl reaper exited with error: {:?}", e); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
|
|
@@ -113,12 +118,22 @@ impl Server { | |
| runtime_dir, | ||
| register_new_reapable_session: new_sess_tx, | ||
| hooks, | ||
| events_bus, | ||
| daily_messenger, | ||
| log_level_handle, | ||
| vars: HashMap::new().into(), | ||
| })) | ||
| } | ||
|
|
||
| /// Bind the events socket and spawn the accept thread. The returned | ||
| /// guard unlinks the socket file on drop. | ||
| pub fn start_events_listener( | ||
| self: &Arc<Self>, | ||
| socket_path: PathBuf, | ||
| ) -> anyhow::Result<events::ListenerGuard> { | ||
| events::start_listener(socket_path, Arc::clone(&self.events_bus)) | ||
| } | ||
|
|
||
| #[instrument(skip_all)] | ||
| pub fn serve(server: Arc<Self>, listener: UnixListener) -> anyhow::Result<()> { | ||
| test_hooks::emit("daemon-about-to-listen"); | ||
|
|
@@ -333,7 +348,12 @@ impl Server { | |
| { | ||
| let _s = span!(Level::INFO, "2_lock(shells)").entered(); | ||
| let mut shells = self.shells.lock(); | ||
| shells.remove(&header.name); | ||
| // The publish below is gated on `is_some()` because a | ||
| // concurrent kill or reaper may have already removed the | ||
| // entry (and published) while we were waiting for the lock. | ||
| if shells.remove(&header.name).is_some() { | ||
| self.events_bus.publish(&events::Event::SessionRemoved); | ||
| } | ||
| } | ||
|
|
||
| // The child shell has exited, so the shell->client thread should | ||
|
|
@@ -354,6 +374,7 @@ impl Server { | |
| if let Some(session) = shells.get(&header.name) { | ||
| session.lifecycle_timestamps.lock().last_disconnected_at = | ||
| Some(time::SystemTime::now()); | ||
| self.events_bus.publish(&events::Event::SessionDetached); | ||
| } | ||
| } | ||
| if let Err(err) = self.hooks.on_client_disconnect(&header.name) { | ||
|
|
@@ -429,6 +450,9 @@ impl Server { | |
| "child_exited chan unclosed, but shell->client thread has exited, clobbering with new subshell" | ||
| ); | ||
| } else { | ||
| // Reattach confirmed; the create path won't run | ||
| // and clobber the entry, so it's safe to publish. | ||
| self.events_bus.publish(&events::Event::SessionAttached); | ||
| if let Err(err) = self.hooks.on_reattach(&header.name) { | ||
| warn!("reattach hook: {:?}", err); | ||
| } | ||
|
|
@@ -445,8 +469,6 @@ impl Server { | |
| AttachStatus::Attached { warnings }, | ||
| )); | ||
| } | ||
|
|
||
| // status is already attached | ||
| } | ||
| Some(exit_status) => { | ||
| // the channel is closed so we know the subshell exited | ||
|
|
@@ -503,10 +525,18 @@ impl Server { | |
|
|
||
| session.lifecycle_timestamps.lock().last_connected_at = Some(time::SystemTime::now()); | ||
| { | ||
| // we unwrap to propagate the poison as an unwind | ||
| let _s = span!(Level::INFO, "select_shell_lock_2(shells)").entered(); | ||
| let mut shells = self.shells.lock(); | ||
| // If we're replacing a stale entry whose shell process is | ||
| // gone, surface that to subscribers before announcing the | ||
| // replacement. | ||
| let clobbered = shells.contains_key(&header.name); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can avoid the double-probe with the entry API. I think we can do with using |
||
| shells.insert(header.name.clone(), Box::new(session)); | ||
| if clobbered { | ||
| self.events_bus.publish(&events::Event::SessionRemoved); | ||
| } | ||
| self.events_bus.publish(&events::Event::SessionCreated); | ||
| self.events_bus.publish(&events::Event::SessionAttached); | ||
| } | ||
|
|
||
| // we unwrap to propagate the poison as an unwind | ||
|
|
@@ -604,6 +634,10 @@ impl Server { | |
| if let shell::ClientConnectionStatus::DetachNone = status { | ||
| not_attached_sessions.push(session); | ||
| } else { | ||
| // The bidi-loop unwind in handle_attach owns the | ||
| // SessionDetached publish; we just update | ||
| // last_disconnected_at eagerly so a concurrent list() | ||
| // reflects the detach immediately. | ||
| s.lifecycle_timestamps.lock().last_disconnected_at = | ||
| Some(time::SystemTime::now()); | ||
| } | ||
|
|
@@ -714,6 +748,7 @@ impl Server { | |
|
|
||
| for session in to_remove.iter() { | ||
| shells.remove(session); | ||
| self.events_bus.publish(&events::Event::SessionRemoved); | ||
| } | ||
| if !to_remove.is_empty() { | ||
| test_hooks::emit("daemon-handle-kill-removed-shells"); | ||
|
|
@@ -729,8 +764,7 @@ impl Server { | |
| fn handle_list(&self, mut stream: UnixStream) -> anyhow::Result<()> { | ||
| let _s = span!(Level::INFO, "lock(shells)").entered(); | ||
| let shells = self.shells.lock(); | ||
|
|
||
| let sessions: anyhow::Result<Vec<Session>> = shells | ||
| let sessions: Vec<Session> = shells | ||
| .iter() | ||
| .map(|(k, v)| { | ||
| let status = match v.inner.try_lock() { | ||
|
|
@@ -743,7 +777,6 @@ impl Server { | |
| .last_connected_at | ||
| .map(|t| t.duration_since(time::UNIX_EPOCH).map(|d| d.as_millis() as i64)) | ||
| .transpose()?; | ||
|
|
||
| let last_disconnected_at_unix_ms = timestamps | ||
| .last_disconnected_at | ||
| .map(|t| t.duration_since(time::UNIX_EPOCH).map(|d| d.as_millis() as i64)) | ||
|
|
@@ -758,11 +791,9 @@ impl Server { | |
| status, | ||
| }) | ||
| }) | ||
| .collect(); | ||
| let sessions = sessions.context("collecting running session metadata")?; | ||
|
|
||
| .collect::<anyhow::Result<_>>() | ||
| .context("collecting running session metadata")?; | ||
| write_reply(&mut stream, ListReply { sessions })?; | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's a bit weird to have two different things responsible for cleaning up the socket file (this signal handler and the RAII guard). I guess it's a bit of a pre-existing sin of the code, so it's ok to leave it like this, but maybe we should consider instead having the signal handler thread explicitly hang up the events bus to signal for the sink thread to exit and take the socket file with it.