Skip to content

Commit cea1610

Browse files
committed
improve: improve memory efficiency of flow capture
1 parent 8769cbe commit cea1610

File tree

1 file changed

+17
-33
lines changed

1 file changed

+17
-33
lines changed

src/net/online_fluereflow.rs

Lines changed: 17 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use std::{
66
collections::HashMap,
77
fs,
8+
mem::take,
89
time::{Duration, Instant},
910
};
1011

@@ -29,9 +30,8 @@ use fluere_config::Config;
2930
use fluere_plugin::PluginManager;
3031
use fluereflow::FluereRecord;
3132

32-
use tokio::task;
33-
3433
use log::{debug, info, trace};
34+
use tokio::task;
3535

3636
// This function captures packets from a network interface and converts them into NetFlow data.
3737
// It takes the command line arguments as input, which specify the network interface to capture from and other parameters.
@@ -53,17 +53,13 @@ pub async fn packet_capture(arg: Args) -> Result<(), FluereError> {
5353
.await
5454
.expect("Failed to load plugins");
5555

56-
let interface = find_device(interface_name.as_str())?;
56+
let interface = find_device(&interface_name)?;
5757
let mut cap_device = CaptureDevice::new(interface.clone()).map_err(NetError::from)?;
5858
let cap = &mut cap_device.capture;
5959

6060
let file_dir = "./output";
61-
match fs::create_dir_all(<&str>::clone(&file_dir)) {
62-
Ok(_) => {
63-
trace!("Created directory: {}", file_dir)
64-
}
65-
Err(error) => panic!("Problem creating directory: {:?}", error),
66-
};
61+
fs::create_dir_all(file_dir)
62+
.unwrap_or_else(|error| panic!("Problem creating directory: {:?}", error));
6763

6864
let start = Instant::now();
6965
let mut last_export = Instant::now();
@@ -78,16 +74,12 @@ pub async fn packet_capture(arg: Args) -> Result<(), FluereError> {
7874
let mut active_flow: HashMap<Key, FluereRecord> = HashMap::new();
7975
let mut tasks = vec![];
8076
let mut export_tasks = vec![];
81-
// let mut packet_count = 0;
82-
// let export_rt =
77+
8378
loop {
8479
match cap.next_packet() {
85-
Err(_) => {
86-
continue;
87-
}
80+
Err(_) => continue,
8881
Ok(packet) => {
8982
trace!("received packet");
90-
// trace!("packet: {:?}", );
9183

9284
let (mut key_value, mut reverse_key) = match parse_keys(packet.clone()) {
9385
Ok(keys) => keys,
@@ -149,14 +141,14 @@ pub async fn packet_capture(arg: Args) -> Result<(), FluereError> {
149141
packet.header.ts.tv_sec as u64,
150142
packet.header.ts.tv_usec as u64,
151143
);
152-
//println!("time: {:?}", time);
153144
let pkt = flowdata.min_pkt;
154145
let ttl = flowdata.min_ttl;
155146
// trace!(
156147
// "current inputed flow{:?}",
157148
// active_flow.get(&key_value).unwrap()
158149
// );
159150
let flow_key = if is_reverse { &reverse_key } else { &key_value };
151+
160152
if let Some(flow) = active_flow.get_mut(flow_key) {
161153
let update_key = UDFlowKey {
162154
doctets,
@@ -190,7 +182,7 @@ pub async fn packet_capture(arg: Args) -> Result<(), FluereError> {
190182
if last_export.elapsed() >= Duration::from_millis(interval) && interval != 0 {
191183
let mut expired_flows = vec![];
192184
let mut expired_flow_data = vec![];
193-
// packet_count = 0;
185+
194186
debug!("Calculating timeout start");
195187
for (key, flow) in active_flow.iter() {
196188
if flow_timeout > 0 && flow.last < (time - (flow_timeout * 1000)) {
@@ -204,19 +196,14 @@ pub async fn packet_capture(arg: Args) -> Result<(), FluereError> {
204196
}
205197
}
206198

207-
// Send the expired flows to the plugins
208199
debug!(
209200
"Sending {} expired flows to plugins start",
210201
expired_flows.len()
211202
);
212-
213-
let cloned_plugin_manager = plugin_manager.clone();
203+
let plugin_manager_clone = plugin_manager.clone();
214204
tasks.push(task::spawn(async move {
215205
for flow in &expired_flow_data {
216-
cloned_plugin_manager
217-
.process_flow_data(*flow)
218-
.await
219-
.unwrap();
206+
plugin_manager_clone.process_flow_data(*flow).await.unwrap();
220207
}
221208
debug!(
222209
"Sending {} expired flows to plugins done",
@@ -225,21 +212,18 @@ pub async fn packet_capture(arg: Args) -> Result<(), FluereError> {
225212
}));
226213

227214
active_flow.retain(|key, _| !expired_flows.contains(key));
228-
let cloned_records = records.clone();
229-
records.clear();
215+
let records_to_export = take(&mut records);
230216
debug!("Calculating timeout done");
231217

232218
let file_path_clone = file_path.clone();
233-
//let file = fs::File::create(file_path_clone).unwrap();
234219
info!("Export {} Started", file_path_clone);
235220
export_tasks.push(task::spawn(async move {
236-
fluere_exporter(cloned_records, file).await;
221+
fluere_exporter(records_to_export, file).await;
237222
info!("Export {} Finished", file_path_clone);
238223
}));
239224

240-
// let result = tasks.await;
241-
info!("running without blockng");
242-
file_path = cur_time_file(csv_file.as_str(), file_dir, ".csv");
225+
info!("running without blocking");
226+
file_path = cur_time_file(&csv_file, file_dir, ".csv");
243227
file = fs::File::create(file_path.as_ref()).unwrap();
244228
last_export = Instant::now();
245229
}
@@ -270,9 +254,9 @@ pub async fn packet_capture(arg: Args) -> Result<(), FluereError> {
270254
let _ = task.await;
271255
}
272256

273-
let cloned_records = records.clone();
257+
let records_to_export = take(&mut records);
274258
export_tasks.push(task::spawn(async {
275-
fluere_exporter(cloned_records, file).await;
259+
fluere_exporter(records_to_export, file).await;
276260
}));
277261
plugin_manager.await_completion(plugin_worker).await;
278262
drop(plugin_manager);

0 commit comments

Comments
 (0)