-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathclient.rs
More file actions
297 lines (276 loc) · 10.4 KB
/
Copy pathclient.rs
File metadata and controls
297 lines (276 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use crate::daemon::{Daemon, RunOptions};
use crate::error::IpcError;
use crate::ipc::{IpcRequest, IpcResponse, deserialize, fs_name, serialize};
use crate::{Result, supervisor};
use exponential_backoff::Backoff;
use interprocess::local_socket::tokio::{RecvHalf, SendHalf};
use interprocess::local_socket::traits::tokio::Stream;
use miette::Context;
use std::path::PathBuf;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::Mutex;
use uuid::Uuid;
pub struct IpcClient {
_id: String,
recv: Mutex<BufReader<RecvHalf>>,
send: Mutex<SendHalf>,
}
const CONNECT_ATTEMPTS: u32 = 5;
const CONNECT_MIN_DELAY: Duration = Duration::from_millis(100);
const CONNECT_MAX_DELAY: Duration = Duration::from_secs(1);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
impl IpcClient {
pub async fn connect(autostart: bool) -> Result<Self> {
if autostart {
supervisor::start_if_not_running()?;
}
let id = Uuid::new_v4().to_string();
let client = Self::connect_(&id, "main").await?;
trace!("Connected to IPC socket");
let rsp = client.request(IpcRequest::Connect).await?;
if !rsp.is_ok() {
return Err(IpcError::UnexpectedResponse {
expected: "Ok".to_string(),
actual: format!("{:?}", rsp),
}
.into());
}
debug!("Connected to IPC main");
Ok(client)
}
async fn connect_(id: &str, name: &str) -> Result<Self> {
for duration in Backoff::new(CONNECT_ATTEMPTS, CONNECT_MIN_DELAY, CONNECT_MAX_DELAY) {
match interprocess::local_socket::tokio::Stream::connect(fs_name(name)?).await {
Ok(conn) => {
let (recv, send) = conn.split();
let recv = BufReader::new(recv);
return Ok(Self {
_id: id.to_string(),
recv: Mutex::new(recv),
send: Mutex::new(send),
});
}
Err(err) => {
if let Some(duration) = duration {
debug!(
"Failed to connect to IPC socket: {:?}, retrying in {:?}",
err, duration
);
tokio::time::sleep(duration).await;
continue;
} else {
return Err(IpcError::ConnectionFailed {
attempts: CONNECT_ATTEMPTS,
details: Some(format!(
"{err}\nensure the supervisor is running with: pitchfork supervisor start"
)),
}
.into());
}
}
}
}
Err(IpcError::ConnectionFailed {
attempts: CONNECT_ATTEMPTS,
details: Some(
"ensure the supervisor is running with: pitchfork supervisor start".to_string(),
),
}
.into())
}
pub async fn send(&self, msg: IpcRequest) -> Result<()> {
let mut msg = serialize(&msg)?;
if msg.contains(&0) {
return Err(IpcError::InvalidMessage {
details: Some("message contains null byte".to_string()),
}
.into());
}
msg.push(0);
let mut send = self.send.lock().await;
send.write_all(&msg)
.await
.map_err(|e| IpcError::SendFailed {
details: Some(e.to_string()),
})?;
Ok(())
}
async fn read(&self, timeout: Duration) -> Result<IpcResponse> {
let mut recv = self.recv.lock().await;
let mut bytes = Vec::new();
match tokio::time::timeout(timeout, recv.read_until(0, &mut bytes)).await {
Ok(Ok(_)) => {}
Ok(Err(err)) => {
return Err(IpcError::ReadFailed {
details: Some(err.to_string()),
}
.into());
}
Err(_) => {
return Err(IpcError::Timeout {
seconds: timeout.as_secs(),
}
.into());
}
}
if bytes.is_empty() {
return Err(IpcError::ConnectionClosed.into());
}
deserialize(&bytes).wrap_err("failed to deserialize IPC response")
}
async fn request(&self, msg: IpcRequest) -> Result<IpcResponse> {
self.request_with_timeout(msg, REQUEST_TIMEOUT).await
}
fn unexpected_response(expected: &str, actual: &IpcResponse) -> IpcError {
IpcError::UnexpectedResponse {
expected: expected.to_string(),
actual: format!("{:?}", actual),
}
}
async fn request_with_timeout(
&self,
msg: IpcRequest,
timeout: Duration,
) -> Result<IpcResponse> {
self.send(msg).await?;
self.read(timeout).await
}
pub async fn enable(&self, id: String) -> Result<bool> {
let rsp = self.request(IpcRequest::Enable { id: id.clone() }).await?;
match rsp {
IpcResponse::Yes => {
info!("enabled daemon {}", id);
Ok(true)
}
IpcResponse::No => {
info!("daemon {} already enabled", id);
Ok(false)
}
rsp => Err(Self::unexpected_response("Yes or No", &rsp).into()),
}
}
pub async fn disable(&self, id: String) -> Result<bool> {
let rsp = self.request(IpcRequest::Disable { id: id.clone() }).await?;
match rsp {
IpcResponse::Yes => {
info!("disabled daemon {}", id);
Ok(true)
}
IpcResponse::No => {
info!("daemon {} already disabled", id);
Ok(false)
}
rsp => Err(Self::unexpected_response("Yes or No", &rsp).into()),
}
}
pub async fn run(&self, opts: RunOptions) -> Result<(Vec<String>, Option<i32>)> {
info!("starting daemon {}", opts.id);
let start_time = chrono::Local::now();
// Use longer timeout for daemon start - ready_delay can be up to 60s+
let timeout = Duration::from_secs(opts.ready_delay.unwrap_or(3) + 60);
let rsp = self
.request_with_timeout(IpcRequest::Run(opts.clone()), timeout)
.await?;
let mut started_daemons = vec![];
let mut exit_code = None;
match rsp {
IpcResponse::DaemonStart { daemon } => {
started_daemons.push(daemon.id.clone());
info!("started {}", daemon.id);
}
IpcResponse::DaemonReady { daemon } => {
started_daemons.push(daemon.id.clone());
info!("started {}", daemon.id);
}
IpcResponse::DaemonFailedWithCode { exit_code: code } => {
let code = code.unwrap_or(1);
exit_code = Some(code);
error!("daemon {} failed with exit code {}", opts.id, code);
// Print logs from the time we started this specific daemon
if let Err(e) =
crate::cli::logs::print_logs_for_time_range(&opts.id, start_time, None)
{
error!("Failed to print logs: {}", e);
}
}
IpcResponse::DaemonAlreadyRunning => {
warn!("daemon {} already running", opts.id);
}
IpcResponse::DaemonFailed { error } => {
error!("Failed to start daemon {}: {}", opts.id, error);
exit_code = Some(1);
// Print logs from the time we started this specific daemon
if let Err(e) =
crate::cli::logs::print_logs_for_time_range(&opts.id, start_time, None)
{
error!("Failed to print logs: {}", e);
}
}
rsp => {
return Err(Self::unexpected_response("DaemonStart or DaemonReady", &rsp).into());
}
}
Ok((started_daemons, exit_code))
}
pub async fn active_daemons(&self) -> Result<Vec<Daemon>> {
let rsp = self.request(IpcRequest::GetActiveDaemons).await?;
match rsp {
IpcResponse::ActiveDaemons(daemons) => Ok(daemons),
rsp => Err(Self::unexpected_response("ActiveDaemons", &rsp).into()),
}
}
pub async fn update_shell_dir(&self, shell_pid: u32, dir: PathBuf) -> Result<()> {
let rsp = self
.request(IpcRequest::UpdateShellDir {
shell_pid,
dir: dir.clone(),
})
.await?;
match rsp {
IpcResponse::Ok => {
trace!("updated shell dir for pid {shell_pid} to {}", dir.display());
}
rsp => return Err(Self::unexpected_response("Ok", &rsp).into()),
}
Ok(())
}
pub async fn clean(&self) -> Result<()> {
let rsp = self.request(IpcRequest::Clean).await?;
match rsp {
IpcResponse::Ok => {
trace!("cleaned");
}
rsp => return Err(Self::unexpected_response("Ok", &rsp).into()),
}
Ok(())
}
pub async fn get_disabled_daemons(&self) -> Result<Vec<String>> {
let rsp = self.request(IpcRequest::GetDisabledDaemons).await?;
match rsp {
IpcResponse::DisabledDaemons(daemons) => Ok(daemons),
rsp => Err(Self::unexpected_response("DisabledDaemons", &rsp).into()),
}
}
pub async fn get_notifications(&self) -> Result<Vec<(log::LevelFilter, String)>> {
let rsp = self.request(IpcRequest::GetNotifications).await?;
match rsp {
IpcResponse::Notifications(notifications) => Ok(notifications),
rsp => Err(Self::unexpected_response("Notifications", &rsp).into()),
}
}
pub async fn stop(&self, id: String) -> Result<()> {
let rsp = self.request(IpcRequest::Stop { id: id.clone() }).await?;
match rsp {
IpcResponse::Ok => {
info!("stopped daemon {}", id);
Ok(())
}
IpcResponse::DaemonAlreadyStopped => {
warn!("daemon {} is not running", id);
Ok(())
}
rsp => Err(Self::unexpected_response("Ok or DaemonAlreadyStopped", &rsp).into()),
}
}
}