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
use crate::DebugConfig;
use cyfs_base::*;
use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
#[derive(Clone)]
pub struct ProcessDeadHelper {
interval_in_secs: u64,
task_system_last_active: Arc<AtomicU64>,
exit_on_task_system_dead: Arc<AtomicU64>,
exit_on_dead: bool,
}
impl ProcessDeadHelper {
fn new(interval_in_secs: u64) -> Self {
let exit_on_dead = match get_channel() {
CyfsChannel::Nightly => false,
_ => true,
};
let mut ret = Self {
interval_in_secs,
task_system_last_active: Arc::new(AtomicU64::new(bucky_time_now())),
exit_on_task_system_dead: Arc::new(AtomicU64::new(0)),
exit_on_dead,
};
ret.load_config();
ret
}
fn load_config(&mut self) {
if let Some(config_node) = DebugConfig::get_config("check") {
if let Err(e) = self.load_config_value(config_node) {
println!("load process dead check config error! {}", e);
}
}
}
fn load_config_value(&mut self, config_node: &toml::Value) -> BuckyResult<()> {
let node = config_node.as_table().ok_or_else(|| {
let msg = format!("invalid debug config format! content={}", config_node,);
error!("{}", msg);
BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
})?;
for (k, v) in node {
match k.as_str() {
"exit_on_dead" => {
if let Some(v) = v.as_bool() {
println!("load check.exit_on_dead from config: {}, current={}", v, self.exit_on_dead);
self.exit_on_dead = v;
} else {
println!("unknown exit_on_dead config node: {:?}", v);
}
}
key @ _ => {
println!("unknown check config node: {}={:?}", key, v);
}
}
}
Ok(())
}
pub fn patch_task_min_thread() {
let cpu_nums = num_cpus::get();
if cpu_nums <= 1 {
const KEY: &str = "ASYNC_STD_THREAD_COUNT";
if std::env::var(KEY).is_err() {
std::env::set_var(KEY, "2");
}
}
}
pub fn instance() -> &'static Self {
static INSTANCE: OnceCell<ProcessDeadHelper> = OnceCell::new();
INSTANCE.get_or_init(|| Self::new(60))
}
pub fn start_check(&self) {
static INIT_DONE: AtomicBool = AtomicBool::new(false);
if !INIT_DONE.swap(true, Ordering::SeqCst) {
self.start_check_process();
self.start_check_task_system();
}
}
pub fn enable_exit_on_task_system_dead(&self, timeout_in_secs: Option<u64>) {
let v = timeout_in_secs.unwrap_or(60 * 5) * 1000 * 1000;
self.exit_on_task_system_dead.store(v, Ordering::SeqCst);
if v > 0 {
info!("enable exit on task system dead: timeout={}", v);
self.start_check();
} else {
info!("disable exit on task system dead");
}
}
fn update_task_alive(&self) {
let now = bucky_time_now();
self.task_system_last_active.store(now, Ordering::SeqCst);
}
fn check_task_alive(&self) {
let exit_timeout = self.exit_on_task_system_dead.load(Ordering::SeqCst);
if exit_timeout == 0 || !self.exit_on_dead {
return;
}
let now = bucky_time_now();
let last_active = self.task_system_last_active.load(Ordering::SeqCst);
if now >= last_active && now - last_active >= exit_timeout {
error!(
"task system dead timeout, now will exit process! last_active={}, exit_timeout={}s",
last_active,
exit_timeout / (1000 * 1000)
);
println!("process will exit on task system dead...");
let ins = crate::dump::DumpHelper::get_instance();
if ins.is_enable_dump() {
ins.dump();
}
std::thread::sleep(std::time::Duration::from_secs(5));
std::process::exit(-1);
}
}
fn start_check_process(&self) {
let dur = std::time::Duration::from_secs(self.interval_in_secs);
let this = self.clone();
std::thread::spawn(move || loop {
std::thread::sleep(dur);
info!("process still alive {:?}, {}", std::thread::current().id(), cyfs_base::get_version());
this.check_task_alive();
});
}
fn start_check_task_system(&self) {
let dur = std::time::Duration::from_secs(self.interval_in_secs);
let this = self.clone();
async_std::task::spawn(async move {
loop {
this.update_task_alive();
async_std::task::sleep(dur).await;
info!(
"process task system still alive {:?}",
std::thread::current().id(),
);
}
});
}
}
#[cfg(test)]
mod tests {
use cyfs_base::bucky_time_to_system_time;
use super::ProcessDeadHelper;
use std::sync::RwLock;
struct Test {
v: Option<u32>,
}
impl Test {
fn new() -> Self {
Self { v: None }
}
fn get(&self) -> Option<&u32> {
self.v.as_ref()
}
fn set(&mut self, v: u32) {
self.v = Some(v);
}
}
async fn dead_lock() {
let r: RwLock<Test> = RwLock::new(Test::new());
if let Some(v) = r.read().unwrap().get().cloned() {
println!("v={}", v);
} else {
println!("enter else");
r.write().unwrap().set(1);
println!("v={}", 1);
};
}
#[test]
fn test_time() {
let t = 13316567010962630;
let s = bucky_time_to_system_time(t);
println!("{:#?}", s);
let datetime = chrono::offset::Local::now();
println!("{:?}", datetime);
let datetime: chrono::DateTime<chrono::Local> = s.into();
let time_str = datetime.format("%Y-%m-%d %H:%M:%S%.3f %:z");
println!("{}", time_str);
}
#[test]
fn test_dead_lock() {
ProcessDeadHelper::instance().start_check();
ProcessDeadHelper::instance().enable_exit_on_task_system_dead(Some(1000 * 1000 * 2));
async_std::task::block_on(dead_lock());
}
#[test]
fn test_safe_lock() {
let r: RwLock<Test> = RwLock::new(Test::new());
let v = r.read().unwrap().get().cloned();
if let Some(v) = v {
println!("v={}", v);
} else {
println!("enter else");
r.write().unwrap().set(1);
println!("v={}", 1);
};
}
}