kernels.rs

  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
 84impl Kernel {
 85    pub fn dot(&mut self) -> Indicator {
 86        match self {
 87            Kernel::RunningKernel(kernel) => match kernel.execution_state {
 88                ExecutionState::Idle => Indicator::dot().color(Color::Success),
 89                ExecutionState::Busy => Indicator::dot().color(Color::Modified),
 90            },
 91            Kernel::StartingKernel(_) => Indicator::dot().color(Color::Modified),
 92            Kernel::ErroredLaunch(_) => Indicator::dot().color(Color::Error),
 93            Kernel::ShuttingDown => Indicator::dot().color(Color::Modified),
 94            Kernel::Shutdown => Indicator::dot().color(Color::Disabled),
 95        }
 96    }
 97
 98    pub fn set_execution_state(&mut self, status: &ExecutionState) {
 99        match self {
100            Kernel::RunningKernel(running_kernel) => {
101                running_kernel.execution_state = status.clone();
102            }
103            _ => {}
104        }
105    }
106
107    pub fn set_kernel_info(&mut self, kernel_info: &KernelInfoReply) {
108        match self {
109            Kernel::RunningKernel(running_kernel) => {
110                running_kernel.kernel_info = Some(kernel_info.clone());
111            }
112            _ => {}
113        }
114    }
115}
116
117pub struct RunningKernel {
118    pub process: smol::process::Child,
119    _shell_task: Task<anyhow::Result<()>>,
120    _iopub_task: Task<anyhow::Result<()>>,
121    _control_task: Task<anyhow::Result<()>>,
122    _routing_task: Task<anyhow::Result<()>>,
123    connection_path: PathBuf,
124    pub request_tx: mpsc::Sender<JupyterMessage>,
125    pub execution_state: ExecutionState,
126    pub kernel_info: Option<KernelInfoReply>,
127}
128
129type JupyterMessageChannel = stream::SelectAll<Receiver<JupyterMessage>>;
130
131impl Debug for RunningKernel {
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        f.debug_struct("RunningKernel")
134            .field("process", &self.process)
135            .finish()
136    }
137}
138
139impl RunningKernel {
140    pub fn new(
141        kernel_specification: KernelSpecification,
142        entity_id: EntityId,
143        fs: Arc<dyn Fs>,
144        cx: &mut AppContext,
145    ) -> Task<anyhow::Result<(Self, JupyterMessageChannel)>> {
146        cx.spawn(|cx| async move {
147            let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
148            let ports = peek_ports(ip).await?;
149
150            let connection_info = ConnectionInfo {
151                transport: "tcp".to_string(),
152                ip: ip.to_string(),
153                stdin_port: ports[0],
154                control_port: ports[1],
155                hb_port: ports[2],
156                shell_port: ports[3],
157                iopub_port: ports[4],
158                signature_scheme: "hmac-sha256".to_string(),
159                key: uuid::Uuid::new_v4().to_string(),
160                kernel_name: Some(format!("zed-{}", kernel_specification.name)),
161            };
162
163            let runtime_dir = dirs::runtime_dir();
164            fs.create_dir(&runtime_dir)
165                .await
166                .with_context(|| format!("Failed to create jupyter runtime dir {runtime_dir:?}"))?;
167            let connection_path = runtime_dir.join(format!("kernel-zed-{entity_id}.json"));
168            let content = serde_json::to_string(&connection_info)?;
169            // write out file to disk for kernel
170            fs.atomic_write(connection_path.clone(), content).await?;
171
172            let mut cmd = kernel_specification.command(&connection_path)?;
173            let process = cmd
174                // .stdout(Stdio::null())
175                // .stderr(Stdio::null())
176                .kill_on_drop(true)
177                .spawn()
178                .context("failed to start the kernel process")?;
179
180            let mut iopub_socket = connection_info.create_client_iopub_connection("").await?;
181            let mut shell_socket = connection_info.create_client_shell_connection().await?;
182            let mut control_socket = connection_info.create_client_control_connection().await?;
183
184            let (mut iopub, iosub) = futures::channel::mpsc::channel(100);
185
186            let (request_tx, mut request_rx) =
187                futures::channel::mpsc::channel::<JupyterMessage>(100);
188
189            let (mut control_reply_tx, control_reply_rx) = futures::channel::mpsc::channel(100);
190            let (mut shell_reply_tx, shell_reply_rx) = futures::channel::mpsc::channel(100);
191
192            let mut messages_rx = SelectAll::new();
193            messages_rx.push(iosub);
194            messages_rx.push(control_reply_rx);
195            messages_rx.push(shell_reply_rx);
196
197            let _iopub_task = cx.background_executor().spawn({
198                async move {
199                    while let Ok(message) = iopub_socket.read().await {
200                        iopub.send(message).await?;
201                    }
202                    anyhow::Ok(())
203                }
204            });
205
206            let (mut control_request_tx, mut control_request_rx) =
207                futures::channel::mpsc::channel(100);
208            let (mut shell_request_tx, mut shell_request_rx) = futures::channel::mpsc::channel(100);
209
210            let _routing_task = cx.background_executor().spawn({
211                async move {
212                    while let Some(message) = request_rx.next().await {
213                        match message.content {
214                            JupyterMessageContent::DebugRequest(_)
215                            | JupyterMessageContent::InterruptRequest(_)
216                            | JupyterMessageContent::ShutdownRequest(_) => {
217                                control_request_tx.send(message).await?;
218                            }
219                            _ => {
220                                shell_request_tx.send(message).await?;
221                            }
222                        }
223                    }
224                    anyhow::Ok(())
225                }
226            });
227
228            let _shell_task = cx.background_executor().spawn({
229                async move {
230                    while let Some(message) = shell_request_rx.next().await {
231                        shell_socket.send(message).await.ok();
232                        let reply = shell_socket.read().await?;
233                        shell_reply_tx.send(reply).await?;
234                    }
235                    anyhow::Ok(())
236                }
237            });
238
239            let _control_task = cx.background_executor().spawn({
240                async move {
241                    while let Some(message) = control_request_rx.next().await {
242                        control_socket.send(message).await.ok();
243                        let reply = control_socket.read().await?;
244                        control_reply_tx.send(reply).await?;
245                    }
246                    anyhow::Ok(())
247                }
248            });
249
250            anyhow::Ok((
251                Self {
252                    process,
253                    request_tx,
254                    _shell_task,
255                    _iopub_task,
256                    _control_task,
257                    _routing_task,
258                    connection_path,
259                    execution_state: ExecutionState::Busy,
260                    kernel_info: None,
261                },
262                messages_rx,
263            ))
264        })
265    }
266}
267
268impl Drop for RunningKernel {
269    fn drop(&mut self) {
270        std::fs::remove_file(&self.connection_path).ok();
271
272        self.request_tx.close_channel();
273    }
274}
275
276async fn read_kernelspec_at(
277    // Path should be a directory to a jupyter kernelspec, as in
278    // /usr/local/share/jupyter/kernels/python3
279    kernel_dir: PathBuf,
280    fs: &dyn Fs,
281) -> anyhow::Result<KernelSpecification> {
282    let path = kernel_dir;
283    let kernel_name = if let Some(kernel_name) = path.file_name() {
284        kernel_name.to_string_lossy().to_string()
285    } else {
286        anyhow::bail!("Invalid kernelspec directory: {path:?}");
287    };
288
289    if !fs.is_dir(path.as_path()).await {
290        anyhow::bail!("Not a directory: {path:?}");
291    }
292
293    let expected_kernel_json = path.join("kernel.json");
294    let spec = fs.load(expected_kernel_json.as_path()).await?;
295    let spec = serde_json::from_str::<JupyterKernelspec>(&spec)?;
296
297    Ok(KernelSpecification {
298        name: kernel_name,
299        path,
300        kernelspec: spec,
301    })
302}
303
304/// Read a directory of kernelspec directories
305async fn read_kernels_dir(path: PathBuf, fs: &dyn Fs) -> anyhow::Result<Vec<KernelSpecification>> {
306    let mut kernelspec_dirs = fs.read_dir(&path).await?;
307
308    let mut valid_kernelspecs = Vec::new();
309    while let Some(path) = kernelspec_dirs.next().await {
310        match path {
311            Ok(path) => {
312                if fs.is_dir(path.as_path()).await {
313                    if let Ok(kernelspec) = read_kernelspec_at(path, fs).await {
314                        valid_kernelspecs.push(kernelspec);
315                    }
316                }
317            }
318            Err(err) => log::warn!("Error reading kernelspec directory: {err:?}"),
319        }
320    }
321
322    Ok(valid_kernelspecs)
323}
324
325pub async fn kernel_specifications(fs: Arc<dyn Fs>) -> anyhow::Result<Vec<KernelSpecification>> {
326    let data_dirs = dirs::data_dirs();
327    let kernel_dirs = data_dirs
328        .iter()
329        .map(|dir| dir.join("kernels"))
330        .map(|path| read_kernels_dir(path, fs.as_ref()))
331        .collect::<Vec<_>>();
332
333    let kernel_dirs = futures::future::join_all(kernel_dirs).await;
334    let kernel_dirs = kernel_dirs
335        .into_iter()
336        .filter_map(Result::ok)
337        .flatten()
338        .collect::<Vec<_>>();
339
340    Ok(kernel_dirs)
341}
342
343#[cfg(test)]
344mod test {
345    use super::*;
346    use std::path::PathBuf;
347
348    use gpui::TestAppContext;
349    use project::FakeFs;
350    use serde_json::json;
351
352    #[gpui::test]
353    async fn test_get_kernelspecs(cx: &mut TestAppContext) {
354        let fs = FakeFs::new(cx.executor());
355        fs.insert_tree(
356            "/jupyter",
357            json!({
358                ".zed": {
359                    "settings.json": r#"{ "tab_size": 8 }"#,
360                    "tasks.json": r#"[{
361                        "label": "cargo check",
362                        "command": "cargo",
363                        "args": ["check", "--all"]
364                    },]"#,
365                },
366                "kernels": {
367                    "python": {
368                        "kernel.json": r#"{
369                            "display_name": "Python 3",
370                            "language": "python",
371                            "argv": ["python3", "-m", "ipykernel_launcher", "-f", "{connection_file}"],
372                            "env": {}
373                        }"#
374                    },
375                    "deno": {
376                        "kernel.json": r#"{
377                            "display_name": "Deno",
378                            "language": "typescript",
379                            "argv": ["deno", "run", "--unstable", "--allow-net", "--allow-read", "https://deno.land/std/http/file_server.ts", "{connection_file}"],
380                            "env": {}
381                        }"#
382                    }
383                },
384            }),
385        )
386        .await;
387
388        let mut kernels = read_kernels_dir(PathBuf::from("/jupyter/kernels"), fs.as_ref())
389            .await
390            .unwrap();
391
392        kernels.sort_by(|a, b| a.name.cmp(&b.name));
393
394        assert_eq!(
395            kernels.iter().map(|c| c.name.clone()).collect::<Vec<_>>(),
396            vec!["deno", "python"]
397        );
398    }
399}