-
Notifications
You must be signed in to change notification settings - Fork 2
/
probe.rs
2061 lines (1827 loc) · 85.9 KB
/
probe.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* rsprobe: probe.rs - MpegTS Stream Analysis Probe with Kafka and GStreamer
*
* Written in 2024 by Chris Kennedy (C)
*
* License: MIT
*
*/
use ahash::AHashMap;
use base64::{engine::general_purpose, Engine as _};
#[cfg(feature = "dpdk_enabled")]
use capsule::config::{load_config, DPDKConfig};
#[cfg(feature = "dpdk_enabled")]
use capsule::dpdk;
#[cfg(all(feature = "dpdk_enabled", target_os = "linux"))]
use capsule::prelude::*;
use clap::Parser;
use env_logger::{Builder as LogBuilder, Env};
use futures::stream::StreamExt;
#[cfg(feature = "gst")]
use gstreamer as gst;
#[cfg(feature = "gst")]
use gstreamer::prelude::*;
use lazy_static::lazy_static;
use log::{debug, error, info};
use pcap::{Active, Capture, Device, PacketCodec};
use rdkafka::admin::{AdminClient, AdminOptions, NewTopic};
use rdkafka::client::DefaultClientContext;
use rdkafka::config::ClientConfig;
use rdkafka::error::KafkaError;
use rdkafka::producer::{FutureProducer, FutureRecord};
use rdkafka::types::RDKafkaErrorCode;
use rsprobe::get_system_stats;
use rsprobe::stream_data::process_mpegts_packet;
use rsprobe::stream_data::{
cleanup_stale_streams, get_pid_map, identify_video_pid, parse_and_store_pat, process_packet,
update_pid_map, Codec, ImageData, PmtInfo, StreamData, Tr101290Errors, PAT_PID,
};
#[cfg(feature = "gst")]
use rsprobe::stream_data::{initialize_pipeline, process_video_packets, pull_images};
use rsprobe::watch_file::watch_daemon;
use rsprobe::{current_unix_timestamp_ms, hexdump};
use serde::Serialize;
use serde_json::{json, Value};
use std::fs::File;
use std::sync::mpsc::channel;
use std::sync::RwLock;
use std::thread;
use std::{
error::Error as StdError,
fmt, io,
io::Write,
net::{IpAddr, Ipv4Addr, UdpSocket},
sync::atomic::{AtomicBool, Ordering},
sync::Arc,
time::Instant,
};
use tokio::sync::mpsc::error::TryRecvError;
use tokio::sync::mpsc::{self};
use tokio::time::Duration;
lazy_static! {
static ref PROBE_DATA: RwLock<AHashMap<String, ProbeData>> = RwLock::new(AHashMap::new());
}
struct ProbeData {
stream_groupings: AHashMap<u16, StreamGrouping>,
global_data: serde_json::Map<String, Value>,
}
struct StreamGrouping {
stream_data_list: Vec<StreamData>,
}
#[derive(Serialize)]
struct PidStreamType {
pid: u16,
stream_type: String,
stream_type_number: u8,
media_type: String, // audio, video, data
ccerrors: u32,
bitrate: u64,
}
fn flatten_streams(
stream_groupings: &AHashMap<u16, StreamGrouping>,
probe_id: String,
) -> serde_json::Map<String, Value> {
let mut flat_structure: serde_json::Map<String, Value> = serde_json::Map::new();
for (pid, grouping) in stream_groupings.iter() {
let stream_data = grouping.stream_data_list.last().unwrap(); // Assuming last item is representative
let prefix = format!("streams.{}", pid);
flat_structure.insert(format!("{}.id", prefix), json!(probe_id.clone()));
flat_structure.insert(
format!("{}.program_number", prefix),
json!(stream_data.program_number),
);
flat_structure.insert(format!("{}.pid", prefix), json!(stream_data.pid));
flat_structure.insert(format!("{}.pmt_pid", prefix), json!(stream_data.pmt_pid));
flat_structure.insert(
format!("{}.stream_type", prefix),
json!(stream_data.stream_type),
);
flat_structure.insert(
format!("{}.capture_time", prefix),
json!(stream_data.capture_time),
);
flat_structure.insert(
format!("{}.capture_iat", prefix),
json!(stream_data.capture_iat),
);
flat_structure.insert(
format!("{}.capture_iat_max", prefix),
json!(stream_data.capture_iat_max),
);
flat_structure.insert(format!("{}.iat", prefix), json!(stream_data.iat));
flat_structure.insert(format!("{}.iat_max", prefix), json!(stream_data.iat_max));
flat_structure.insert(format!("{}.iat_min", prefix), json!(stream_data.iat_min));
flat_structure.insert(format!("{}.iat_avg", prefix), json!(stream_data.iat_avg));
flat_structure.insert(
format!("{}.packet_count", prefix),
json!(grouping.stream_data_list.len()),
);
flat_structure.insert(
format!("{}.continuity_counter", prefix),
json!(stream_data.continuity_counter),
);
flat_structure.insert(
format!("{}.timestamp", prefix),
json!(stream_data.timestamp),
);
flat_structure.insert(format!("{}.bitrate", prefix), json!(stream_data.bitrate));
flat_structure.insert(
format!("{}.bitrate_max", prefix),
json!(stream_data.bitrate_max),
);
flat_structure.insert(
format!("{}.bitrate_min", prefix),
json!(stream_data.bitrate_min),
);
flat_structure.insert(
format!("{}.bitrate_avg", prefix),
json!(stream_data.bitrate_avg),
);
flat_structure.insert(
format!("{}.error_count", prefix),
json!(stream_data.error_count),
);
flat_structure.insert(
format!("{}.current_error_count", prefix),
json!(stream_data.current_error_count),
);
flat_structure.insert(
format!("{}.last_arrival_time", prefix),
json!(stream_data.last_arrival_time),
);
flat_structure.insert(
format!("{}.last_sample_time", prefix),
json!(stream_data.last_sample_time),
);
flat_structure.insert(
format!("{}.start_time", prefix),
json!(stream_data.start_time),
);
flat_structure.insert(
format!("{}.total_bits", prefix),
json!(stream_data.total_bits),
);
flat_structure.insert(
format!("{}.total_bits_sample", prefix),
json!(stream_data.total_bits_sample),
);
flat_structure.insert(format!("{}.count", prefix), json!(stream_data.count));
flat_structure.insert(
format!("{}.packet_start", prefix),
json!(stream_data.packet_start),
);
flat_structure.insert(
format!("{}.packet_len", prefix),
json!(stream_data.packet_len),
);
flat_structure.insert(
format!("{}.stream_type_number", prefix),
json!(stream_data.stream_type_number),
);
// pcr and pts
flat_structure.insert(format!("{}.pcr", prefix), json!(stream_data.pcr));
flat_structure.insert(format!("{}.pts", prefix), json!(stream_data.pts));
}
flat_structure
}
// Define your custom PacketCodec
pub struct BoxCodec;
impl PacketCodec for BoxCodec {
type Item = (Box<[u8]>, std::time::SystemTime); // Adjusted to return SystemTime
fn decode(&mut self, packet: pcap::Packet) -> Self::Item {
// Convert pcap timestamp to SystemTime
let timestamp = std::time::UNIX_EPOCH
+ std::time::Duration::new(
packet.header.ts.tv_sec as u64,
packet.header.ts.tv_usec as u32 * 1000,
);
(packet.data.into(), timestamp)
}
}
// Define a custom error for when the target device is not found
#[derive(Debug)]
struct DeviceNotFoundError;
impl std::error::Error for DeviceNotFoundError {}
impl DeviceNotFoundError {
#[allow(dead_code)]
fn new() -> ErrorWrapper {
ErrorWrapper(Box::new(Self))
}
}
impl fmt::Display for DeviceNotFoundError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Target device not found")
}
}
struct ErrorWrapper(Box<dyn StdError + Send + Sync>);
impl fmt::Debug for ErrorWrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Display for ErrorWrapper {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl StdError for ErrorWrapper {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.0.source()
}
}
pub trait Packet: Send {
fn data(&self) -> &[u8];
}
// Common interface for DPDK functionality
trait DpdkPort: Send {
fn start(&self) -> Result<(), Box<dyn std::error::Error>>;
fn stop(&self) -> Result<(), Box<dyn std::error::Error>>;
fn rx_burst(&self, packets: &mut Vec<Box<dyn Packet>>) -> Result<(), anyhow::Error>;
// Other necessary methods...
}
// Implementation for Linux with DPDK enabled
#[cfg(all(feature = "dpdk_enabled", target_os = "linux"))]
struct RealDpdkPort(dpdk::Port);
#[cfg(all(feature = "dpdk_enabled", target_os = "linux"))]
impl DpdkPort for RealDpdkPort {
fn start(&self) -> Result<(), Box<dyn std::error::Error>> {
self.0.start()?;
Ok(())
}
fn stop(&self) -> Result<(), Box<dyn std::error::Error>> {
self.0.stop()?;
Ok(())
}
fn rx_burst(&self, packets: &mut Vec<Box<dyn Packet>>) -> Result<(), anyhow::Error> {
// Logic for rx_burst...
Ok(())
}
}
#[cfg(all(feature = "dpdk_enabled", target_os = "linux"))]
fn init_dpdk(
port_id: u16,
promiscuous_mode: bool,
) -> Result<Box<dyn DpdkPort>, Box<dyn std::error::Error>> {
// Initialize capsule environment
let config = load_config()?;
dpdk::eal::init(config)?;
// Configure network interface
let port = dpdk::Port::new(port_id)?;
port.configure()?;
// Set promiscuous mode if needed
if promiscuous_mode {
port.set_promiscuous(true)?;
}
// Start the port
port.start()?;
Ok(Box::new(RealDpdkPort(port)))
}
// Placeholder implementation for non-Linux or DPDK disabled builds
#[cfg(not(all(feature = "dpdk_enabled", target_os = "linux")))]
struct DummyDpdkPort;
#[cfg(not(all(feature = "dpdk_enabled", target_os = "linux")))]
impl DpdkPort for DummyDpdkPort {
fn start(&self) -> Result<(), Box<dyn std::error::Error>> {
Err("DPDK is not supported on this OS".into())
}
fn stop(&self) -> Result<(), Box<dyn std::error::Error>> {
Err("DPDK is not supported on this OS".into())
}
fn rx_burst(&self, _packets: &mut Vec<Box<dyn Packet>>) -> Result<(), anyhow::Error> {
Err(anyhow::Error::msg("DPDK is not supported on this OS"))
}
}
#[cfg(not(all(feature = "dpdk_enabled", target_os = "linux")))]
fn init_dpdk(
_port_id: u16,
_promiscuous: bool,
) -> Result<Box<dyn DpdkPort>, Box<dyn std::error::Error>> {
Ok(Box::new(DummyDpdkPort))
}
fn init_pcap(
source_device: &str,
#[cfg(target_os = "linux")] _use_wireless: bool,
#[cfg(not(target_os = "linux"))] use_wireless: bool,
promiscuous: bool,
read_time_out: i32,
read_size: i32,
immediate_mode: bool,
buffer_size: i64,
source_protocol: &str,
source_port: i32,
source_ip: &str,
) -> Result<(Capture<Active>, UdpSocket), Box<dyn StdError>> {
let devices = Device::list().map_err(|e| Box::new(e) as Box<dyn StdError>)?;
debug!("init_pcap: devices: {:?}", devices);
info!("init_pcap: specified source_device: {}", source_device);
// Different handling for Linux and non-Linux systems
#[cfg(target_os = "linux")]
let target_device = devices
.into_iter()
.find(|d| d.name == source_device || source_device.is_empty())
.ok_or_else(|| Box::new(DeviceNotFoundError) as Box<dyn StdError>)?;
#[cfg(not(target_os = "linux"))]
let target_device = devices
.into_iter()
.find(|d| {
(d.name == source_device || source_device.is_empty())
&& d.flags.is_up()
&& !d.flags.is_loopback()
&& d.flags.is_running()
&& (!d.flags.is_wireless() || use_wireless)
})
.ok_or_else(|| Box::new(DeviceNotFoundError) as Box<dyn StdError>)?;
// Get the IP address of the target device
let interface_addr = target_device
.addresses
.iter()
.find_map(|addr| match addr.addr {
IpAddr::V4(ipv4_addr) => Some(ipv4_addr),
_ => None,
})
.ok_or_else(|| "No valid IPv4 address found for target device")?;
let multicast_addr = source_ip
.parse::<Ipv4Addr>()
.expect("Invalid IP address format for source_ip");
info!(
"init_pcap: UDP Socket Binding to interface {} with Join IGMP Multicast for address:port udp://{}:{}.",
interface_addr, multicast_addr, source_port
);
let socket = UdpSocket::bind("0.0.0.0:0").map_err(|e| Box::new(e) as Box<dyn StdError>)?;
socket
.join_multicast_v4(&multicast_addr, &interface_addr)
.map_err(|e| Box::new(e) as Box<dyn StdError>)?;
let source_host_and_port = format!(
"{} dst port {} and ip dst host {}",
source_protocol, source_port, source_ip
);
let cap = Capture::from_device(target_device.clone())
.map_err(|e| Box::new(e) as Box<dyn StdError>)?
.promisc(promiscuous)
.timeout(read_time_out)
.snaplen(read_size)
.immediate_mode(immediate_mode)
.buffer_size(buffer_size as i32)
.open()
.map_err(|e| Box::new(e) as Box<dyn StdError>)?;
info!(
"init_pcap: set non-blocking mode on capture device {}",
target_device.name
);
let mut cap = cap
.setnonblock()
.map_err(|e| Box::new(e) as Box<dyn StdError>)?;
info!(
"init_pcap: set filter for {} on capture device {}",
source_host_and_port, target_device.name
);
cap.filter(&source_host_and_port, true)
.map_err(|e| Box::new(e) as Box<dyn StdError>)?;
info!(
"init_pcap: capture device {} successfully initialized",
target_device.name
);
Ok((cap, socket))
}
async fn create_kafka_producer(kafka_config: &ClientConfig) -> FutureProducer {
kafka_config
.create()
.expect("Failed to create Kafka producer")
}
async fn send_to_kafka(
producer: &FutureProducer,
topic: &str,
key: &str,
payload: &str,
timeout: Duration,
retry_attempts: usize,
retry_delay: Duration,
) -> Result<(), KafkaError> {
let mut attempt = 0;
loop {
let record = FutureRecord::to(topic).payload(payload).key(key);
match producer.send(record, timeout).await {
Ok((partition, offset)) => {
log::debug!(
"Message sent successfully to topic: {}, partition: {}, offset: {}",
topic,
partition,
offset
);
return Ok(());
}
Err((KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull), _)) => {
attempt += 1;
if attempt >= retry_attempts {
log::error!(
"Failed to send message after {} retries. Giving up.",
attempt
);
return Err(KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull));
} else {
log::warn!(
"Queue is full. Retrying in {} ms... (attempt {}/{})",
retry_delay.as_millis(),
attempt,
retry_attempts
);
tokio::time::sleep(retry_delay).await;
}
}
Err((err, _)) => {
log::error!("Failed to send message: {:?}", err);
return Err(err);
}
}
}
}
/// RsProbe Configuration
#[derive(Parser, Debug)]
#[clap(
author = "Chris Kennedy",
version = "0.7.9",
about = "MpegTS Stream Analysis Probe with Kafka and GStreamer"
)]
struct Args {
/// probe ID - ID for the probe to send with the messages
#[clap(long, env = "PROBE_ID", default_value = "")]
probe_id: String,
/// Sets the batch size
#[clap(long, env = "PCAP_BATCH_SIZE", default_value_t = 7)]
pcap_batch_size: usize,
/// Sets the payload offset
#[clap(long, env = "PAYLOAD_OFFSET", default_value_t = 42)]
payload_offset: usize,
/// Sets the packet size
#[clap(long, env = "PACKET_SIZE", default_value_t = 188)]
packet_size: usize,
/// Sets the read timeout
#[clap(long, env = "READ_TIME_OUT", default_value_t = 300_000)]
read_time_out: i32,
/// Sets the source device
#[clap(long, env = "SOURCE_DEVICE", default_value = "")]
source_device: String,
/// Sets the source IP
#[clap(long, env = "SOURCE_IP", default_value = "224.0.0.200")]
source_ip: String,
/// Sets the source protocol
#[clap(long, env = "SOURCE_PROTOCOL", default_value = "udp")]
source_protocol: String,
/// Sets the source port
#[clap(long, env = "SOURCE_PORT", default_value_t = 10_000)]
source_port: i32,
/// Sets the debug mode
#[clap(long, env = "DEBUG", default_value_t = false)]
debug_on: bool,
/// Sets the silent mode
#[clap(long, env = "SILENT", default_value_t = false)]
silent: bool,
/// Sets if wireless is used
#[clap(long, env = "USE_WIRELESS", default_value_t = false)]
use_wireless: bool,
/// number of packets to capture
#[clap(long, env = "PACKET_COUNT", default_value_t = 0)]
packet_count: u64,
/// Turn off progress output dots
#[clap(long, env = "NO_PROGRESS", default_value_t = false)]
no_progress: bool,
/// Use promiscuous mode
#[clap(long, env = "PROMISCUOUS", default_value_t = false)]
promiscuous: bool,
/// Show the TR101290 p1, p2 and p3 errors if any
#[clap(long, env = "SHOW_TR101290", default_value_t = false)]
show_tr101290: bool,
/// Sets the pcap buffer size
#[clap(long, env = "BUFFER_SIZE", default_value_t = 1 * 1_358 * 1_000)]
buffer_size: usize,
/// PCAP immediate mode
#[clap(long, env = "IMMEDIATE_MODE", default_value_t = false)]
immediate_mode: bool,
/// PCAP output capture stats mode
#[clap(long, env = "PCAP_STATS", default_value_t = false)]
pcap_stats: bool,
/// MPSC Channel Size for ZeroMQ
#[clap(long, env = "PCAP_CHANNEL_SIZE", default_value_t = 100000)]
pcap_channel_size: usize,
/// MPSC Channel Size for PCAP
#[clap(long, env = "KAFKA_CHANNEL_SIZE", default_value_t = 100000)]
kafka_channel_size: usize,
/// DPDK enable
#[clap(long, env = "DPDK", default_value_t = false)]
dpdk: bool,
/// DPDK Port ID
#[clap(long, env = "DPDK_PORT_ID", default_value_t = 0)]
dpdk_port_id: u16,
/// IPC Path for ZeroMQ
#[clap(long, env = "IPC_PATH")]
ipc_path: Option<String>,
/// Output file for Kafka
#[clap(long, env = "OUTPUT_FILE", default_value = "")]
output_file: String,
/// Watch File - File we watch for changes to send as the streams.PID.log_line string
#[clap(long, env = "WATCH_FILE", default_value = "")]
watch_file: String,
/// Input Codec - Expected codec type for Video stream, limited to h264, h265 or mpeg2.
#[clap(long, env = "INPUT_CODEC", default_value = "h264")]
input_codec: String,
/// Loglevel - Log level for the application
#[clap(long, env = "LOGLEVEL", default_value = "info")]
loglevel: String,
/// Extract Images from the video stream (requires feature gst)
#[clap(long, env = "EXTRACT_IMAGES", default_value_t = false)]
extract_images: bool,
/// Extract Captions from the video stream (requires feature gst)
#[clap(long, env = "EXTRACT_CAPTIONS", default_value_t = false)]
extract_captions: bool,
/// Save Images to disk
#[cfg(feature = "gst")]
#[clap(long, env = "SAVE_IMAGES", default_value_t = false)]
save_images: bool,
/// Image Sample Rate Ns - Image sample rate in nano seconds (fails to get images as frequently)
#[clap(long, env = "IMAGE_SAMPLE_RATE_NS", default_value_t = 0)]
image_sample_rate_ns: u64,
/// Scale Images using gstreamer - Scale the images with gstreamer instead of separately
#[clap(long, env = "SCALE_IMAGES_AFTER_GSTREAMER", default_value_t = false)]
scale_images_after_gstreamer: bool,
/// Jpeg Quality - Quality of the Jpeg images
#[clap(long, env = "JPEG_QUALITY", default_value_t = 75)]
jpeg_quality: u8,
/// Image Height - Image height in pixels of Thumbnail extracted images
#[clap(long, env = "IMAGE_HEIGHT", default_value_t = 96)]
image_height: u32,
/// filmstrip length
#[clap(long, env = "FILMSTRIP_LENGTH", default_value_t = 8)]
filmstrip_length: usize,
/// Gstreamer Queue Buffers
#[clap(long, env = "GST_QUEUE_BUFFERS", default_value_t = 2)]
gst_queue_buffers: u32,
/// image framerate - Framerate of the images extracted in 1/1 format
#[clap(long, env = "IMAGE_FRAMERATE", default_value = "1/1")]
image_framerate: String,
/// image_frame_increment - Increment the frame number by this amount for jpeg image strip, 0 matches filmstrip-length
#[clap(long, env = "IMAGE_FRAME_INCREMENT", default_value_t = 0)]
image_frame_increment: u8,
/// Image buffer size - Size of the buffer for the images from gstreamer
#[clap(long, env = "IMAGE_BUFFER_SIZE", default_value_t = 10)]
image_buffer_size: usize,
/// Video buffer size - Size of the buffer for the video to gstreamer
#[clap(long, env = "VIDEO_BUFFER_SIZE", default_value_t = 1000000)]
video_buffer_size: usize,
/// Kafka Broker
#[clap(long, env = "KAFKA_BROKER", default_value = "")]
kafka_broker: String,
/// Kafka Topic
#[clap(long, env = "KAFKA_TOPIC", default_value = "")]
kafka_topic: String,
/// Kafka timeout to drop packets
#[clap(long, env = "KAFKA_TIMEOUT", default_value_t = 100)]
kafka_timeout: u64,
/// Kafka Key
#[clap(long, env = "KAFKA_KEY", default_value = "")]
kafka_key: String,
/// Kafka sending interval in milliseconds
#[clap(long, env = "KAFKA_INTERVAL", default_value_t = 1000)]
kafka_interval: u64,
/// System Stats Interval in milliseconds
#[clap(long, env = "SYSTEM_STATS_INTERVAL", default_value_t = 5000)]
system_stats_interval: u64,
/// Dump Packets - Dump packets to the console in hex
#[clap(long, env = "DUMP_PACKETS", default_value_t = false)]
dump_packets: bool,
/// Clear Stream Timeout - Clear the streams that are not changing after this amout of time in ms
#[clap(long, env = "CLEAR_STREAM_TIMEOUT", default_value_t = 0)]
clear_stream_timeout: u64,
}
// MAIN Function
#[tokio::main]
async fn main() {
let ctrl_c = tokio::signal::ctrl_c();
let running = Arc::new(AtomicBool::new(true));
tokio::select! {
_ = ctrl_c => {
println!("\nCtrl-C received, shutting down");
running.store(false, Ordering::SeqCst);
std::process::exit(1);
}
_ = rsprobe(running.clone()) => {
println!("\nRsProbe exited");
}
}
}
// RsProbeFunction
async fn rsprobe(running: Arc<AtomicBool>) {
let running_capture = running.clone();
let running_kafka = running.clone();
#[cfg(feature = "gst")]
let running_gstreamer_process = running.clone();
#[cfg(feature = "gst")]
let running_gstreamer_pull = running.clone();
let running_watch_file = running.clone();
dotenv::dotenv().ok(); // read .env file
let args = Args::parse();
// Clone the args for use in the threads
let probe_id_clone = args.probe_id.clone();
let source_ip_clone = args.source_ip.clone();
let source_ip_clone1 = args.source_ip.clone();
let source_ip_clone2 = args.source_ip.clone();
#[cfg(all(feature = "dpdk_enabled", target_os = "linux"))]
let use_dpdk = args.dpdk;
println!("Starting RsProbe...");
if args.silent {
// set log level to error
std::env::set_var("RUST_LOG", "error");
}
// calculate read size based on batch size and packet size
let read_size: i32 =
(args.packet_size as i32 * args.pcap_batch_size as i32) + args.payload_offset as i32; // pcap read size
// Set Rust log level with --loglevel if it is set
let loglevel = args.loglevel.to_lowercase();
match loglevel.as_str() {
"error" => {
log::set_max_level(log::LevelFilter::Error);
}
"warn" => {
log::set_max_level(log::LevelFilter::Warn);
}
"info" => {
log::set_max_level(log::LevelFilter::Info);
}
"debug" => {
log::set_max_level(log::LevelFilter::Debug);
}
"trace" => {
log::set_max_level(log::LevelFilter::Trace);
}
_ => {
log::set_max_level(log::LevelFilter::Info);
}
}
// Initialize logging
let env = Env::default().filter_or("RUST_LOG", loglevel.as_str()); // Default to `info` if `RUST_LOG` is not set
LogBuilder::from_env(env).init();
let (ptx, mut prx) = mpsc::channel::<(Arc<Vec<u8>>, u64, u64)>(args.pcap_channel_size);
// Spawn a new thread for packet capture
let capture_task = if cfg!(feature = "dpdk_enabled") && args.dpdk {
// DPDK is enabled
tokio::spawn(async move {
let port_id = 0; // Set your port ID
let promiscuous_mode = args.promiscuous;
// Initialize DPDK
let port = match init_dpdk(port_id, promiscuous_mode) {
Ok(p) => p,
Err(e) => {
error!("Failed to initialize DPDK: {:?}", e);
return;
}
};
let mut packets = Vec::new();
let mut last_iat = 0;
while running_capture.load(Ordering::SeqCst) {
match port.rx_burst(&mut packets) {
Ok(_) => {
for packet in packets.drain(..) {
// Extract data from the packet
let data = packet.data();
// Convert to Arc<Vec<u8>> to maintain consistency with pcap logic
let packet_data = Arc::new(data.to_vec());
let timestamp = current_unix_timestamp_ms().unwrap_or(0);
let iat = if last_iat == 0 {
0
} else {
timestamp - last_iat
};
last_iat = timestamp;
// Send packet data to processing channel
ptx.send((packet_data, timestamp, iat)).await.unwrap();
// Here you can implement additional processing such as parsing the packet,
// updating statistics, handling specific packet types, etc.
}
}
Err(e) => {
error!("Error fetching packets: {:?}", e);
break;
}
}
}
// Cleanup
// Handle stopping the port
if let Err(e) = port.stop() {
error!("Error stopping DPDK port: {:?}", e);
}
})
} else {
tokio::spawn(async move {
// initialize the pcap
let (cap, _socket) = init_pcap(
&args.source_device,
args.use_wireless,
args.promiscuous,
args.read_time_out,
read_size,
args.immediate_mode,
args.buffer_size as i64,
&args.source_protocol,
args.source_port,
&source_ip_clone,
)
.expect("Failed to initialize pcap");
// Create a PacketStream from the Capture
let mut stream = cap.stream(BoxCodec).unwrap();
let mut count = 0;
let mut stats_last_sent_ts = Instant::now();
let mut packets_dropped = 0;
let mut last_iat = 0;
while running_capture.load(Ordering::SeqCst) {
while let Some(packet) = stream.next().await {
if !running_capture.load(Ordering::SeqCst) {
break;
}
match packet {
Ok((data, system_time_timestamp)) => {
count += 1;
let packet_data = Arc::new(data.to_vec());
// Convert SystemTime to u64 milliseconds
let duration_since_epoch = system_time_timestamp
.duration_since(std::time::UNIX_EPOCH)
.expect("Time went backwards");
let timestamp_ms = duration_since_epoch.as_secs() * 1_000
+ duration_since_epoch.subsec_millis() as u64;
let iat = if last_iat == 0 {
0
} else {
timestamp_ms - last_iat
};
last_iat = timestamp_ms;
match ptx.send((packet_data, timestamp_ms, iat)).await {
Ok(_) => {
// Successfully sent, continue or perform other operations
}
Err(e) => {
eprintln!("Error sending packet: {}", e);
break; // Exit the loop if sending fails
}
}
if !running_capture.load(Ordering::SeqCst) {
break;
}
let current_ts = Instant::now();
if args.pcap_stats
&& ((current_ts.duration_since(stats_last_sent_ts).as_secs() >= 30)
|| count == 1)
{
stats_last_sent_ts = current_ts;
let stats = stream.capture_mut().stats().unwrap();
println!(
"[{}] #{} Current stats: Received: {}, Dropped: {}/{}, Interface Dropped: {} packet_size: {} bytes.",
timestamp_ms, count, stats.received, stats.dropped - packets_dropped, stats.dropped, stats.if_dropped, data.len(),
);
packets_dropped = stats.dropped;
}
}
Err(e) => {
// Print error and information about it
error!("PCap Capture Error occurred: {}", e);
if e == pcap::Error::TimeoutExpired {
// If timeout expired, check for running_capture
if !running_capture.load(Ordering::SeqCst) {
break;
}
// Timeout expired, continue and try again
continue;
} else {
// Exit the loop if an error occurs
running_capture.store(false, Ordering::SeqCst);
break;
}
}
}
}
if args.debug_on {
let stats = stream.capture_mut().stats().unwrap();
println!(
"Current stats: Received: {}, Dropped: {}, Interface Dropped: {}",
stats.received, stats.dropped, stats.if_dropped
);
}
if !running_capture.load(Ordering::SeqCst) {
break;
}
}
let stats = stream.capture_mut().stats().unwrap();
println!("Packet capture statistics:");
println!("Received: {}", stats.received);
println!("Dropped: {}", stats.dropped);
println!("Interface Dropped: {}", stats.if_dropped);
})
};
let mut probe_id = args.probe_id.clone();
if probe_id_clone.is_empty() {
// construct stream.source_ip and stream.source_port with stream.host
let system_stats = get_system_stats();
probe_id = format!(
"{}:{}:{}",
system_stats.host_name, source_ip_clone1, args.source_port
);
}
let probe_id_clone1 = probe_id.clone();
let probe_id_clone2 = probe_id.clone();
// Setup channel for passing stream_data for Kafka thread sending the stream data to monitor process
let (ktx, mut krx) = mpsc::channel::<(
Vec<Arc<StreamData>>,
Vec<String>,
Vec<ImageData>,
AHashMap<u16, Arc<StreamData>>,
Tr101290Errors,
)>(args.kafka_channel_size);
let kafka_broker_clone = args.kafka_broker.clone();
let kafka_topic_clone = args.kafka_topic.clone();
let kafka_topic_clone1 = args.kafka_topic.clone();
let kafka_topic_clone2 = args.kafka_topic.clone();
let kafka_topic_clone3 = args.kafka_topic.clone();
let kafka_broker_clone2 = args.kafka_broker.clone();
let kafka_broker_clone3 = args.kafka_broker.clone();
let kafka_thread = tokio::spawn(async move {
// exit thread if kafka_broker is not set
if kafka_broker_clone.is_empty() || kafka_topic_clone.is_empty() {
return;
}
// Flatten the processes and insert them into the structure as an array of strings
let cpu_threshold = 5.0; // CPU usage threshold (in percentage)
let ram_threshold = 100 * 1024 * 1024; // RAM usage threshold (in bytes)
let mut output_file_counter: u32 = 0;
let mut last_system_stats = Instant::now();
let mut dot_last_file_write = Instant::now();
let mut log_messages = Vec::<String>::new();
let output_file_without_jpg = args.output_file.replace(".jpg", "");
// Now you can directly use the fields from `image_data`
let mut image_pts: u64 = 0;
let mut duplicates: u64 = 0;
let mut hash = 0;
let mut hamming: f64 = 0.0;
info!("Kafka publisher startup {}", args.kafka_broker);
let mut kafka_conf = ClientConfig::new();