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