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 request_tx: mpsc::Sender<JupyterMessage>,
175 pub execution_state: ExecutionState,
176 pub kernel_info: Option<KernelInfoReply>,
177}
178
179type JupyterMessageChannel = stream::SelectAll<Receiver<JupyterMessage>>;
180
181impl Debug for RunningKernel {
182 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183 f.debug_struct("RunningKernel")
184 .field("process", &self.process)
185 .finish()
186 }
187}
188
189impl RunningKernel {
190 pub fn new(
191 kernel_specification: KernelSpecification,
192 entity_id: EntityId,
193 fs: Arc<dyn Fs>,
194 cx: &mut AppContext,
195 ) -> Task<anyhow::Result<(Self, JupyterMessageChannel)>> {
196 cx.spawn(|cx| async move {
197 let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
198 let ports = peek_ports(ip).await?;
199
200 let connection_info = ConnectionInfo {
201 transport: "tcp".to_string(),
202 ip: ip.to_string(),
203 stdin_port: ports[0],
204 control_port: ports[1],
205 hb_port: ports[2],
206 shell_port: ports[3],
207 iopub_port: ports[4],
208 signature_scheme: "hmac-sha256".to_string(),
209 key: uuid::Uuid::new_v4().to_string(),
210 kernel_name: Some(format!("zed-{}", kernel_specification.name)),
211 };
212
213 let runtime_dir = dirs::runtime_dir();
214 fs.create_dir(&runtime_dir)
215 .await
216 .with_context(|| format!("Failed to create jupyter runtime dir {runtime_dir:?}"))?;
217 let connection_path = runtime_dir.join(format!("kernel-zed-{entity_id}.json"));
218 let content = serde_json::to_string(&connection_info)?;
219 // write out file to disk for kernel
220 fs.atomic_write(connection_path.clone(), content).await?;
221
222 let mut cmd = kernel_specification.command(&connection_path)?;
223 let process = cmd
224 // .stdout(Stdio::null())
225 // .stderr(Stdio::null())
226 .kill_on_drop(true)
227 .spawn()
228 .context("failed to start the kernel process")?;
229
230 let mut iopub_socket = connection_info.create_client_iopub_connection("").await?;
231 let mut shell_socket = connection_info.create_client_shell_connection().await?;
232 let mut control_socket = connection_info.create_client_control_connection().await?;
233
234 let (mut iopub, iosub) = futures::channel::mpsc::channel(100);
235
236 let (request_tx, mut request_rx) =
237 futures::channel::mpsc::channel::<JupyterMessage>(100);
238
239 let (mut control_reply_tx, control_reply_rx) = futures::channel::mpsc::channel(100);
240 let (mut shell_reply_tx, shell_reply_rx) = futures::channel::mpsc::channel(100);
241
242 let mut messages_rx = SelectAll::new();
243 messages_rx.push(iosub);
244 messages_rx.push(control_reply_rx);
245 messages_rx.push(shell_reply_rx);
246
247 let _iopub_task = cx.background_executor().spawn({
248 async move {
249 while let Ok(message) = iopub_socket.read().await {
250 iopub.send(message).await?;
251 }
252 anyhow::Ok(())
253 }
254 });
255
256 let (mut control_request_tx, mut control_request_rx) =
257 futures::channel::mpsc::channel(100);
258 let (mut shell_request_tx, mut shell_request_rx) = futures::channel::mpsc::channel(100);
259
260 let _routing_task = cx.background_executor().spawn({
261 async move {
262 while let Some(message) = request_rx.next().await {
263 match message.content {
264 JupyterMessageContent::DebugRequest(_)
265 | JupyterMessageContent::InterruptRequest(_)
266 | JupyterMessageContent::ShutdownRequest(_) => {
267 control_request_tx.send(message).await?;
268 }
269 _ => {
270 shell_request_tx.send(message).await?;
271 }
272 }
273 }
274 anyhow::Ok(())
275 }
276 });
277
278 let _shell_task = cx.background_executor().spawn({
279 async move {
280 while let Some(message) = shell_request_rx.next().await {
281 shell_socket.send(message).await.ok();
282 let reply = shell_socket.read().await?;
283 shell_reply_tx.send(reply).await?;
284 }
285 anyhow::Ok(())
286 }
287 });
288
289 let _control_task = cx.background_executor().spawn({
290 async move {
291 while let Some(message) = control_request_rx.next().await {
292 control_socket.send(message).await.ok();
293 let reply = control_socket.read().await?;
294 control_reply_tx.send(reply).await?;
295 }
296 anyhow::Ok(())
297 }
298 });
299
300 anyhow::Ok((
301 Self {
302 process,
303 request_tx,
304 _shell_task,
305 _iopub_task,
306 _control_task,
307 _routing_task,
308 connection_path,
309 execution_state: ExecutionState::Busy,
310 kernel_info: None,
311 },
312 messages_rx,
313 ))
314 })
315 }
316}
317
318impl Drop for RunningKernel {
319 fn drop(&mut self) {
320 std::fs::remove_file(&self.connection_path).ok();
321
322 self.request_tx.close_channel();
323 }
324}
325
326async fn read_kernelspec_at(
327 // Path should be a directory to a jupyter kernelspec, as in
328 // /usr/local/share/jupyter/kernels/python3
329 kernel_dir: PathBuf,
330 fs: &dyn Fs,
331) -> anyhow::Result<KernelSpecification> {
332 let path = kernel_dir;
333 let kernel_name = if let Some(kernel_name) = path.file_name() {
334 kernel_name.to_string_lossy().to_string()
335 } else {
336 anyhow::bail!("Invalid kernelspec directory: {path:?}");
337 };
338
339 if !fs.is_dir(path.as_path()).await {
340 anyhow::bail!("Not a directory: {path:?}");
341 }
342
343 let expected_kernel_json = path.join("kernel.json");
344 let spec = fs.load(expected_kernel_json.as_path()).await?;
345 let spec = serde_json::from_str::<JupyterKernelspec>(&spec)?;
346
347 Ok(KernelSpecification {
348 name: kernel_name,
349 path,
350 kernelspec: spec,
351 })
352}
353
354/// Read a directory of kernelspec directories
355async fn read_kernels_dir(path: PathBuf, fs: &dyn Fs) -> anyhow::Result<Vec<KernelSpecification>> {
356 let mut kernelspec_dirs = fs.read_dir(&path).await?;
357
358 let mut valid_kernelspecs = Vec::new();
359 while let Some(path) = kernelspec_dirs.next().await {
360 match path {
361 Ok(path) => {
362 if fs.is_dir(path.as_path()).await {
363 if let Ok(kernelspec) = read_kernelspec_at(path, fs).await {
364 valid_kernelspecs.push(kernelspec);
365 }
366 }
367 }
368 Err(err) => log::warn!("Error reading kernelspec directory: {err:?}"),
369 }
370 }
371
372 Ok(valid_kernelspecs)
373}
374
375pub async fn kernel_specifications(fs: Arc<dyn Fs>) -> anyhow::Result<Vec<KernelSpecification>> {
376 let data_dirs = dirs::data_dirs();
377 let kernel_dirs = data_dirs
378 .iter()
379 .map(|dir| dir.join("kernels"))
380 .map(|path| read_kernels_dir(path, fs.as_ref()))
381 .collect::<Vec<_>>();
382
383 let kernel_dirs = futures::future::join_all(kernel_dirs).await;
384 let kernel_dirs = kernel_dirs
385 .into_iter()
386 .filter_map(Result::ok)
387 .flatten()
388 .collect::<Vec<_>>();
389
390 Ok(kernel_dirs)
391}
392
393#[cfg(test)]
394mod test {
395 use super::*;
396 use std::path::PathBuf;
397
398 use gpui::TestAppContext;
399 use project::FakeFs;
400 use serde_json::json;
401
402 #[gpui::test]
403 async fn test_get_kernelspecs(cx: &mut TestAppContext) {
404 let fs = FakeFs::new(cx.executor());
405 fs.insert_tree(
406 "/jupyter",
407 json!({
408 ".zed": {
409 "settings.json": r#"{ "tab_size": 8 }"#,
410 "tasks.json": r#"[{
411 "label": "cargo check",
412 "command": "cargo",
413 "args": ["check", "--all"]
414 },]"#,
415 },
416 "kernels": {
417 "python": {
418 "kernel.json": r#"{
419 "display_name": "Python 3",
420 "language": "python",
421 "argv": ["python3", "-m", "ipykernel_launcher", "-f", "{connection_file}"],
422 "env": {}
423 }"#
424 },
425 "deno": {
426 "kernel.json": r#"{
427 "display_name": "Deno",
428 "language": "typescript",
429 "argv": ["deno", "run", "--unstable", "--allow-net", "--allow-read", "https://deno.land/std/http/file_server.ts", "{connection_file}"],
430 "env": {}
431 }"#
432 }
433 },
434 }),
435 )
436 .await;
437
438 let mut kernels = read_kernels_dir(PathBuf::from("/jupyter/kernels"), fs.as_ref())
439 .await
440 .unwrap();
441
442 kernels.sort_by(|a, b| a.name.cmp(&b.name));
443
444 assert_eq!(
445 kernels.iter().map(|c| c.name.clone()).collect::<Vec<_>>(),
446 vec!["deno", "python"]
447 );
448 }
449}