-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathprocess.rs
More file actions
274 lines (251 loc) · 9.16 KB
/
Copy pathprocess.rs
File metadata and controls
274 lines (251 loc) · 9.16 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
// process function just run in unique process
use std::{
sync::Arc,
};
use async_trait::async_trait;
use enum_as_inner::EnumAsInner;
use parking_lot::RwLock;
use tokio::{process::Command, sync::oneshot};
use crate::{
general::{
m_appmeta_manager::{AppType},
network::rpc_model::{self, HashValue},
},
worker::func::{shared::java, InstanceTrait},
};
use super::process_rpc::{self, proc_proto};
#[derive(EnumAsInner)]
pub enum ProcessInstanceConnState {
Connecting(Vec<oneshot::Sender<proc_proto::AppStarted>>),
Connected(proc_proto::AppStarted),
}
pub type PID = u32;
pub struct ProcessInstanceStateInner(
ProcessInstanceConnState,
Option<(tokio::process::Child, Option<PID>)>,
);
impl Drop for ProcessInstanceStateInner {
fn drop(&mut self) {
assert!(self.1.is_none());
}
}
#[derive(Clone)]
pub struct ProcessInstanceState(Arc<RwLock<ProcessInstanceStateInner>>);
#[derive(Clone)]
pub struct ProcessInstance {
/// handle to socket
app: String,
/// for take snapshot
pub app_type: AppType,
state: ProcessInstanceState,
}
// impl Drop for ProcessInstance {
// fn drop(&mut self) {
// // must be killed before drop
// assert!(self.state.0.read().1.is_none());
// }
// }
impl ProcessInstance {
// pub fn raw_pid(&self) -> Option<PID> {
// self.state.0.read().1.as_ref().map(|v| v.0.id().unwrap())
// }
// pub fn checked_pid(&self) -> Option<PID> {
// self.state.0.read().1.as_ref().map(|v| v.1)
// }
pub async fn kill(&self) {
let takeprocess = self.state.0.write().1.take();
if let Some((mut p, id)) = takeprocess {
let pid = p.id().unwrap();
tracing::debug!("killing app {} on pid raw:{} check:{:?}", self.app, pid, id);
// let pid = p.id().unwrap();
p.kill().await;
// cmd kill id
if let Some(id) = id {
let _ = Command::new("kill")
.arg("-9")
.arg(id.to_string())
.status()
.await;
} else {
// use jcmd to find and kill
if self.app_type == AppType::Jar {
if let Ok(pid) = java::find_pid(&self.app).await {
let _ = Command::new("kill")
.arg("-9")
.arg(pid.to_string())
.status()
.await;
}
}
}
// clean the conn_map in rpc_model
tracing::debug!("close conn for p: {}", self.app);
rpc_model::close_conn(&HashValue::Str(self.app.clone()));
// let _ = Command::new("kill")
// .arg("-9") // Use signal 9 (SIGKILL) for forceful termination
// .arg(pid.to_string())
// .stdout(Stdio::piped())
// .stderr(Stdio::piped())
// .output()
// .await
// .expect("Failed to execute kill command");
// tracing::debug!(
// "check port {:?}",
// Command::new("lsof")
// .arg("-:i8080") // Use signal 9 (SIGKILL) for forceful termination
// .stdout(Stdio::piped())
// .stderr(Stdio::piped())
// .output()
// .await
// .expect("Failed to execute kill command")
// );
}
}
pub fn new(app: String, app_type: AppType) -> Self {
Self {
app_type,
app,
state: ProcessInstanceState(Arc::new(RwLock::new(ProcessInstanceStateInner(
ProcessInstanceConnState::Connecting(Vec::new()),
None,
)))),
}
}
pub fn bind_process(&self, child: tokio::process::Child) {
let mut state_w = self.state.0.write();
state_w.1 = Some((child, None));
}
pub fn bind_checked_pid(&self, pid: PID) {
let mut state_w = self.state.0.write();
let _ = state_w.1.as_mut().map(|v| v.1 = Some(pid));
}
pub fn set_verifyed(&self, verify_msg: proc_proto::AppStarted) -> bool {
let mut state_w = self.state.0.write();
state_w.1.as_mut().unwrap().1 = Some(verify_msg.pid);
let state_w = &mut state_w.0;
let Some(waiters) = state_w.as_connecting_mut() else {
tracing::warn!("verify received when already verified");
return false;
};
while let Some(w) = waiters.pop() {
let _ = w.send(verify_msg.clone()).unwrap();
}
*state_w = ProcessInstanceConnState::Connected(verify_msg);
true
}
// KV DEBUG
pub async fn wait_for_verify(&self) -> proc_proto::AppStarted {
if let Some(v) = self.state.0.read().0.as_connected() {
return v.clone();
}
let waiter = {
let mut state_wr = self.state.0.write();
match &mut state_wr.0 {
ProcessInstanceConnState::Connected(verify_msg) => {
tracing::debug!("connected, don't need wait");
return verify_msg.clone();
}
ProcessInstanceConnState::Connecting(waiters) => {
let (tx, rx) = oneshot::channel();
waiters.push(tx);
rx
}
}
};
tracing::debug!("connecting, wait for verify");
waiter.await.expect(
"tx lives in ProcessInstanceStateInner::Connecting and
destroyed when { notify all the waiters then transfer to Connected }
so it's impossible to drop the tx before the rx",
)
// let (tx, rx) = oneshot::channel();
// let mut wating_verify = WATING_VERIFY.lock();
// let wating = wating_verify.entry(self.app.clone()).or_insert_with(Vec::new);
// wating.push(tx);
// drop(wating_verify);
// let _ = rx.await;
}
pub fn before_checkpoint(&self) {
// state to starting
let mut state = self.state.0.write();
match &state.0 {
ProcessInstanceConnState::Connected(_) => {
//just trans to connecting
}
ProcessInstanceConnState::Connecting(_) => {
// verify not received yet
// imposible, verify msg is the first analyzed,
// this function can only be called when function require for update check
unreachable!("update_checkpoint before verify")
}
}
state.0 = ProcessInstanceConnState::Connecting(Vec::new());
}
}
#[async_trait]
impl InstanceTrait for ProcessInstance {
fn instance_name(&self) -> String {
self.app.clone()
}
async fn execute(
&self,
fn_ctx: &mut crate::worker::func::FnExeCtx,
) -> crate::result::WSResult<Option<String>> {
// if rpc_model::start_remote_once(rpc_model::HashValue::Str(fn_ctx.func.to_owned())) {
// // cold start the java process
// }
// if fn_ctx.func_meta.allow_rpc_call()
{
let _ = self.wait_for_verify().await;
return process_rpc::call_func(&fn_ctx.app, &fn_ctx.func, fn_ctx.http_str_unwrap())
.await
.map(|v| Some(v.ret_str));
}
// if let Some(httpmethod) = fn_ctx.func_meta.allow_http_call() {
// let fnverify = self.wait_for_verify().await;
// let Some(http_port) = &fnverify.http_port else {
// return Err(WsFuncError::FuncBackendHttpNotSupported {
// fname: fn_ctx.func.to_owned(),
// }
// .into());
// };
// let http_url = format!("http://127.0.0.1:{}/{}", http_port, fn_ctx.func);
// let res = match httpmethod {
// HttpMethod::Get => reqwest::get(http_url).await,
// HttpMethod::Post => {
// reqwest::Client::new()
// .post(http_url)
// .body(fn_ctx.http_str_unwrap())
// .send()
// .await
// }
// };
// let ok = match res {
// Err(e) => {
// return Err(WsFuncError::FuncHttpFail {
// app: fn_ctx.app.clone(),
// func: fn_ctx.func.clone(),
// http_err: e,
// }
// .into());
// }
// Ok(ok) => ok,
// };
// return ok
// .text()
// .await
// .map_err(|e| {
// WsFuncError::FuncHttpFail {
// app: fn_ctx.app.clone(),
// func: fn_ctx.func.clone(),
// http_err: e,
// }
// .into()
// })
// .map(|ok| Some(ok));
// }
// unreachable!("Missing call description in func meta");
}
}
// pub struct InstanceManagerProcessState {
// }