1use anyhow::{Context as _, Result};
2use futures::{
3 channel::mpsc::{self, Receiver},
4 future::Shared,
5 stream::{self, SelectAll, StreamExt},
6 SinkExt as _,
7};
8use gpui::{AppContext, EntityId, Task};
9use project::Fs;
10use runtimelib::{
11 dirs, ConnectionInfo, ExecutionState, JupyterKernelspec, JupyterMessage, JupyterMessageContent,
12 KernelInfoReply,
13};
14use smol::{net::TcpListener, process::Command};
15use std::{
16 fmt::Debug,
17 net::{IpAddr, Ipv4Addr, SocketAddr},
18 path::PathBuf,
19 sync::Arc,
20};
21use ui::{Color, Indicator};
22
23#[derive(Debug, Clone)]
24pub struct KernelSpecification {
25 pub name: String,
26 pub path: PathBuf,
27 pub kernelspec: JupyterKernelspec,
28}
29
30impl KernelSpecification {
31 #[must_use]
32 fn command(&self, connection_path: &PathBuf) -> anyhow::Result<Command> {
33 let argv = &self.kernelspec.argv;
34
35 anyhow::ensure!(!argv.is_empty(), "Empty argv in kernelspec {}", self.name);
36 anyhow::ensure!(argv.len() >= 2, "Invalid argv in kernelspec {}", self.name);
37 anyhow::ensure!(
38 argv.iter().any(|arg| arg == "{connection_file}"),
39 "Missing 'connection_file' in argv in kernelspec {}",
40 self.name
41 );
42
43 let mut cmd = Command::new(&argv[0]);
44
45 for arg in &argv[1..] {
46 if arg == "{connection_file}" {
47 cmd.arg(connection_path);
48 } else {
49 cmd.arg(arg);
50 }
51 }
52
53 if let Some(env) = &self.kernelspec.env {
54 cmd.envs(env);
55 }
56
57 Ok(cmd)
58 }
59}
60
61// Find a set of open ports. This creates a listener with port set to 0. The listener will be closed at the end when it goes out of scope.
62// There's a race condition between closing the ports and usage by a kernel, but it's inherent to the Jupyter protocol.
63async fn peek_ports(ip: IpAddr) -> anyhow::Result<[u16; 5]> {
64 let mut addr_zeroport: SocketAddr = SocketAddr::new(ip, 0);
65 addr_zeroport.set_port(0);
66 let mut ports: [u16; 5] = [0; 5];
67 for i in 0..5 {
68 let listener = TcpListener::bind(addr_zeroport).await?;
69 let addr = listener.local_addr()?;
70 ports[i] = addr.port();
71 }
72 Ok(ports)
73}
74
75#[derive(Debug)]
76pub enum Kernel {
77 RunningKernel(RunningKernel),
78 StartingKernel(Shared<Task<()>>),
79 ErroredLaunch(String),
80 ShuttingDown,
81 Shutdown,
82}
83
84#[derive(Debug, Clone)]
85pub enum KernelStatus {
86 Idle,
87 Busy,
88 Starting,
89 Error,
90 ShuttingDown,
91 Shutdown,
92}
93impl KernelStatus {
94 pub fn is_connected(&self) -> bool {
95 match self {
96 KernelStatus::Idle | KernelStatus::Busy => true,
97 _ => false,
98 }
99 }
100}
101
102impl ToString for KernelStatus {
103 fn to_string(&self) -> String {
104 match self {
105 KernelStatus::Idle => "Idle".to_string(),
106 KernelStatus::Busy => "Busy".to_string(),
107 KernelStatus::Starting => "Starting".to_string(),
108 KernelStatus::Error => "Error".to_string(),
109 KernelStatus::ShuttingDown => "Shutting Down".to_string(),
110 KernelStatus::Shutdown => "Shutdown".to_string(),
111 }
112 }
113}
114
115impl From<&Kernel> for KernelStatus {
116 fn from(kernel: &Kernel) -> Self {
117 match kernel {
118 Kernel::RunningKernel(kernel) => match kernel.execution_state {
119 ExecutionState::Idle => KernelStatus::Idle,
120 ExecutionState::Busy => KernelStatus::Busy,
121 },
122 Kernel::StartingKernel(_) => KernelStatus::Starting,
123 Kernel::ErroredLaunch(_) => KernelStatus::Error,
124 Kernel::ShuttingDown => KernelStatus::ShuttingDown,
125 Kernel::Shutdown => KernelStatus::Shutdown,
126 }
127 }
128}
129
130impl Kernel {
131 pub fn dot(&self) -> Indicator {
132 match self {
133 Kernel::RunningKernel(kernel) => match kernel.execution_state {
134 ExecutionState::Idle => Indicator::dot().color(Color::Success),
135 ExecutionState::Busy => Indicator::dot().color(Color::Modified),
136 },
137 Kernel::StartingKernel(_) => Indicator::dot().color(Color::Modified),
138 Kernel::ErroredLaunch(_) => Indicator::dot().color(Color::Error),
139 Kernel::ShuttingDown => Indicator::dot().color(Color::Modified),
140 Kernel::Shutdown => Indicator::dot().color(Color::Disabled),
141 }
142 }
143
144 pub fn status(&self) -> KernelStatus {
145 self.into()
146 }
147
148 pub fn set_execution_state(&mut self, status: &ExecutionState) {
149 match self {
150 Kernel::RunningKernel(running_kernel) => {
151 running_kernel.execution_state = status.clone();
152 }
153 _ => {}
154 }
155 }
156
157 pub fn set_kernel_info(&mut self, kernel_info: &KernelInfoReply) {
158 match self {
159 Kernel::RunningKernel(running_kernel) => {
160 running_kernel.kernel_info = Some(kernel_info.clone());
161 }
162 _ => {}
163 }
164 }
165}
166
167pub struct RunningKernel {
168 pub process: smol::process::Child,
169 _shell_task: Task<anyhow::Result<()>>,
170 _iopub_task: Task<anyhow::Result<()>>,
171 _control_task: Task<anyhow::Result<()>>,
172 _routing_task: Task<anyhow::Result<()>>,
173 connection_path: PathBuf,
174 pub working_directory: PathBuf,
175 pub request_tx: mpsc::Sender<JupyterMessage>,
176 pub execution_state: ExecutionState,
177 pub kernel_info: Option<KernelInfoReply>,
178}
179
180type JupyterMessageChannel = stream::SelectAll<Receiver<JupyterMessage>>;
181
182impl Debug for RunningKernel {
183 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184 f.debug_struct("RunningKernel")
185 .field("process", &self.process)
186 .finish()
187 }
188}
189
190impl RunningKernel {
191 pub fn new(
192 kernel_specification: KernelSpecification,
193 entity_id: EntityId,
194 working_directory: PathBuf,
195 fs: Arc<dyn Fs>,
196 cx: &mut AppContext,
197 ) -> Task<anyhow::Result<(Self, JupyterMessageChannel)>> {
198 cx.spawn(|cx| async move {
199 let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
200 let ports = peek_ports(ip).await?;
201
202 let connection_info = ConnectionInfo {
203 transport: "tcp".to_string(),
204 ip: ip.to_string(),
205 stdin_port: ports[0],
206 control_port: ports[1],
207 hb_port: ports[2],
208 shell_port: ports[3],
209 iopub_port: ports[4],
210 signature_scheme: "hmac-sha256".to_string(),
211 key: uuid::Uuid::new_v4().to_string(),
212 kernel_name: Some(format!("zed-{}", kernel_specification.name)),
213 };
214
215 let runtime_dir = dirs::runtime_dir();
216 fs.create_dir(&runtime_dir)
217 .await
218 .with_context(|| format!("Failed to create jupyter runtime dir {runtime_dir:?}"))?;
219 let connection_path = runtime_dir.join(format!("kernel-zed-{entity_id}.json"));
220 let content = serde_json::to_string(&connection_info)?;
221 fs.atomic_write(connection_path.clone(), content).await?;
222
223 let mut cmd = kernel_specification.command(&connection_path)?;
224
225 let process = cmd
226 .current_dir(&working_directory)
227 // .stdout(Stdio::null())
228 // .stderr(Stdio::null())
229 .kill_on_drop(true)
230 .spawn()
231 .context("failed to start the kernel process")?;
232
233 let mut iopub_socket = connection_info.create_client_iopub_connection("").await?;
234 let mut shell_socket = connection_info.create_client_shell_connection().await?;
235 let mut control_socket = connection_info.create_client_control_connection().await?;
236
237 let (mut iopub, iosub) = futures::channel::mpsc::channel(100);
238
239 let (request_tx, mut request_rx) =
240 futures::channel::mpsc::channel::<JupyterMessage>(100);
241
242 let (mut control_reply_tx, control_reply_rx) = futures::channel::mpsc::channel(100);
243 let (mut shell_reply_tx, shell_reply_rx) = futures::channel::mpsc::channel(100);
244
245 let mut messages_rx = SelectAll::new();
246 messages_rx.push(iosub);
247 messages_rx.push(control_reply_rx);
248 messages_rx.push(shell_reply_rx);
249
250 let _iopub_task = cx.background_executor().spawn({
251 async move {
252 while let Ok(message) = iopub_socket.read().await {
253 iopub.send(message).await?;
254 }
255 anyhow::Ok(())
256 }
257 });
258
259 let (mut control_request_tx, mut control_request_rx) =
260 futures::channel::mpsc::channel(100);
261 let (mut shell_request_tx, mut shell_request_rx) = futures::channel::mpsc::channel(100);
262
263 let _routing_task = cx.background_executor().spawn({
264 async move {
265 while let Some(message) = request_rx.next().await {
266 match message.content {
267 JupyterMessageContent::DebugRequest(_)
268 | JupyterMessageContent::InterruptRequest(_)
269 | JupyterMessageContent::ShutdownRequest(_) => {
270 control_request_tx.send(message).await?;
271 }
272 _ => {
273 shell_request_tx.send(message).await?;
274 }
275 }
276 }
277 anyhow::Ok(())
278 }
279 });
280
281 let _shell_task = cx.background_executor().spawn({
282 async move {
283 while let Some(message) = shell_request_rx.next().await {
284 shell_socket.send(message).await.ok();
285 let reply = shell_socket.read().await?;
286 shell_reply_tx.send(reply).await?;
287 }
288 anyhow::Ok(())
289 }
290 });
291
292 let _control_task = cx.background_executor().spawn({
293 async move {
294 while let Some(message) = control_request_rx.next().await {
295 control_socket.send(message).await.ok();
296 let reply = control_socket.read().await?;
297 control_reply_tx.send(reply).await?;
298 }
299 anyhow::Ok(())
300 }
301 });
302
303 anyhow::Ok((
304 Self {
305 process,
306 request_tx,
307 working_directory,
308 _shell_task,
309 _iopub_task,
310 _control_task,
311 _routing_task,
312 connection_path,
313 execution_state: ExecutionState::Busy,
314 kernel_info: None,
315 },
316 messages_rx,
317 ))
318 })
319 }
320}
321
322impl Drop for RunningKernel {
323 fn drop(&mut self) {
324 std::fs::remove_file(&self.connection_path).ok();
325
326 self.request_tx.close_channel();
327 }
328}
329
330async fn read_kernelspec_at(
331 // Path should be a directory to a jupyter kernelspec, as in
332 // /usr/local/share/jupyter/kernels/python3
333 kernel_dir: PathBuf,
334 fs: &dyn Fs,
335) -> anyhow::Result<KernelSpecification> {
336 let path = kernel_dir;
337 let kernel_name = if let Some(kernel_name) = path.file_name() {
338 kernel_name.to_string_lossy().to_string()
339 } else {
340 anyhow::bail!("Invalid kernelspec directory: {path:?}");
341 };
342
343 if !fs.is_dir(path.as_path()).await {
344 anyhow::bail!("Not a directory: {path:?}");
345 }
346
347 let expected_kernel_json = path.join("kernel.json");
348 let spec = fs.load(expected_kernel_json.as_path()).await?;
349 let spec = serde_json::from_str::<JupyterKernelspec>(&spec)?;
350
351 Ok(KernelSpecification {
352 name: kernel_name,
353 path,
354 kernelspec: spec,
355 })
356}
357
358/// Read a directory of kernelspec directories
359async fn read_kernels_dir(path: PathBuf, fs: &dyn Fs) -> anyhow::Result<Vec<KernelSpecification>> {
360 let mut kernelspec_dirs = fs.read_dir(&path).await?;
361
362 let mut valid_kernelspecs = Vec::new();
363 while let Some(path) = kernelspec_dirs.next().await {
364 match path {
365 Ok(path) => {
366 if fs.is_dir(path.as_path()).await {
367 if let Ok(kernelspec) = read_kernelspec_at(path, fs).await {
368 valid_kernelspecs.push(kernelspec);
369 }
370 }
371 }
372 Err(err) => log::warn!("Error reading kernelspec directory: {err:?}"),
373 }
374 }
375
376 Ok(valid_kernelspecs)
377}
378
379pub async fn kernel_specifications(fs: Arc<dyn Fs>) -> anyhow::Result<Vec<KernelSpecification>> {
380 let data_dirs = dirs::data_dirs();
381 let kernel_dirs = data_dirs
382 .iter()
383 .map(|dir| dir.join("kernels"))
384 .map(|path| read_kernels_dir(path, fs.as_ref()))
385 .collect::<Vec<_>>();
386
387 let kernel_dirs = futures::future::join_all(kernel_dirs).await;
388 let kernel_dirs = kernel_dirs
389 .into_iter()
390 .filter_map(Result::ok)
391 .flatten()
392 .collect::<Vec<_>>();
393
394 Ok(kernel_dirs)
395}
396
397#[cfg(test)]
398mod test {
399 use super::*;
400 use std::path::PathBuf;
401
402 use gpui::TestAppContext;
403 use project::FakeFs;
404 use serde_json::json;
405
406 #[gpui::test]
407 async fn test_get_kernelspecs(cx: &mut TestAppContext) {
408 let fs = FakeFs::new(cx.executor());
409 fs.insert_tree(
410 "/jupyter",
411 json!({
412 ".zed": {
413 "settings.json": r#"{ "tab_size": 8 }"#,
414 "tasks.json": r#"[{
415 "label": "cargo check",
416 "command": "cargo",
417 "args": ["check", "--all"]
418 },]"#,
419 },
420 "kernels": {
421 "python": {
422 "kernel.json": r#"{
423 "display_name": "Python 3",
424 "language": "python",
425 "argv": ["python3", "-m", "ipykernel_launcher", "-f", "{connection_file}"],
426 "env": {}
427 }"#
428 },
429 "deno": {
430 "kernel.json": r#"{
431 "display_name": "Deno",
432 "language": "typescript",
433 "argv": ["deno", "run", "--unstable", "--allow-net", "--allow-read", "https://deno.land/std/http/file_server.ts", "{connection_file}"],
434 "env": {}
435 }"#
436 }
437 },
438 }),
439 )
440 .await;
441
442 let mut kernels = read_kernels_dir(PathBuf::from("/jupyter/kernels"), fs.as_ref())
443 .await
444 .unwrap();
445
446 kernels.sort_by(|a, b| a.name.cmp(&b.name));
447
448 assert_eq!(
449 kernels.iter().map(|c| c.name.clone()).collect::<Vec<_>>(),
450 vec!["deno", "python"]
451 );
452 }
453}