1mod headless_project;
2
3#[cfg(test)]
4mod remote_editing_tests;
5
6#[cfg(windows)]
7pub mod windows;
8
9pub use headless_project::{HeadlessAppState, HeadlessProject};
10
11use anyhow::{Context as _, Result, anyhow};
12use clap::Subcommand;
13use client::ProxySettings;
14use collections::HashMap;
15use extension::ExtensionHostProxy;
16use fs::{Fs, RealFs};
17use futures::{
18 AsyncRead, AsyncWrite, AsyncWriteExt, FutureExt, SinkExt,
19 channel::{mpsc, oneshot},
20 select, select_biased,
21};
22use git::GitHostingProviderRegistry;
23use gpui::{App, AppContext as _, Context, Entity, UpdateGlobal as _};
24use gpui_tokio::Tokio;
25use http_client::{Url, read_proxy_from_env};
26use language::LanguageRegistry;
27use net::async_net::{UnixListener, UnixStream};
28use node_runtime::{NodeBinaryOptions, NodeRuntime};
29use paths::logs_dir;
30use project::{project_settings::ProjectSettings, trusted_worktrees};
31use proto::CrashReport;
32use release_channel::{AppCommitSha, AppVersion, RELEASE_CHANNEL, ReleaseChannel};
33use remote::{
34 RemoteClient,
35 json_log::LogRecord,
36 protocol::{read_message, write_message},
37 proxy::ProxyLaunchError,
38};
39use reqwest_client::ReqwestClient;
40use rpc::proto::{self, Envelope, REMOTE_SERVER_PROJECT_ID};
41use rpc::{AnyProtoClient, TypedEnvelope};
42use settings::{Settings, SettingsStore, watch_config_file};
43use smol::{
44 channel::{Receiver, Sender},
45 io::AsyncReadExt,
46 stream::StreamExt as _,
47};
48use std::{
49 env,
50 ffi::OsStr,
51 fs::File,
52 io::Write,
53 mem,
54 path::{Path, PathBuf},
55 str::FromStr,
56 sync::{Arc, LazyLock},
57 time::Instant,
58};
59use thiserror::Error;
60use util::{ResultExt, command::new_command};
61
62#[derive(Subcommand)]
63pub enum Commands {
64 Run {
65 #[arg(long)]
66 log_file: PathBuf,
67 #[arg(long)]
68 pid_file: PathBuf,
69 #[arg(long)]
70 stdin_socket: PathBuf,
71 #[arg(long)]
72 stdout_socket: PathBuf,
73 #[arg(long)]
74 stderr_socket: PathBuf,
75 },
76 Proxy {
77 #[arg(long)]
78 reconnect: bool,
79 #[arg(long)]
80 identifier: String,
81 },
82 Version,
83}
84
85pub fn run(command: Commands) -> anyhow::Result<()> {
86 use anyhow::Context;
87 use release_channel::{RELEASE_CHANNEL, ReleaseChannel};
88
89 match command {
90 Commands::Run {
91 log_file,
92 pid_file,
93 stdin_socket,
94 stdout_socket,
95 stderr_socket,
96 } => execute_run(
97 log_file,
98 pid_file,
99 stdin_socket,
100 stdout_socket,
101 stderr_socket,
102 ),
103 Commands::Proxy {
104 identifier,
105 reconnect,
106 } => execute_proxy(identifier, reconnect).context("running proxy on the remote server"),
107 Commands::Version => {
108 let release_channel = *RELEASE_CHANNEL;
109 match release_channel {
110 ReleaseChannel::Stable | ReleaseChannel::Preview => {
111 println!("{}", env!("ZED_PKG_VERSION"))
112 }
113 ReleaseChannel::Nightly | ReleaseChannel::Dev => {
114 let commit_sha =
115 option_env!("ZED_COMMIT_SHA").unwrap_or(release_channel.dev_name());
116 let build_id = option_env!("ZED_BUILD_ID");
117 if let Some(build_id) = build_id {
118 println!("{}+{}", build_id, commit_sha)
119 } else {
120 println!("{commit_sha}");
121 }
122 }
123 };
124 Ok(())
125 }
126 }
127}
128
129pub static VERSION: LazyLock<String> = LazyLock::new(|| match *RELEASE_CHANNEL {
130 ReleaseChannel::Stable | ReleaseChannel::Preview => env!("ZED_PKG_VERSION").to_owned(),
131 ReleaseChannel::Nightly | ReleaseChannel::Dev => {
132 let commit_sha = option_env!("ZED_COMMIT_SHA").unwrap_or("missing-zed-commit-sha");
133 let build_identifier = option_env!("ZED_BUILD_ID");
134 if let Some(build_id) = build_identifier {
135 format!("{build_id}+{commit_sha}")
136 } else {
137 commit_sha.to_owned()
138 }
139 }
140});
141
142fn init_logging_proxy() {
143 env_logger::builder()
144 .format(|buf, record| {
145 let mut log_record = LogRecord::new(record);
146 log_record.message =
147 std::borrow::Cow::Owned(format!("(remote proxy) {}", log_record.message));
148 serde_json::to_writer(&mut *buf, &log_record)?;
149 buf.write_all(b"\n")?;
150 Ok(())
151 })
152 .init();
153}
154
155fn init_logging_server(log_file_path: &Path) -> Result<Receiver<Vec<u8>>> {
156 struct MultiWrite {
157 file: File,
158 channel: Sender<Vec<u8>>,
159 buffer: Vec<u8>,
160 }
161
162 impl Write for MultiWrite {
163 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
164 let written = self.file.write(buf)?;
165 self.buffer.extend_from_slice(&buf[..written]);
166 Ok(written)
167 }
168
169 fn flush(&mut self) -> std::io::Result<()> {
170 self.channel
171 .send_blocking(self.buffer.clone())
172 .map_err(std::io::Error::other)?;
173 self.buffer.clear();
174 self.file.flush()
175 }
176 }
177
178 let log_file = std::fs::OpenOptions::new()
179 .create(true)
180 .append(true)
181 .open(log_file_path)
182 .context("Failed to open log file in append mode")?;
183
184 let (tx, rx) = smol::channel::unbounded();
185
186 let target = Box::new(MultiWrite {
187 file: log_file,
188 channel: tx,
189 buffer: Vec::new(),
190 });
191
192 let old_hook = std::panic::take_hook();
193 std::panic::set_hook(Box::new(move |info| {
194 let backtrace = std::backtrace::Backtrace::force_capture();
195 let message = info.payload_as_str().unwrap_or("Box<Any>").to_owned();
196 let location = info
197 .location()
198 .map_or_else(|| "<unknown>".to_owned(), |location| location.to_string());
199 let current_thread = std::thread::current();
200 let thread_name = current_thread.name().unwrap_or("<unnamed>");
201
202 let msg = format!("thread '{thread_name}' panicked at {location}:\n{message}\n{backtrace}");
203 // NOTE: This log never reaches the client, as the communication is handled on a main thread task
204 // which will never run once we panic.
205 log::error!("{msg}");
206 old_hook(info);
207 }));
208 env_logger::Builder::new()
209 .filter_level(log::LevelFilter::Info)
210 .parse_default_env()
211 .target(env_logger::Target::Pipe(target))
212 .format(|buf, record| {
213 let mut log_record = LogRecord::new(record);
214 log_record.message =
215 std::borrow::Cow::Owned(format!("(remote server) {}", log_record.message));
216 serde_json::to_writer(&mut *buf, &log_record)?;
217 buf.write_all(b"\n")?;
218 Ok(())
219 })
220 .init();
221
222 Ok(rx)
223}
224
225fn handle_crash_files_requests(project: &Entity<HeadlessProject>, client: &AnyProtoClient) {
226 client.add_request_handler(
227 project.downgrade(),
228 |_, _: TypedEnvelope<proto::GetCrashFiles>, _cx| async move {
229 let mut legacy_panics = Vec::new();
230 let mut crashes = Vec::new();
231 let mut children = smol::fs::read_dir(paths::logs_dir()).await?;
232 while let Some(child) = children.next().await {
233 let child = child?;
234 let child_path = child.path();
235
236 let extension = child_path.extension();
237 if extension == Some(OsStr::new("panic")) {
238 let filename = if let Some(filename) = child_path.file_name() {
239 filename.to_string_lossy()
240 } else {
241 continue;
242 };
243
244 if !filename.starts_with("zed") {
245 continue;
246 }
247
248 let file_contents = smol::fs::read_to_string(&child_path)
249 .await
250 .context("error reading panic file")?;
251
252 legacy_panics.push(file_contents);
253 smol::fs::remove_file(&child_path)
254 .await
255 .context("error removing panic")
256 .log_err();
257 } else if extension == Some(OsStr::new("dmp")) {
258 let mut json_path = child_path.clone();
259 json_path.set_extension("json");
260 if let Ok(json_content) = smol::fs::read_to_string(&json_path).await {
261 crashes.push(CrashReport {
262 metadata: json_content,
263 minidump_contents: smol::fs::read(&child_path).await?,
264 });
265 smol::fs::remove_file(&child_path).await.log_err();
266 smol::fs::remove_file(&json_path).await.log_err();
267 } else {
268 log::error!("Couldn't find json metadata for crash: {child_path:?}");
269 }
270 }
271 }
272
273 anyhow::Ok(proto::GetCrashFilesResponse { crashes })
274 },
275 );
276}
277
278struct ServerListeners {
279 stdin: UnixListener,
280 stdout: UnixListener,
281 stderr: UnixListener,
282}
283
284impl ServerListeners {
285 pub fn new(stdin_path: PathBuf, stdout_path: PathBuf, stderr_path: PathBuf) -> Result<Self> {
286 Ok(Self {
287 stdin: UnixListener::bind(stdin_path).context("failed to bind stdin socket")?,
288 stdout: UnixListener::bind(stdout_path).context("failed to bind stdout socket")?,
289 stderr: UnixListener::bind(stderr_path).context("failed to bind stderr socket")?,
290 })
291 }
292}
293
294fn start_server(
295 listeners: ServerListeners,
296 log_rx: Receiver<Vec<u8>>,
297 cx: &mut App,
298 is_wsl_interop: bool,
299) -> AnyProtoClient {
300 // This is the server idle timeout. If no connection comes in this timeout, the server will shut down.
301 const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
302
303 let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();
304 let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded::<Envelope>();
305 let (app_quit_tx, mut app_quit_rx) = mpsc::unbounded::<()>();
306
307 cx.on_app_quit(move |_| {
308 let mut app_quit_tx = app_quit_tx.clone();
309 async move {
310 log::info!("app quitting. sending signal to server main loop");
311 app_quit_tx.send(()).await.ok();
312 }
313 })
314 .detach();
315
316 cx.spawn(async move |cx| {
317 loop {
318 let streams = futures::future::join3(
319 listeners.stdin.accept(),
320 listeners.stdout.accept(),
321 listeners.stderr.accept(),
322 );
323
324 log::info!("accepting new connections");
325 let result = select! {
326 streams = streams.fuse() => {
327 let (Ok((stdin_stream, _)), Ok((stdout_stream, _)), Ok((stderr_stream, _))) = streams else {
328 log::error!("failed to accept new connections");
329 break;
330 };
331 log::info!("accepted new connections");
332 anyhow::Ok((stdin_stream, stdout_stream, stderr_stream))
333 }
334 _ = futures::FutureExt::fuse(cx.background_executor().timer(IDLE_TIMEOUT)) => {
335 log::warn!("timed out waiting for new connections after {:?}. exiting.", IDLE_TIMEOUT);
336 cx.update(|cx| {
337 // TODO: This is a hack, because in a headless project, shutdown isn't executed
338 // when calling quit, but it should be.
339 cx.shutdown();
340 cx.quit();
341 });
342 break;
343 }
344 _ = app_quit_rx.next().fuse() => {
345 log::info!("app quit requested");
346 break;
347 }
348 };
349
350 let Ok((mut stdin_stream, mut stdout_stream, mut stderr_stream)) = result else {
351 break;
352 };
353
354 let mut input_buffer = Vec::new();
355 let mut output_buffer = Vec::new();
356
357 let (mut stdin_msg_tx, mut stdin_msg_rx) = mpsc::unbounded::<Envelope>();
358 cx.background_spawn(async move {
359 while let Ok(msg) = read_message(&mut stdin_stream, &mut input_buffer).await {
360 if (stdin_msg_tx.send(msg).await).is_err() {
361 break;
362 }
363 }
364 }).detach();
365
366 loop {
367
368 select_biased! {
369 _ = app_quit_rx.next().fuse() => {
370 return anyhow::Ok(());
371 }
372
373 stdin_message = stdin_msg_rx.next().fuse() => {
374 let Some(message) = stdin_message else {
375 log::warn!("error reading message on stdin, dropping connection.");
376 break;
377 };
378 if let Err(error) = incoming_tx.unbounded_send(message) {
379 log::error!("failed to send message to application: {error:?}. exiting.");
380 return Err(anyhow!(error));
381 }
382 }
383
384 outgoing_message = outgoing_rx.next().fuse() => {
385 let Some(message) = outgoing_message else {
386 log::error!("stdout handler, no message");
387 break;
388 };
389
390 if let Err(error) =
391 write_message(&mut stdout_stream, &mut output_buffer, message).await
392 {
393 log::error!("failed to write stdout message: {:?}", error);
394 break;
395 }
396 if let Err(error) = stdout_stream.flush().await {
397 log::error!("failed to flush stdout message: {:?}", error);
398 break;
399 }
400 }
401
402 log_message = log_rx.recv().fuse() => {
403 if let Ok(log_message) = log_message {
404 if let Err(error) = stderr_stream.write_all(&log_message).await {
405 log::error!("failed to write log message to stderr: {:?}", error);
406 break;
407 }
408 if let Err(error) = stderr_stream.flush().await {
409 log::error!("failed to flush stderr stream: {:?}", error);
410 break;
411 }
412 }
413 }
414 }
415 }
416 }
417 anyhow::Ok(())
418 })
419 .detach();
420
421 RemoteClient::proto_client_from_channels(incoming_rx, outgoing_tx, cx, "server", is_wsl_interop)
422}
423
424fn init_paths() -> anyhow::Result<()> {
425 for path in [
426 paths::config_dir(),
427 paths::extensions_dir(),
428 paths::languages_dir(),
429 paths::logs_dir(),
430 paths::temp_dir(),
431 paths::hang_traces_dir(),
432 paths::remote_extensions_dir(),
433 paths::remote_extensions_uploads_dir(),
434 ]
435 .iter()
436 {
437 std::fs::create_dir_all(path).with_context(|| format!("creating directory {path:?}"))?;
438 }
439 Ok(())
440}
441
442pub fn execute_run(
443 log_file: PathBuf,
444 pid_file: PathBuf,
445 stdin_socket: PathBuf,
446 stdout_socket: PathBuf,
447 stderr_socket: PathBuf,
448) -> Result<()> {
449 init_paths()?;
450
451 let startup_time = Instant::now();
452 let app = gpui_platform::headless();
453 let pid = std::process::id();
454 let id = pid.to_string();
455 crashes::init(
456 crashes::InitCrashHandler {
457 session_id: id,
458 zed_version: VERSION.to_owned(),
459 binary: "zed-remote-server".to_string(),
460 release_channel: release_channel::RELEASE_CHANNEL_NAME.clone(),
461 commit_sha: option_env!("ZED_COMMIT_SHA").unwrap_or("no_sha").to_owned(),
462 },
463 |task| {
464 app.background_executor().spawn(task).detach();
465 },
466 );
467 let log_rx = init_logging_server(&log_file)?;
468 log::info!(
469 "starting up with PID {}:\npid_file: {:?}, log_file: {:?}, stdin_socket: {:?}, stdout_socket: {:?}, stderr_socket: {:?}",
470 pid,
471 pid_file,
472 log_file,
473 stdin_socket,
474 stdout_socket,
475 stderr_socket
476 );
477
478 write_pid_file(&pid_file, pid)
479 .with_context(|| format!("failed to write pid file: {:?}", &pid_file))?;
480
481 let listeners = ServerListeners::new(stdin_socket, stdout_socket, stderr_socket)?;
482
483 rayon::ThreadPoolBuilder::new()
484 .num_threads(std::thread::available_parallelism().map_or(1, |n| n.get().div_ceil(2)))
485 .stack_size(10 * 1024 * 1024)
486 .thread_name(|ix| format!("RayonWorker{}", ix))
487 .build_global()
488 .unwrap();
489
490 #[cfg(unix)]
491 let shell_env_loaded_rx = {
492 let (shell_env_loaded_tx, shell_env_loaded_rx) = oneshot::channel();
493 app.background_executor()
494 .spawn(async {
495 util::load_login_shell_environment().await.log_err();
496 shell_env_loaded_tx.send(()).ok();
497 })
498 .detach();
499 Some(shell_env_loaded_rx)
500 };
501 #[cfg(windows)]
502 let shell_env_loaded_rx: Option<oneshot::Receiver<()>> = None;
503
504 let git_hosting_provider_registry = Arc::new(GitHostingProviderRegistry::new());
505 let run = move |cx: &mut _| {
506 settings::init(cx);
507 let app_commit_sha = option_env!("ZED_COMMIT_SHA").map(|s| AppCommitSha::new(s.to_owned()));
508 let app_version = AppVersion::load(
509 env!("ZED_PKG_VERSION"),
510 option_env!("ZED_BUILD_ID"),
511 app_commit_sha,
512 );
513 release_channel::init(app_version, cx);
514 gpui_tokio::init(cx);
515
516 HeadlessProject::init(cx);
517
518 let is_wsl_interop = if cfg!(target_os = "linux") {
519 // See: https://learn.microsoft.com/en-us/windows/wsl/filesystems#disable-interoperability
520 matches!(std::fs::read_to_string("/proc/sys/fs/binfmt_misc/WSLInterop").or_else(|_| std::fs::read_to_string("/proc/sys/fs/binfmt_misc/WSLInterop-late")), Ok(s) if s.contains("enabled"))
521 } else {
522 false
523 };
524
525 log::info!("gpui app started, initializing server");
526 let session = start_server(listeners, log_rx, cx, is_wsl_interop);
527 trusted_worktrees::init(HashMap::default(), cx);
528
529 GitHostingProviderRegistry::set_global(git_hosting_provider_registry, cx);
530 git_hosting_providers::init(cx);
531 dap_adapters::init(cx);
532
533 extension::init(cx);
534 let extension_host_proxy = ExtensionHostProxy::global(cx);
535
536 json_schema_store::init(cx);
537
538 let project = cx.new(|cx| {
539 let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
540 let node_settings_rx = initialize_settings(session.clone(), fs.clone(), cx);
541
542 let proxy_url = read_proxy_settings(cx);
543
544 let http_client = {
545 let _guard = Tokio::handle(cx).enter();
546 Arc::new(
547 ReqwestClient::proxy_and_user_agent(
548 proxy_url,
549 &format!(
550 "Zed-Server/{} ({}; {})",
551 env!("CARGO_PKG_VERSION"),
552 std::env::consts::OS,
553 std::env::consts::ARCH
554 ),
555 )
556 .expect("Could not start HTTP client"),
557 )
558 };
559
560 let node_runtime =
561 NodeRuntime::new(http_client.clone(), shell_env_loaded_rx, node_settings_rx);
562
563 let mut languages = LanguageRegistry::new(cx.background_executor().clone());
564 languages.set_language_server_download_dir(paths::languages_dir().clone());
565 let languages = Arc::new(languages);
566
567 HeadlessProject::new(
568 HeadlessAppState {
569 session: session.clone(),
570 fs,
571 http_client,
572 node_runtime,
573 languages,
574 extension_host_proxy,
575 startup_time,
576 },
577 true,
578 cx,
579 )
580 });
581
582 handle_crash_files_requests(&project, &session);
583
584 cx.background_spawn(async move {
585 cleanup_old_binaries_wsl();
586 cleanup_old_binaries()
587 })
588 .detach();
589
590 mem::forget(project);
591 };
592 // We do not reuse any of the state after unwinding, so we don't run risk of observing broken invariants.
593 let app = std::panic::AssertUnwindSafe(app);
594 let run = std::panic::AssertUnwindSafe(run);
595 let res = std::panic::catch_unwind(move || { app }.0.run({ run }.0));
596 if let Err(_) = res {
597 log::error!("app panicked. quitting.");
598 Err(anyhow::anyhow!("panicked"))
599 } else {
600 log::info!("gpui app is shut down. quitting.");
601 Ok(())
602 }
603}
604
605#[derive(Debug, Error)]
606pub enum ServerPathError {
607 #[error("Failed to create server_dir `{path}`")]
608 CreateServerDir {
609 #[source]
610 source: std::io::Error,
611 path: PathBuf,
612 },
613 #[error("Failed to create logs_dir `{path}`")]
614 CreateLogsDir {
615 #[source]
616 source: std::io::Error,
617 path: PathBuf,
618 },
619}
620
621#[derive(Clone, Debug)]
622struct ServerPaths {
623 log_file: PathBuf,
624 pid_file: PathBuf,
625 stdin_socket: PathBuf,
626 stdout_socket: PathBuf,
627 stderr_socket: PathBuf,
628}
629
630impl ServerPaths {
631 fn new(identifier: &str) -> Result<Self, ServerPathError> {
632 let server_dir = paths::remote_server_state_dir().join(identifier);
633 std::fs::create_dir_all(&server_dir).map_err(|source| {
634 ServerPathError::CreateServerDir {
635 source,
636 path: server_dir.clone(),
637 }
638 })?;
639 let log_dir = logs_dir();
640 std::fs::create_dir_all(log_dir).map_err(|source| ServerPathError::CreateLogsDir {
641 source,
642 path: log_dir.clone(),
643 })?;
644
645 let pid_file = server_dir.join("server.pid");
646 let stdin_socket = server_dir.join("stdin.sock");
647 let stdout_socket = server_dir.join("stdout.sock");
648 let stderr_socket = server_dir.join("stderr.sock");
649 let log_file = logs_dir().join(format!("server-{}.log", identifier));
650
651 Ok(Self {
652 pid_file,
653 stdin_socket,
654 stdout_socket,
655 stderr_socket,
656 log_file,
657 })
658 }
659}
660
661#[derive(Debug, Error)]
662pub enum ExecuteProxyError {
663 #[error("Failed to init server paths: {0:#}")]
664 ServerPath(#[from] ServerPathError),
665
666 #[error(transparent)]
667 ServerNotRunning(#[from] ProxyLaunchError),
668
669 #[error("Failed to check PidFile '{path}': {source:#}")]
670 CheckPidFile {
671 #[source]
672 source: CheckPidError,
673 path: PathBuf,
674 },
675
676 #[error("Failed to kill existing server with pid '{pid}'")]
677 KillRunningServer { pid: u32 },
678
679 #[error("failed to spawn server")]
680 SpawnServer(#[source] SpawnServerError),
681
682 #[error("stdin_task failed: {0:#}")]
683 StdinTask(#[source] anyhow::Error),
684 #[error("stdout_task failed: {0:#}")]
685 StdoutTask(#[source] anyhow::Error),
686 #[error("stderr_task failed: {0:#}")]
687 StderrTask(#[source] anyhow::Error),
688}
689
690impl ExecuteProxyError {
691 pub fn to_exit_code(&self) -> i32 {
692 match self {
693 ExecuteProxyError::ServerNotRunning(proxy_launch_error) => {
694 proxy_launch_error.to_exit_code()
695 }
696 _ => 1,
697 }
698 }
699}
700
701pub(crate) fn execute_proxy(
702 identifier: String,
703 is_reconnecting: bool,
704) -> Result<(), ExecuteProxyError> {
705 init_logging_proxy();
706
707 let server_paths = ServerPaths::new(&identifier)?;
708
709 let id = std::process::id().to_string();
710 crashes::init(
711 crashes::InitCrashHandler {
712 session_id: id,
713 zed_version: VERSION.to_owned(),
714 binary: "zed-remote-server".to_string(),
715 release_channel: release_channel::RELEASE_CHANNEL_NAME.clone(),
716 commit_sha: option_env!("ZED_COMMIT_SHA").unwrap_or("no_sha").to_owned(),
717 },
718 |task| {
719 smol::spawn(task).detach();
720 },
721 );
722
723 log::info!("starting proxy process. PID: {}", std::process::id());
724 let server_pid = {
725 let server_pid = check_pid_file(&server_paths.pid_file).map_err(|source| {
726 ExecuteProxyError::CheckPidFile {
727 source,
728 path: server_paths.pid_file.clone(),
729 }
730 })?;
731 if is_reconnecting {
732 match server_pid {
733 None => {
734 log::error!("attempted to reconnect, but no server running");
735 return Err(ExecuteProxyError::ServerNotRunning(
736 ProxyLaunchError::ServerNotRunning,
737 ));
738 }
739 Some(server_pid) => server_pid,
740 }
741 } else {
742 if let Some(pid) = server_pid {
743 log::info!(
744 "proxy found server already running with PID {}. Killing process and cleaning up files...",
745 pid
746 );
747 kill_running_server(pid, &server_paths)?;
748 }
749 smol::block_on(spawn_server(&server_paths)).map_err(ExecuteProxyError::SpawnServer)?;
750 std::fs::read_to_string(&server_paths.pid_file)
751 .and_then(|contents| {
752 contents.parse::<u32>().map_err(|_| {
753 std::io::Error::new(
754 std::io::ErrorKind::InvalidData,
755 "Invalid PID file contents",
756 )
757 })
758 })
759 .map_err(SpawnServerError::ProcessStatus)
760 .map_err(ExecuteProxyError::SpawnServer)?
761 }
762 };
763
764 let stdin_task = smol::spawn(async move {
765 let stdin = smol::Unblock::new(std::io::stdin());
766 let stream = UnixStream::connect(&server_paths.stdin_socket)
767 .await
768 .with_context(|| {
769 format!(
770 "Failed to connect to stdin socket {}",
771 server_paths.stdin_socket.display()
772 )
773 })?;
774 handle_io(stdin, stream, "stdin").await
775 });
776
777 let stdout_task: smol::Task<Result<()>> = smol::spawn(async move {
778 let stdout = smol::Unblock::new(std::io::stdout());
779 let stream = UnixStream::connect(&server_paths.stdout_socket)
780 .await
781 .with_context(|| {
782 format!(
783 "Failed to connect to stdout socket {}",
784 server_paths.stdout_socket.display()
785 )
786 })?;
787 handle_io(stream, stdout, "stdout").await
788 });
789
790 let stderr_task: smol::Task<Result<()>> = smol::spawn(async move {
791 let mut stderr = smol::Unblock::new(std::io::stderr());
792 let mut stream = UnixStream::connect(&server_paths.stderr_socket)
793 .await
794 .with_context(|| {
795 format!(
796 "Failed to connect to stderr socket {}",
797 server_paths.stderr_socket.display()
798 )
799 })?;
800 let mut stderr_buffer = vec![0; 2048];
801 loop {
802 match stream
803 .read(&mut stderr_buffer)
804 .await
805 .context("reading stderr")?
806 {
807 0 => {
808 let error =
809 std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "stderr closed");
810 Err(anyhow!(error))?;
811 }
812 n => {
813 stderr.write_all(&stderr_buffer[..n]).await?;
814 stderr.flush().await?;
815 }
816 }
817 }
818 });
819
820 if let Err(forwarding_result) = smol::block_on(async move {
821 futures::select! {
822 result = stdin_task.fuse() => result.map_err(ExecuteProxyError::StdinTask),
823 result = stdout_task.fuse() => result.map_err(ExecuteProxyError::StdoutTask),
824 result = stderr_task.fuse() => result.map_err(ExecuteProxyError::StderrTask),
825 }
826 }) {
827 log::error!("encountered error while forwarding messages: {forwarding_result:#}",);
828 if !matches!(smol::block_on(check_server_running(server_pid)), Ok(true)) {
829 log::error!("server exited unexpectedly");
830 return Err(ExecuteProxyError::ServerNotRunning(
831 ProxyLaunchError::ServerNotRunning,
832 ));
833 }
834 return Err(forwarding_result);
835 }
836
837 Ok(())
838}
839
840fn kill_running_server(pid: u32, paths: &ServerPaths) -> Result<(), ExecuteProxyError> {
841 log::info!("killing existing server with PID {}", pid);
842 let system = sysinfo::System::new_with_specifics(
843 sysinfo::RefreshKind::nothing().with_processes(sysinfo::ProcessRefreshKind::nothing()),
844 );
845
846 if let Some(process) = system.process(sysinfo::Pid::from_u32(pid)) {
847 let killed = process.kill();
848 if !killed {
849 return Err(ExecuteProxyError::KillRunningServer { pid });
850 }
851 }
852
853 for file in [
854 &paths.pid_file,
855 &paths.stdin_socket,
856 &paths.stdout_socket,
857 &paths.stderr_socket,
858 ] {
859 log::debug!("cleaning up file {:?} before starting new server", file);
860 std::fs::remove_file(file).ok();
861 }
862
863 Ok(())
864}
865
866#[derive(Debug, Error)]
867pub enum SpawnServerError {
868 #[error("failed to remove stdin socket")]
869 RemoveStdinSocket(#[source] std::io::Error),
870
871 #[error("failed to remove stdout socket")]
872 RemoveStdoutSocket(#[source] std::io::Error),
873
874 #[error("failed to remove stderr socket")]
875 RemoveStderrSocket(#[source] std::io::Error),
876
877 #[error("failed to get current_exe")]
878 CurrentExe(#[source] std::io::Error),
879
880 #[error("failed to launch server process")]
881 ProcessStatus(#[source] std::io::Error),
882
883 #[error("failed to wait for server to be ready to accept connections")]
884 Timeout,
885}
886
887async fn spawn_server(paths: &ServerPaths) -> Result<(), SpawnServerError> {
888 log::info!("spawning server process",);
889 if paths.stdin_socket.exists() {
890 std::fs::remove_file(&paths.stdin_socket).map_err(SpawnServerError::RemoveStdinSocket)?;
891 }
892 if paths.stdout_socket.exists() {
893 std::fs::remove_file(&paths.stdout_socket).map_err(SpawnServerError::RemoveStdoutSocket)?;
894 }
895 if paths.stderr_socket.exists() {
896 std::fs::remove_file(&paths.stderr_socket).map_err(SpawnServerError::RemoveStderrSocket)?;
897 }
898
899 let binary_name = std::env::current_exe().map_err(SpawnServerError::CurrentExe)?;
900
901 #[cfg(windows)]
902 {
903 spawn_server_windows(&binary_name, paths)?;
904 }
905
906 #[cfg(not(windows))]
907 {
908 spawn_server_normal(&binary_name, paths)?;
909 }
910
911 let mut total_time_waited = std::time::Duration::from_secs(0);
912 let wait_duration = std::time::Duration::from_millis(20);
913 while !paths.stdout_socket.exists()
914 || !paths.stdin_socket.exists()
915 || !paths.stderr_socket.exists()
916 {
917 log::debug!("waiting for server to be ready to accept connections...");
918 std::thread::sleep(wait_duration);
919 total_time_waited += wait_duration;
920 if total_time_waited > std::time::Duration::from_secs(10) {
921 return Err(SpawnServerError::Timeout);
922 }
923 }
924
925 log::info!(
926 "server ready to accept connections. total time waited: {:?}",
927 total_time_waited
928 );
929
930 Ok(())
931}
932
933#[cfg(windows)]
934fn spawn_server_windows(binary_name: &Path, paths: &ServerPaths) -> Result<(), SpawnServerError> {
935 let binary_path = binary_name.to_string_lossy().to_string();
936 let parameters = format!(
937 "run --log-file \"{}\" --pid-file \"{}\" --stdin-socket \"{}\" --stdout-socket \"{}\" --stderr-socket \"{}\"",
938 paths.log_file.to_string_lossy(),
939 paths.pid_file.to_string_lossy(),
940 paths.stdin_socket.to_string_lossy(),
941 paths.stdout_socket.to_string_lossy(),
942 paths.stderr_socket.to_string_lossy()
943 );
944
945 let directory = binary_name
946 .parent()
947 .map(|p| p.to_string_lossy().to_string())
948 .unwrap_or_default();
949
950 crate::windows::shell_execute_from_explorer(&binary_path, ¶meters, &directory)
951 .map_err(|e| SpawnServerError::ProcessStatus(std::io::Error::other(e)))?;
952
953 Ok(())
954}
955
956#[cfg(not(windows))]
957fn spawn_server_normal(binary_name: &Path, paths: &ServerPaths) -> Result<(), SpawnServerError> {
958 let mut server_process = new_command(binary_name);
959 server_process
960 .stdin(util::command::Stdio::null())
961 .stdout(util::command::Stdio::null())
962 .stderr(util::command::Stdio::null())
963 .arg("run")
964 .arg("--log-file")
965 .arg(&paths.log_file)
966 .arg("--pid-file")
967 .arg(&paths.pid_file)
968 .arg("--stdin-socket")
969 .arg(&paths.stdin_socket)
970 .arg("--stdout-socket")
971 .arg(&paths.stdout_socket)
972 .arg("--stderr-socket")
973 .arg(&paths.stderr_socket);
974
975 server_process
976 .spawn()
977 .map_err(SpawnServerError::ProcessStatus)?;
978
979 Ok(())
980}
981
982#[derive(Debug, Error)]
983#[error("Failed to remove PID file for missing process (pid `{pid}`")]
984pub struct CheckPidError {
985 #[source]
986 source: std::io::Error,
987 pid: u32,
988}
989async fn check_server_running(pid: u32) -> std::io::Result<bool> {
990 new_command("kill")
991 .arg("-0")
992 .arg(pid.to_string())
993 .output()
994 .await
995 .map(|output| output.status.success())
996}
997
998fn check_pid_file(path: &Path) -> Result<Option<u32>, CheckPidError> {
999 let Some(pid) = std::fs::read_to_string(path)
1000 .ok()
1001 .and_then(|contents| contents.parse::<u32>().ok())
1002 else {
1003 return Ok(None);
1004 };
1005
1006 log::debug!("Checking if process with PID {} exists...", pid);
1007
1008 let system = sysinfo::System::new_with_specifics(
1009 sysinfo::RefreshKind::nothing().with_processes(sysinfo::ProcessRefreshKind::nothing()),
1010 );
1011
1012 if system.process(sysinfo::Pid::from_u32(pid)).is_some() {
1013 log::debug!(
1014 "Process with PID {} exists. NOT spawning new server, but attaching to existing one.",
1015 pid
1016 );
1017 Ok(Some(pid))
1018 } else {
1019 log::debug!("Found PID file, but process with that PID does not exist. Removing PID file.");
1020 std::fs::remove_file(path).map_err(|source| CheckPidError { source, pid })?;
1021 Ok(None)
1022 }
1023}
1024
1025fn write_pid_file(path: &Path, pid: u32) -> Result<()> {
1026 if path.exists() {
1027 std::fs::remove_file(path)?;
1028 }
1029 log::debug!("writing PID {} to file {:?}", pid, path);
1030 std::fs::write(path, pid.to_string()).context("Failed to write PID file")
1031}
1032
1033async fn handle_io<R, W>(mut reader: R, mut writer: W, socket_name: &str) -> Result<()>
1034where
1035 R: AsyncRead + Unpin,
1036 W: AsyncWrite + Unpin,
1037{
1038 use remote::protocol::{read_message_raw, write_size_prefixed_buffer};
1039
1040 let mut buffer = Vec::new();
1041 loop {
1042 read_message_raw(&mut reader, &mut buffer)
1043 .await
1044 .with_context(|| format!("failed to read message from {}", socket_name))?;
1045 write_size_prefixed_buffer(&mut writer, &mut buffer)
1046 .await
1047 .with_context(|| format!("failed to write message to {}", socket_name))?;
1048 writer.flush().await?;
1049 buffer.clear();
1050 }
1051}
1052
1053fn initialize_settings(
1054 session: AnyProtoClient,
1055 fs: Arc<dyn Fs>,
1056 cx: &mut App,
1057) -> watch::Receiver<Option<NodeBinaryOptions>> {
1058 let (user_settings_file_rx, watcher_task) =
1059 watch_config_file(cx.background_executor(), fs, paths::settings_file().clone());
1060
1061 handle_settings_file_changes(user_settings_file_rx, watcher_task, cx, {
1062 move |err, _cx| {
1063 if let Some(e) = err {
1064 log::info!("Server settings failed to change: {}", e);
1065
1066 session
1067 .send(proto::Toast {
1068 project_id: REMOTE_SERVER_PROJECT_ID,
1069 notification_id: "server-settings-failed".to_string(),
1070 message: format!(
1071 "Error in settings on remote host {:?}: {}",
1072 paths::settings_file(),
1073 e
1074 ),
1075 })
1076 .log_err();
1077 } else {
1078 session
1079 .send(proto::HideToast {
1080 project_id: REMOTE_SERVER_PROJECT_ID,
1081 notification_id: "server-settings-failed".to_string(),
1082 })
1083 .log_err();
1084 }
1085 }
1086 });
1087
1088 let (mut tx, rx) = watch::channel(None);
1089 let mut node_settings = None;
1090 cx.observe_global::<SettingsStore>(move |cx| {
1091 let new_node_settings = &ProjectSettings::get_global(cx).node;
1092 if Some(new_node_settings) != node_settings.as_ref() {
1093 log::info!("Got new node settings: {new_node_settings:?}");
1094 let options = NodeBinaryOptions {
1095 allow_path_lookup: !new_node_settings.ignore_system_version,
1096 // TODO: Implement this setting
1097 allow_binary_download: true,
1098 use_paths: new_node_settings.path.as_ref().map(|node_path| {
1099 let node_path = PathBuf::from(shellexpand::tilde(node_path).as_ref());
1100 let npm_path = new_node_settings
1101 .npm_path
1102 .as_ref()
1103 .map(|path| PathBuf::from(shellexpand::tilde(&path).as_ref()));
1104 (
1105 node_path.clone(),
1106 npm_path.unwrap_or_else(|| {
1107 let base_path = PathBuf::new();
1108 node_path.parent().unwrap_or(&base_path).join("npm")
1109 }),
1110 )
1111 }),
1112 };
1113 node_settings = Some(new_node_settings.clone());
1114 tx.send(Some(options)).ok();
1115 }
1116 })
1117 .detach();
1118
1119 rx
1120}
1121
1122pub fn handle_settings_file_changes(
1123 mut server_settings_file: mpsc::UnboundedReceiver<String>,
1124 watcher_task: gpui::Task<()>,
1125 cx: &mut App,
1126 settings_changed: impl Fn(Option<anyhow::Error>, &mut App) + 'static,
1127) {
1128 let server_settings_content = cx
1129 .foreground_executor()
1130 .block_on(server_settings_file.next())
1131 .unwrap();
1132 SettingsStore::update_global(cx, |store, cx| {
1133 store
1134 .set_server_settings(&server_settings_content, cx)
1135 .log_err();
1136 });
1137 cx.spawn(async move |cx| {
1138 let _watcher_task = watcher_task;
1139 while let Some(server_settings_content) = server_settings_file.next().await {
1140 cx.update_global(|store: &mut SettingsStore, cx| {
1141 let result = store.set_server_settings(&server_settings_content, cx);
1142 if let Err(err) = &result {
1143 log::error!("Failed to load server settings: {err}");
1144 }
1145 settings_changed(result.err(), cx);
1146 cx.refresh_windows();
1147 });
1148 }
1149 })
1150 .detach();
1151}
1152
1153fn read_proxy_settings(cx: &mut Context<HeadlessProject>) -> Option<Url> {
1154 let proxy_str = ProxySettings::get_global(cx).proxy.to_owned();
1155
1156 proxy_str
1157 .as_deref()
1158 .map(str::trim)
1159 .filter(|input| !input.is_empty())
1160 .and_then(|input| {
1161 input
1162 .parse::<Url>()
1163 .inspect_err(|e| log::error!("Error parsing proxy settings: {}", e))
1164 .ok()
1165 })
1166 .or_else(read_proxy_from_env)
1167}
1168
1169fn cleanup_old_binaries() -> Result<()> {
1170 let server_dir = paths::remote_server_dir_relative();
1171 let release_channel = release_channel::RELEASE_CHANNEL.dev_name();
1172 let prefix = format!("zed-remote-server-{}-", release_channel);
1173
1174 for entry in std::fs::read_dir(server_dir.as_std_path())? {
1175 let path = entry?.path();
1176
1177 if let Some(file_name) = path.file_name()
1178 && let Some(version) = file_name.to_string_lossy().strip_prefix(&prefix)
1179 && !is_new_version(version)
1180 && !is_file_in_use(file_name)
1181 {
1182 log::info!("removing old remote server binary: {:?}", path);
1183 std::fs::remove_file(&path)?;
1184 }
1185 }
1186
1187 Ok(())
1188}
1189
1190// Remove this once 223 goes stable, we only have this to clean up old binaries on WSL
1191// we no longer download them into this folder, we use the same folder as other remote servers
1192fn cleanup_old_binaries_wsl() {
1193 let server_dir = paths::remote_wsl_server_dir_relative();
1194 if let Ok(()) = std::fs::remove_dir_all(server_dir.as_std_path()) {
1195 log::info!("removing old wsl remote server folder: {:?}", server_dir);
1196 }
1197}
1198
1199fn is_new_version(version: &str) -> bool {
1200 semver::Version::from_str(version)
1201 .ok()
1202 .zip(semver::Version::from_str(env!("ZED_PKG_VERSION")).ok())
1203 .is_some_and(|(version, current_version)| version >= current_version)
1204}
1205
1206fn is_file_in_use(file_name: &OsStr) -> bool {
1207 let info = sysinfo::System::new_with_specifics(sysinfo::RefreshKind::nothing().with_processes(
1208 sysinfo::ProcessRefreshKind::nothing().with_exe(sysinfo::UpdateKind::Always),
1209 ));
1210
1211 for process in info.processes().values() {
1212 if process
1213 .exe()
1214 .is_some_and(|exe| exe.file_name().is_some_and(|name| name == file_name))
1215 {
1216 return true;
1217 }
1218 }
1219
1220 false
1221}