1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Multi-node multiplexed interactive session handling
use anyhow::Result;
use chrono;
use owo_colors::OwoColorize;
use rustyline::config::Configurer;
use rustyline::error::ReadlineError;
use rustyline::DefaultEditor;
use tokio::time::Duration;
use super::super::interactive_signal::is_interrupted;
use super::types::{
InteractiveCommand, NodeSession, NODES_TO_SHOW_IN_COMPACT, SSH_OUTPUT_POLL_INTERVAL_MS,
};
impl InteractiveCommand {
/// Run interactive mode with multiple nodes (multiplex)
pub(super) async fn run_multiplex_mode(&self, mut sessions: Vec<NodeSession>) -> Result<usize> {
let mut commands_executed = 0;
// Set up rustyline editor
let history_path = self.expand_path(&self.history_file)?;
let mut rl = DefaultEditor::new()?;
rl.set_max_history_size(1000)?;
// Load history if it exists
if history_path.exists() {
let _ = rl.load_history(&history_path);
}
println!(
"Interactive multiplex mode started. Commands will be sent to all {} nodes.",
sessions.len()
);
println!("Type 'exit' or press Ctrl+D to quit. Type '!help' for special commands.");
println!();
// Main interactive loop
loop {
// Check for interrupt signal
if is_interrupted() {
println!("\nInterrupted by user. Exiting...");
break;
}
// Build prompt with node status
let active_count = sessions
.iter()
.filter(|s| s.is_active && s.is_connected)
.count();
let total_connected = sessions.iter().filter(|s| s.is_connected).count();
let total_nodes = sessions.len();
// Use compact display for many nodes (threshold: 10)
const MAX_INDIVIDUAL_DISPLAY: usize = 10;
let prompt = if total_nodes > MAX_INDIVIDUAL_DISPLAY {
// Compact display for many nodes
if active_count == total_connected {
// All active
format!("[All {total_connected}/{total_nodes}] bssh> ")
} else if active_count == 0 {
// None active
format!("[None 0/{total_connected}] bssh> ")
} else {
// Some active - show which nodes are active (first few)
let active_nodes: Vec<usize> = sessions
.iter()
.enumerate()
.filter(|(_, s)| s.is_active && s.is_connected)
.map(|(i, _)| i + 1)
.collect();
let display = if active_nodes.len() <= 5 {
// Show all active node numbers if 5 or fewer
let node_list = active_nodes
.iter()
.map(std::string::ToString::to_string)
.collect::<Vec<_>>()
.join(",");
format!("[Nodes {node_list}]")
} else {
// Show first 3 and count
let first_three = active_nodes
.iter()
.take(NODES_TO_SHOW_IN_COMPACT)
.map(std::string::ToString::to_string)
.collect::<Vec<_>>()
.join(",");
format!(
"[Nodes {first_three}... +{}]",
active_nodes.len() - NODES_TO_SHOW_IN_COMPACT
)
};
format!("{display} ({active_count}/{total_connected}) bssh> ")
}
} else if active_count == total_connected {
// All nodes active - show simple status for small number of nodes
let mut status = String::from("[");
for (i, session) in sessions.iter().enumerate() {
if i > 0 {
status.push(' ');
}
if session.is_connected {
status.push_str(&"●".green().to_string());
} else {
status.push_str(&"○".red().to_string());
}
}
status.push_str("] bssh> ");
status
} else {
// Some nodes inactive - show which are active for small number of nodes
let mut status = String::from("[");
for (i, session) in sessions.iter().enumerate() {
if i > 0 {
status.push(' ');
}
if !session.is_connected {
status.push_str(&"○".red().to_string());
} else if session.is_active {
status.push_str(&format!("{}", (i + 1).to_string().green()));
} else {
status.push_str(&"·".yellow().to_string());
}
}
status.push_str(&format!("] ({active_count}/{total_connected}) bssh> "));
status
};
// Read input
match rl.readline(&prompt) {
Ok(line) => {
if line.trim() == "exit" {
break;
}
// Check for broadcast command specifically
let broadcast_prefix = self
.interactive_config
.broadcast_prefix
.as_deref()
.unwrap_or("!broadcast ");
let is_broadcast = line.trim().starts_with(broadcast_prefix);
let command_to_execute = if is_broadcast {
// Extract the actual command from the broadcast prefix
line.trim()
.strip_prefix(broadcast_prefix)
.unwrap_or("")
.to_string()
} else {
line.clone()
};
// Check for special commands first (non-broadcast)
let special_prefix = self
.interactive_config
.node_switch_prefix
.as_deref()
.unwrap_or("!");
if !is_broadcast
&& line.trim().starts_with(special_prefix)
&& self.handle_special_command(&line, &mut sessions, special_prefix)?
{
continue; // Command was handled, continue to next iteration
}
// Skip if broadcast command is empty
if is_broadcast && command_to_execute.trim().is_empty() {
println!("Usage: {broadcast_prefix}<command>");
continue;
}
rl.add_history_entry(&line)?;
// Save current active states if broadcasting
let saved_states: Vec<bool> = if is_broadcast {
println!("Broadcasting command to all connected nodes...");
sessions.iter().map(|s| s.is_active).collect()
} else {
vec![]
};
// Temporarily activate all nodes for broadcast
if is_broadcast {
for session in &mut sessions {
if session.is_connected {
session.is_active = true;
}
}
}
// Send command to active nodes
let mut command_sent = false;
for session in &mut sessions {
if session.is_connected && session.is_active {
if let Err(e) = session.send_command(&command_to_execute).await {
eprintln!(
"Failed to send command to {}: {}",
session.node.to_string().red(),
e
);
session.is_connected = false;
} else {
command_sent = true;
}
}
}
// Restore previous active states after broadcast
if is_broadcast && !saved_states.is_empty() {
for (session, was_active) in sessions.iter_mut().zip(saved_states.iter()) {
session.is_active = *was_active;
}
}
if command_sent {
commands_executed += 1;
} else {
eprintln!(
"No active nodes to send command to. Use !list to see nodes or !all to activate all."
);
continue;
}
// Use select! to efficiently collect output from all active nodes
let output_timeout = tokio::time::sleep(Duration::from_millis(500));
tokio::pin!(output_timeout);
// Collect output with timeout using select!
loop {
let mut has_output = false;
tokio::select! {
// Timeout reached, stop collecting output
_ = &mut output_timeout => {
break;
}
// Try to read output from each active session
_ = async {
for session in &mut sessions {
if session.is_connected && session.is_active {
if let Ok(Some(output)) = session.read_output().await {
has_output = true;
// Print output with node prefix and optional timestamp
for line in output.lines() {
if self.interactive_config.show_timestamps {
let timestamp = chrono::Local::now().format("%H:%M:%S");
println!(
"[{} {}] {}",
timestamp.to_string().dimmed(),
format!(
"{}@{}",
session.node.username, session.node.host
)
.cyan(),
line
);
} else {
println!(
"[{}] {}",
format!(
"{}@{}",
session.node.username, session.node.host
)
.cyan(),
line
);
}
}
}
}
}
// If no output was found, sleep briefly to avoid busy waiting
if !has_output {
// Output polling interval in multiplex mode:
// - 10ms provides responsive output collection
// - Prevents busy waiting when no output available
// - Short enough to maintain interactive feel
tokio::time::sleep(Duration::from_millis(SSH_OUTPUT_POLL_INTERVAL_MS)).await;
}
} => {
if !has_output {
break; // No more output available
}
}
}
}
}
Err(ReadlineError::Interrupted) => {
println!("^C");
}
Err(ReadlineError::Eof) => {
println!("^D");
break;
}
Err(err) => {
eprintln!("Error: {err}");
break;
}
}
// Check if all nodes are disconnected
if sessions.iter().all(|s| !s.is_connected) {
eprintln!("All nodes disconnected. Exiting.");
break;
}
}
// Clean up
let _ = rl.save_history(&history_path);
Ok(commands_executed)
}
}