-
Notifications
You must be signed in to change notification settings - Fork 37
/
main.rs
376 lines (339 loc) · 11.3 KB
/
main.rs
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
extern crate dotenv;
use crate::events::CoreEvent;
use advisory_lock::{AdvisoryFileLock, FileLockMode};
use libcrio::Cli;
use log::{debug, error, info};
use serde_json::json;
use serde_json::Value;
use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::process;
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
use zip::write::FileOptions;
use zip::ZipWriter;
mod config;
mod events;
mod logging;
fn main() -> Result<(), anyhow::Error> {
let (send, recv) = channel();
let cc = config::CoreConfig::new()?;
let recv_time: u64 = cc.timeout as u64;
thread::spawn(move || {
let result = handle(cc);
send.send(result).unwrap();
});
let result = recv.recv_timeout(Duration::from_secs(recv_time));
match result {
Ok(inner_result) => inner_result,
Err(_error) => {
error!("Timeout error during coredump processing.");
process::exit(32);
}
}
}
fn handle(mut cc: config::CoreConfig) -> Result<(), anyhow::Error> {
cc.set_namespace("default".to_string());
let l_log_level = cc.log_level.clone();
let log_path = logging::init_logger(l_log_level)?;
debug!("Arguments: {:?}", env::args());
info!(
"Environment config:\n IGNORE_CRIO={}\nCRIO_IMAGE_CMD={}\nUSE_CRIO_CONF={}",
cc.ignore_crio, cc.image_command, cc.use_crio_config
);
info!("Set logfile to: {:?}", &log_path);
debug!("Creating dump for {}", cc.get_templated_name());
let l_crictl_config_path = cc.crictl_config_path.clone();
let config_path = if cc.use_crio_config {
Some(
l_crictl_config_path
.into_os_string()
.to_string_lossy()
.to_string(),
)
} else {
None
};
let l_bin_path = cc.bin_path.clone();
let l_image_command = cc.image_command.clone();
let cli = Cli {
bin_path: l_bin_path,
config_path,
image_command: l_image_command,
};
let pod_object = match cli.pod(&cc.params.hostname) {
Ok(v) => v,
Err(e) => {
error!("{}", e);
// We fall through here as the coredump and info can still be captured.
json!({})
}
};
// match the label filter if there's one, and skip the whole process if it doesn't match
if !cc.pod_selector_label.is_empty() {
debug!(
"Pod selector specified. Will record only if pod has label {}",
&cc.pod_selector_label
);
let pod_labels = pod_object["labels"].as_object().unwrap();
// check if pod_labels has pod_selector_label
if pod_labels.get(&cc.pod_selector_label).is_none() {
info!(
"Skipping pod as it did not match selector label {}",
&cc.pod_selector_label
);
process::exit(0);
}
} else {
debug!("No pod selector specified, selecting all pods");
}
let namespace = pod_object["metadata"]["namespace"]
.as_str()
.unwrap_or("unknown");
cc.set_namespace(namespace.to_string());
let podname = pod_object["metadata"]["name"].as_str().unwrap_or("unknown");
cc.set_podname(podname.to_string());
// Create the base zip file that we are going to put everything into
let compression_method = if cc.compression {
zip::CompressionMethod::Deflated
} else {
zip::CompressionMethod::Stored
};
let options = FileOptions::default()
.compression_method(compression_method)
.unix_permissions(0o444)
.large_file(true);
let file = match File::create(cc.get_zip_full_path()) {
Ok(v) => v,
Err(e) => {
error!("Failed to create file: {}", e);
process::exit(1);
}
};
file.lock(FileLockMode::Exclusive)?;
let mut zip = ZipWriter::new(&file);
debug!(
"Create a JSON file to store the dump meta data\n{}",
cc.get_dump_info_filename()
);
match zip.start_file(cc.get_dump_info_filename(), options) {
Ok(v) => v,
Err(e) => {
error!("Error starting dump file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
match zip.write_all(cc.get_dump_info().as_bytes()) {
Ok(v) => v,
Err(e) => {
error!("Error writing pod file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
// Pipe the core file to zip
match zip.start_file(cc.get_core_filename(), options) {
Ok(v) => v,
Err(e) => error!("Error starting core file \n{}", e),
};
let stdin = io::stdin();
let mut stdin = stdin.lock();
match io::copy(&mut stdin, &mut zip) {
Ok(v) => v,
Err(e) => {
error!("Error writing core file \n{}", e);
process::exit(1);
}
};
zip.flush()?;
if cc.ignore_crio {
if cc.core_events {
let zip_name = format!("{}.zip", cc.get_templated_name());
let evtdir = format!("{}", cc.event_location.display());
let evt = CoreEvent::new_no_crio(cc.params, zip_name);
evt.write_event(&evtdir)?;
}
zip.finish()?;
file.unlock()?;
process::exit(0);
}
debug!("Using runtime_file_name:{}", cc.get_pod_filename());
match zip.start_file(cc.get_pod_filename(), options) {
Ok(v) => v,
Err(e) => {
error!("Error starting pod file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
match zip.write_all(pod_object.to_string().as_bytes()) {
Ok(v) => v,
Err(e) => {
error!("Error writing pod file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
// TODO: Check logging of more than one pod retured
let pod_id = match pod_object["id"].as_str() {
Some(v) => v,
None => {
error!("Failed to get pod id");
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
// With the pod_id get the runtime information from crictl
debug!("Getting inspectp output using pod_id:{}", pod_id);
let inspectp = match cli.inspect_pod(pod_id) {
Ok(v) => v,
Err(e) => {
error!("Failed to inspect pod {}", e);
json!({})
}
};
debug!("Starting inspectp file\n{}", cc.get_inspect_pod_filename());
match zip.start_file(cc.get_inspect_pod_filename(), options) {
Ok(v) => v,
Err(e) => {
error!("Error starting inspect pod file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!("Writing inspectp file\n{}", cc.get_inspect_pod_filename());
match zip.write_all(inspectp.to_string().as_bytes()) {
Ok(v) => v,
Err(e) => {
error!("Error writing inspect pod file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
// Get the container_image_name based on the pod_id
let ps_object = match cli.pod_containers(pod_id) {
Ok(v) => v,
Err(e) => {
error!("{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!("Starting ps file \n{}", cc.get_ps_filename());
match zip.start_file(cc.get_ps_filename(), options) {
Ok(v) => v,
Err(e) => {
error!("Error starting ps file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!("Writing ps file \n{}", cc.get_ps_filename());
match zip.write_all(ps_object.to_string().as_bytes()) {
Ok(v) => v,
Err(e) => {
error!("Error writing ps file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!("Successfully got the process details {}", ps_object);
let mut images: Vec<Value> = vec![];
if let Some(containers) = ps_object["containers"].as_array() {
for (counter, container) in containers.iter().enumerate() {
let img_ref = match container["imageRef"].as_str() {
Some(v) => v,
None => {
error!("Failed to get containerid {}", "");
break;
}
};
let log =
match cli.tail_logs(container["id"].as_str().unwrap_or_default(), cc.log_length) {
Ok(v) => v,
Err(e) => {
error!("Error finding logs:\n{}", e);
"".to_string()
}
};
debug!("Starting log file \n{}", cc.get_log_filename(counter));
match zip.start_file(cc.get_log_filename(counter), options) {
Ok(v) => v,
Err(e) => {
error!("Error starting log file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!("Writing file output \n{}", log);
// TODO: Should this be streamed?
match zip.write_all(log.to_string().as_bytes()) {
Ok(v) => v,
Err(e) => {
error!("Error writing log file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!("found img_id {}", img_ref);
let image = match cli.image(img_ref) {
Ok(v) => v,
Err(e) => {
error!("Error finding image:\n{}", e);
json!({})
}
};
let img_clone = image.clone();
images.push(img_clone);
debug!("Starting image file \n{}", cc.get_image_filename(counter));
match zip.start_file(cc.get_image_filename(counter), options) {
Ok(v) => v,
Err(e) => {
error!("Error starting ps file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!("Writing image file \n{}", cc.get_image_filename(counter));
match zip.write_all(image.to_string().as_bytes()) {
Ok(v) => v,
Err(e) => {
error!("Error writing ps file in zip \n{}", e);
zip.finish()?;
file.unlock()?;
process::exit(1);
}
};
debug!(
"Getting logs for container id {}",
container["id"].as_str().unwrap_or_default()
);
}
};
zip.finish()?;
file.unlock()?;
if cc.core_events {
let zip_name = format!("{}.zip", cc.get_templated_name());
let evtdir = format!("{}", cc.event_location.display());
let evt = CoreEvent::new(cc.params, zip_name, pod_object, images);
evt.write_event(&evtdir)?;
}
Ok(())
}