-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathhandler.rs
More file actions
5995 lines (5671 loc) · 246 KB
/
handler.rs
File metadata and controls
5995 lines (5671 loc) · 246 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
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
/*
* Copyright (c) 2024 Yunshan Networks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::{
borrow::Cow,
cmp::{max, min},
collections::{HashMap, HashSet},
fmt,
hash::{Hash, Hasher},
iter,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
path::PathBuf,
str,
sync::Arc,
time::Duration,
};
use arc_swap::{access::Map, ArcSwap};
use base64::{prelude::BASE64_STANDARD, Engine};
use bytesize::ByteSize;
use flexi_logger::{
writers::FileLogWriter, Age, Cleanup, Criterion, FileSpec, FlexiLoggerError, LogSpecification,
LoggerHandle, Naming,
};
use http2::get_expected_headers;
#[cfg(any(target_os = "linux", target_os = "android"))]
use libc::{mlockall, MCL_CURRENT, MCL_FUTURE};
use log::{debug, error, info, warn};
#[cfg(any(target_os = "linux", target_os = "android"))]
use nix::{
sched::{sched_setaffinity, CpuSet},
unistd::Pid,
};
use sysinfo::SystemExt;
#[cfg(any(target_os = "linux", target_os = "android"))]
use sysinfo::{CpuRefreshKind, RefreshKind, System};
use tokio::runtime::Runtime;
#[cfg(any(target_os = "linux", target_os = "android"))]
use super::config::{Ebpf, EbpfFileIoEvent, ProcessMatcher, SymbolTable};
use super::{
config::{
ApiResources, Config, DpdkSource, ExtraLogFields, ExtraLogFieldsInfo, HttpEndpoint,
HttpEndpointMatchRule, Iso8583ParseConfig, OracleConfig, PcapStream, PortConfig,
ProcessorsFlowLogTunning, RequestLogTunning, SessionTimeout, TagFilterOperator, Timeouts,
UserConfig, WebSphereMqParseConfig, GRPC_BUFFER_SIZE_MIN,
},
ConfigError, KubernetesPollerType, TrafficOverflowAction,
};
use crate::config::InferenceWhitelist;
use crate::flow_generator::protocol_logs::decode_new_rpc_trace_context_with_type;
use crate::rpc::Session;
#[cfg(all(unix, feature = "libtrace"))]
use crate::utils::environment::{get_ctrl_ip_and_mac, is_tt_workload};
use crate::{
common::{
decapsulate::TunnelTypeBitmap, enums::CaptureNetworkType,
l7_protocol_log::L7ProtocolBitmap, Timestamp, DEFAULT_LOG_UNCOMPRESSED_FILE_COUNT,
},
exception::ExceptionHandler,
flow_generator::{protocol_logs::SOFA_NEW_RPC_TRACE_CTX_KEY, FlowTimeout, TcpTimeout},
handler::PacketHandlerBuilder,
metric::document::TapSide,
trident::{AgentComponents, RunningMode},
utils::{
environment::{free_memory_check, running_in_container},
stats,
},
};
#[cfg(any(target_os = "linux", target_os = "android"))]
use crate::{
dispatcher::recv_engine::af_packet::OptTpacketVersion,
utils::environment::{get_container_resource_limits, set_container_resource_limit},
};
#[cfg(target_os = "linux")]
use crate::{
platform::{kubernetes::Poller, ApiWatcher, GenericPoller},
utils::environment::is_tt_pod,
};
use crate::{trident::AgentId, utils::cgroups::is_kernel_available_for_cgroups};
use public::bitmap::Bitmap;
use public::l7_protocol::L7Protocol;
use public::proto::agent::{self, AgentType, PacketCaptureType};
use public::utils::{bitmap::parse_range_list_to_bitmap, net::MacAddr};
cfg_if::cfg_if! {
if #[cfg(feature = "enterprise")] {
use crate::common::{
flow::PacketDirection,
l7_protocol_log::ParseParam,
};
use enterprise_utils::l7::custom_policy::{
custom_field_policy::{CustomFieldPolicy, PolicySlice},
custom_protocol_policy::ExtraCustomProtocolConfig,
};
use public::l7_protocol::L7ProtocolEnum;
}
}
const MB: u64 = 1048576;
type Access<C> = Map<Arc<ArcSwap<ModuleConfig>>, ModuleConfig, fn(&ModuleConfig) -> &C>;
pub type CollectorAccess = Access<CollectorConfig>;
pub type EnvironmentAccess = Access<EnvironmentConfig>;
pub type SenderAccess = Access<SenderConfig>;
pub type NpbAccess = Access<NpbConfig>;
pub type PlatformAccess = Access<PlatformConfig>;
pub type HandlerAccess = Access<HandlerConfig>;
pub type DispatcherAccess = Access<DispatcherConfig>;
pub type DiagnoseAccess = Access<DiagnoseConfig>;
pub type LogAccess = Access<LogConfig>;
pub type FlowAccess = Access<FlowConfig>;
pub type LogParserAccess = Access<LogParserConfig>;
pub type PcapAccess = Access<PcapStream>;
pub type DebugAccess = Access<DebugConfig>;
pub type SynchronizerAccess = Access<SynchronizerConfig>;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub type EbpfAccess = Access<EbpfConfig>;
pub type MetricServerAccess = Access<MetricServerConfig>;
pub type PortAccess = Access<PortConfig>;
#[derive(Clone, PartialEq, Eq)]
pub struct CollectorConfig {
pub enabled: bool,
pub inactive_server_port_aggregation: bool,
pub inactive_ip_aggregation: bool,
pub vtap_flow_1s_enabled: bool,
pub l4_log_collect_nps_threshold: u64,
pub l4_log_store_tap_types: [bool; 256],
pub l4_log_ignore_tap_sides: [bool; TapSide::MAX as usize + 1],
pub aggregate_health_check_l4_flow_log: bool,
pub l7_metrics_enabled: bool,
pub agent_type: AgentType,
pub agent_id: u16,
pub cloud_gateway_traffic: bool,
pub packet_delay: Duration,
pub npm_metrics_concurrent: bool,
}
impl fmt::Debug for CollectorConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CollectorConfig")
.field("enabled", &self.enabled)
.field(
"inactive_server_port_aggregation",
&self.inactive_server_port_aggregation,
)
.field("inactive_ip_aggregation", &self.inactive_ip_aggregation)
.field("vtap_flow_1s_enabled", &self.vtap_flow_1s_enabled)
.field(
"l4_log_store_tap_types",
&self
.l4_log_store_tap_types
.iter()
.enumerate()
.filter(|&(_, b)| *b)
.collect::<Vec<_>>(),
)
.field(
"l4_log_ignore_tap_sides",
&self
.l4_log_ignore_tap_sides
.iter()
.enumerate()
.filter_map(|(i, b)| {
if *b {
TapSide::try_from(i as u8).ok()
} else {
None
}
})
.collect::<Vec<_>>(),
)
.field(
"aggregate_health_check_l4_flow_log",
&self.aggregate_health_check_l4_flow_log,
)
.field(
"l4_log_collect_nps_threshold",
&self.l4_log_collect_nps_threshold,
)
.field("l7_metrics_enabled", &self.l7_metrics_enabled)
.field("agent_type", &self.agent_type)
.field("agent_id", &self.agent_id)
.field("cloud_gateway_traffic", &self.cloud_gateway_traffic)
.field("packet_delay", &self.packet_delay)
.field("npm_metrics_concurrent", &self.npm_metrics_concurrent)
.finish()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct EnvironmentConfig {
pub max_memory: u64,
pub max_millicpus: u32,
pub process_threshold: u32,
pub thread_threshold: u32,
pub sys_memory_limit: u32,
pub sys_memory_metric: agent::SysMemoryMetric,
pub log_file_size: u64,
pub capture_mode: PacketCaptureType,
pub guard_interval: Duration,
pub max_sockets: usize,
pub max_sockets_tolerate_interval: Duration,
pub system_load_circuit_breaker_threshold: f32,
pub system_load_circuit_breaker_recover: f32,
pub system_load_circuit_breaker_metric: agent::SystemLoadMetric,
pub page_cache_reclaim_percentage: u8,
pub free_disk_circuit_breaker_percentage_threshold: u8,
pub free_disk_circuit_breaker_absolute_threshold: u64,
pub free_disk_circuit_breaker_directories: Vec<String>,
pub idle_memory_trimming: bool,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SenderConfig {
pub dest_ip: String,
pub agent_id: u16,
pub team_id: u32,
pub organize_id: u32,
pub dest_port: u16,
pub npb_port: u16,
pub vxlan_flags: u8,
pub npb_enable_qos_bypass: bool,
pub npb_vlan: u16,
pub npb_vlan_mode: agent::VlanMode,
pub npb_dedup_enabled: bool,
pub npb_bps_threshold: u64,
pub npb_socket_type: agent::SocketType,
pub multiple_sockets_to_ingester: bool,
pub max_throughput_to_ingester: u64, // unit: Mbps
pub ingester_traffic_overflow_action: TrafficOverflowAction,
pub collector_socket_type: agent::SocketType,
pub standalone_data_file_size: u64,
pub standalone_data_file_dir: String,
pub server_tx_bandwidth_threshold: u64,
pub bandwidth_probe_interval: Duration,
pub enabled: bool,
}
impl Default for SenderConfig {
fn default() -> Self {
let module_config = ModuleConfig::default();
return module_config.sender.clone();
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct NpbConfig {
pub underlay_is_ipv6: bool,
pub vxlan_flags: u8,
pub npb_port: u16,
pub dedup_enabled: bool,
pub enable_qos_bypass: bool,
pub output_vlan: u16,
pub mtu: u32,
pub vlan_mode: agent::VlanMode,
pub socket_type: agent::SocketType,
pub ignore_overlay_vlan: bool,
pub queue_size: usize,
}
impl Default for NpbConfig {
fn default() -> Self {
let module_config = ModuleConfig::default();
return module_config.npb.clone();
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct OsProcScanConfig {
pub os_proc_root: String,
pub os_proc_socket_sync_interval: u32, // for sec
pub os_proc_socket_min_lifetime: u32, // for sec
pub os_app_tag_exec_user: String,
pub os_app_tag_exec: Vec<String>,
// whether to sync os socket and proc info
// only make sense when process_info_enabled() == true
pub os_proc_sync_enabled: bool,
}
#[cfg(target_os = "windows")]
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct OsProcScanConfig;
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct PlatformConfig {
pub sync_interval: Duration,
pub kubernetes_cluster_id: String,
pub libvirt_xml_path: PathBuf,
pub kubernetes_poller_type: KubernetesPollerType,
pub agent_id: u16,
pub enabled: bool,
pub agent_type: AgentType,
pub epc_id: u32,
pub kubernetes_api_enabled: bool,
pub kubernetes_api_list_limit: u32,
pub kubernetes_api_list_interval: Duration,
pub kubernetes_resources: Vec<ApiResources>,
pub max_memory: u64,
pub namespace: Option<String>,
pub thread_threshold: u32,
pub capture_mode: PacketCaptureType,
pub os_proc_scan_conf: OsProcScanConfig,
pub agent_enabled: bool,
#[cfg(target_os = "linux")]
pub extra_netns_regex: String,
}
#[derive(Clone, PartialEq, Debug, Eq)]
pub struct HandlerConfig {
pub npb_dedup_enabled: bool,
pub agent_type: AgentType,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DispatcherConfig {
pub global_pps_threshold: u64,
pub capture_packet_size: u32,
pub l7_log_packet_size: u32,
pub tunnel_type_bitmap: TunnelTypeBitmap,
pub tunnel_type_trim_bitmap: TunnelTypeBitmap,
pub agent_type: AgentType,
pub agent_id: u16,
pub capture_socket_type: agent::CaptureSocketType,
#[cfg(target_os = "linux")]
pub extra_netns_regex: String,
pub tap_interface_regex: String,
pub inner_interface_capture_enabled: bool,
pub inner_tap_interface_regex: String,
pub if_mac_source: agent::IfMacSource,
pub analyzer_ip: String,
pub analyzer_port: u16,
pub proxy_controller_ip: String,
pub proxy_controller_port: u16,
pub capture_bpf: String,
pub skip_npb_bpf: bool,
pub max_memory: u64,
pub af_packet_blocks: usize,
#[cfg(any(target_os = "linux", target_os = "android"))]
pub af_packet_version: OptTpacketVersion,
pub capture_mode: PacketCaptureType,
pub region_id: u32,
pub pod_cluster_id: u32,
pub enabled: bool,
pub npb_dedup_enabled: bool,
pub dpdk_source: DpdkSource,
pub dispatcher_queue: bool,
pub bond_group: Vec<String>,
#[cfg(any(target_os = "linux", target_os = "android"))]
pub cpu_set: CpuSet,
pub raw_packet_buffer_block_size: usize,
pub raw_packet_queue_size: usize,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct LogConfig {
pub log_level: String,
pub log_threshold: u32,
pub log_retention: u32,
pub rsyslog_enabled: bool,
pub host: String,
}
#[derive(Clone)]
pub struct PluginConfig {
pub last_updated: u32,
pub digest: u64, // for change detection
pub names: Vec<(String, agent::PluginType)>,
// name, data
pub wasm_plugins: Vec<(String, Vec<u8>)>,
pub so_plugins: Vec<(String, Vec<u8>)>,
}
impl PartialEq for PluginConfig {
fn eq(&self, other: &PluginConfig) -> bool {
self.last_updated == other.last_updated
&& self.digest == other.digest
&& self.names == other.names
}
}
impl Eq for PluginConfig {}
impl fmt::Debug for PluginConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PluginConfig")
.field("last_updated", &self.last_updated)
.field("digest", &self.digest)
.field("names", &self.names)
.finish()
}
}
impl PluginConfig {
fn fill_plugin_prog_from_server(
&mut self,
rt: &Runtime,
session: &Session,
agent_id: &AgentId,
) {
self.wasm_plugins.clear();
self.so_plugins.clear();
rt.block_on(async {
for (name, ptype) in self.names.iter() {
log::trace!("get {:?} plugin {}", ptype, name);
match session.grpc_get_plugin(name, *ptype, agent_id).await {
Ok(prog) => match ptype {
agent::PluginType::Wasm => self.wasm_plugins.push((name.clone(), prog)),
#[cfg(any(target_os = "linux", target_os = "android"))]
agent::PluginType::So => self.so_plugins.push((name.clone(), prog)),
#[cfg(any(target_os = "windows"))]
_ => (),
},
Err(err) => {
warn!("get {:?} plugin {} fail: {}", ptype, name, err);
continue;
}
}
}
});
info!(
"{} wasm and {} so plugins pulled from server",
self.wasm_plugins.len(),
self.so_plugins.len()
);
}
}
fn generate_tap_types_array(types: &[i16]) -> [bool; 256] {
let mut tap_types = [false; 256];
for &t in types {
if t == -1 {
return [false; 256];
} else if t < 0 || (t as u16) >= u16::from(CaptureNetworkType::Max) {
warn!("invalid tap type: {}", t);
} else {
tap_types[t as usize] = true;
}
}
tap_types
}
#[derive(Clone, PartialEq, Eq)]
pub struct FlowConfig {
pub agent_id: u16,
pub agent_type: AgentType,
pub cloud_gateway_traffic: bool,
pub collector_enabled: bool,
pub l7_log_tap_types: [bool; 256],
pub capture_mode: PacketCaptureType,
pub capacity: u32,
pub rrt_cache_capacity: u32,
pub hash_slots: u32,
pub packet_delay: Duration,
pub flush_interval: Duration,
pub flow_timeout: FlowTimeout,
pub ignore_tor_mac: bool,
pub ignore_l2_end: bool,
pub ignore_idc_vlan: bool,
pub memory_pool_size: usize,
pub l7_metrics_enabled: bool,
pub l7_metrics_enabled_for_packet: bool,
pub app_proto_log_enabled: bool,
pub l4_performance_enabled: bool,
pub l7_log_packet_size: u32,
pub l7_protocol_inference_max_fail_count: usize,
pub l7_protocol_inference_ttl: usize,
pub l7_protocol_inference_whitelist: Vec<InferenceWhitelist>,
// Enterprise Edition Feature: packet-sequence
pub packet_sequence_flag: u8,
pub packet_sequence_block_size: usize,
pub l7_protocol_enabled_bitmap: L7ProtocolBitmap,
// vec<protocolName, port bitmap>
pub l7_protocol_parse_port_bitmap: Arc<Vec<(String, Bitmap)>>,
pub plugins: PluginConfig,
pub rrt_tcp_timeout: usize, //micro sec
pub rrt_udp_timeout: usize, //micro sec
pub batched_buffer_size_limit: usize,
pub oracle_parse_conf: OracleConfig,
pub iso8583_parse_conf: Iso8583ParseConfig,
pub web_sphere_mq_parse_conf: WebSphereMqParseConfig,
pub obfuscate_enabled_protocols: L7ProtocolBitmap,
pub server_ports: Vec<u16>,
pub consistent_timestamp_in_l7_metrics: bool,
pub packet_segmentation_reassembly: HashSet<u16>,
}
impl From<&UserConfig> for FlowConfig {
fn from(conf: &UserConfig) -> Self {
const ISO8583_FIELD_MAX_COUNT: u16 = 129;
let mut packet_segmentation_reassembly = HashSet::new();
for c in &conf.inputs.cbpf.preprocess.packet_segmentation_reassembly {
if let Ok(port) = c.parse::<u16>() {
packet_segmentation_reassembly.insert(port);
} else {
let Some((start, end)) = c.split_once('-') else {
debug!(
"invalid port or port range in packet_segmentation_reassembly: {}",
c
);
continue;
};
let Ok(start) = start.trim().parse() else {
debug!(
"invalid start port in packet_segmentation_reassembly: {}",
c
);
continue;
};
let Ok(end) = end.trim().parse() else {
debug!("invalid end port in packet_segmentation_reassembly: {}", c);
continue;
};
if start <= end {
for port in start..=end {
packet_segmentation_reassembly.insert(port);
}
} else {
debug!(
"invalid port range in packet_segmentation_reassembly: {}",
c
);
}
}
}
FlowConfig {
agent_id: conf.global.common.agent_id as u16,
agent_type: conf.global.common.agent_type,
capture_mode: conf.inputs.cbpf.common.capture_mode,
cloud_gateway_traffic: conf
.inputs
.cbpf
.physical_mirror
.private_cloud_gateway_traffic,
collector_enabled: conf.outputs.flow_metrics.enabled,
l7_log_tap_types: generate_tap_types_array(
&conf.outputs.flow_log.filters.l7_capture_network_types,
),
rrt_cache_capacity: conf.processors.flow_log.tunning.rrt_cache_capacity,
capacity: conf.processors.flow_log.tunning.concurrent_flow_limit,
hash_slots: conf.processors.flow_log.tunning.flow_map_hash_slots,
packet_delay: conf
.processors
.flow_log
.time_window
.max_tolerable_packet_delay,
flush_interval: conf.processors.flow_log.conntrack.flow_flush_interval,
flow_timeout: FlowTimeout::from(TcpTimeout {
established: conf
.processors
.flow_log
.conntrack
.timeouts
.established
.into(),
closing_rst: conf
.processors
.flow_log
.conntrack
.timeouts
.closing_rst
.into(),
others: conf.processors.flow_log.conntrack.timeouts.others.into(),
opening_rst: conf
.processors
.flow_log
.conntrack
.timeouts
.opening_rst
.into(),
}),
ignore_tor_mac: conf
.processors
.flow_log
.conntrack
.flow_generation
.cloud_traffic_ignore_mac,
ignore_l2_end: conf
.processors
.flow_log
.conntrack
.flow_generation
.ignore_l2_end,
ignore_idc_vlan: conf
.processors
.flow_log
.conntrack
.flow_generation
.idc_traffic_ignore_vlan,
memory_pool_size: conf.processors.flow_log.tunning.memory_pool_size,
l7_metrics_enabled: conf.outputs.flow_metrics.filters.apm_metrics,
l7_metrics_enabled_for_packet: !conf.processors.request_log.filters.cbpf_disabled,
app_proto_log_enabled: !conf
.outputs
.flow_log
.filters
.l7_capture_network_types
.is_empty(),
l4_performance_enabled: conf.outputs.flow_metrics.filters.npm_metrics,
l7_log_packet_size: conf.processors.request_log.tunning.payload_truncation,
l7_protocol_inference_max_fail_count: conf
.processors
.request_log
.application_protocol_inference
.inference_max_retries,
l7_protocol_inference_ttl: conf
.processors
.request_log
.application_protocol_inference
.inference_result_ttl
.as_secs() as usize,
l7_protocol_inference_whitelist: conf
.processors
.request_log
.application_protocol_inference
.inference_whitelist
.clone(),
packet_sequence_flag: conf.processors.packet.tcp_header.header_fields_flag, // Enterprise Edition Feature: packet-sequence
packet_sequence_block_size: conf.processors.packet.tcp_header.block_size, // Enterprise Edition Feature: packet-sequence
l7_protocol_enabled_bitmap: L7ProtocolBitmap::from(
conf.processors
.request_log
.application_protocol_inference
.enabled_protocols
.as_slice(),
),
l7_protocol_parse_port_bitmap: Arc::new(conf.get_protocol_port_parse_bitmap()),
plugins: PluginConfig {
last_updated: conf.plugins.update_time.as_secs() as u32,
digest: {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
if !conf.plugins.so_plugins.is_empty() || !conf.plugins.wasm_plugins.is_empty()
{
conf.plugins.update_time.hash(&mut hasher);
for plugin in conf.plugins.wasm_plugins.iter() {
plugin.hash(&mut hasher);
agent::PluginType::Wasm.hash(&mut hasher);
}
for plugin in conf.plugins.so_plugins.iter() {
plugin.hash(&mut hasher);
agent::PluginType::So.hash(&mut hasher);
}
}
hasher.finish()
},
names: {
let mut plugins = vec![];
plugins.extend(
conf.plugins
.wasm_plugins
.iter()
.map(|p| (p.clone(), agent::PluginType::Wasm)),
);
plugins.extend(
conf.plugins
.so_plugins
.iter()
.map(|p| (p.clone(), agent::PluginType::So)),
);
plugins
},
wasm_plugins: vec![],
so_plugins: vec![],
},
rrt_tcp_timeout: conf
.processors
.request_log
.timeouts
.tcp_request_timeout
.as_micros() as usize,
rrt_udp_timeout: conf
.processors
.request_log
.timeouts
.udp_request_timeout
.as_micros() as usize,
batched_buffer_size_limit: conf.processors.flow_log.tunning.max_batched_buffer_size,
oracle_parse_conf: conf
.processors
.request_log
.application_protocol_inference
.protocol_special_config
.oracle
.clone(),
iso8583_parse_conf: Iso8583ParseConfig {
translation_enabled: conf
.processors
.request_log
.application_protocol_inference
.protocol_special_config
.iso8583
.translation_enabled,
pan_obfuscate: conf
.processors
.request_log
.application_protocol_inference
.protocol_special_config
.iso8583
.pan_obfuscate,
extract_fields: parse_range_list_to_bitmap(
ISO8583_FIELD_MAX_COUNT,
conf.processors
.request_log
.application_protocol_inference
.protocol_special_config
.iso8583
.extract_fields
.clone(),
false,
)
.unwrap(),
},
web_sphere_mq_parse_conf: WebSphereMqParseConfig {
parse_xml_enabled: conf
.processors
.request_log
.application_protocol_inference
.protocol_special_config
.web_sphere_mq
.parse_xml_enabled,
decompress_enabled: conf
.processors
.request_log
.application_protocol_inference
.protocol_special_config
.web_sphere_mq
.decompress_enabled,
filter_attributes_enabled: conf
.processors
.request_log
.application_protocol_inference
.protocol_special_config
.web_sphere_mq
.filter_attributes_enabled,
},
obfuscate_enabled_protocols: L7ProtocolBitmap::from(
conf.processors
.request_log
.tag_extraction
.obfuscate_protocols
.as_slice(),
),
server_ports: conf
.processors
.flow_log
.conntrack
.flow_generation
.server_ports
.clone(),
consistent_timestamp_in_l7_metrics: conf
.processors
.request_log
.tunning
.consistent_timestamp_in_l7_metrics,
packet_segmentation_reassembly,
}
}
}
impl FlowConfig {
pub fn need_to_reassemble(&self, src_port: u16, dst_port: u16) -> bool {
self.packet_segmentation_reassembly.contains(&src_port)
|| self.packet_segmentation_reassembly.contains(&dst_port)
}
pub fn flow_capacity(&self) -> u32 {
let default_capacity = ProcessorsFlowLogTunning::default().concurrent_flow_limit;
match self.capture_mode {
PacketCaptureType::Analyzer if self.capacity <= default_capacity => u32::MAX,
_ => self.capacity,
}
}
}
impl fmt::Debug for FlowConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FlowConfig")
.field("agent_id", &self.agent_id)
.field("agent_type", &self.agent_type)
.field("cloud_gateway_traffic", &self.cloud_gateway_traffic)
.field("collector_enabled", &self.collector_enabled)
.field(
"l7_log_tap_types",
&self
.l7_log_tap_types
.iter()
.enumerate()
.filter(|&(_, b)| *b)
.collect::<Vec<_>>(),
)
.field("capacity", &self.capacity)
.field("flow_capacity", &self.flow_capacity())
.field("hash_slots", &self.hash_slots)
.field("packet_delay", &self.packet_delay)
.field("flush_interval", &self.flush_interval)
.field("flow_timeout", &self.flow_timeout)
.field("ignore_tor_mac", &self.ignore_tor_mac)
.field("ignore_l2_end", &self.ignore_l2_end)
.field("l7_metrics_enabled", &self.l7_metrics_enabled)
.field(
"l7_metrics_enabled_for_packet",
&self.l7_metrics_enabled_for_packet,
)
.field("app_proto_log_enabled", &self.app_proto_log_enabled)
.field("l4_performance_enabled", &self.l4_performance_enabled)
.field("l7_log_packet_size", &self.l7_log_packet_size)
.field(
"l7_protocol_inference_max_fail_count",
&self.l7_protocol_inference_max_fail_count,
)
.field("l7_protocol_inference_ttl", &self.l7_protocol_inference_ttl)
.field("packet_sequence_flag", &self.packet_sequence_flag)
.field(
"packet_sequence_block_size",
&self.packet_sequence_block_size,
)
.field(
"l7_protocol_enabled_bitmap",
&self.l7_protocol_enabled_bitmap,
)
// FIXME: this field is too long to log
// .field("l7_protocol_parse_port_bitmap", &self.l7_protocol_parse_port_bitmap)
.field("plugins", &self.plugins)
.field("server_ports", &self.server_ports)
.field(
"packet_segmentation_reassembly",
&self.packet_segmentation_reassembly,
)
.finish()
}
}
#[derive(Clone, PartialEq, Eq)]
struct TrieNode {
children: HashMap<char, Box<TrieNode>>,
keep_segments: Option<usize>,
}
impl TrieNode {
fn new() -> Self {
TrieNode {
children: HashMap::new(),
keep_segments: None,
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct HttpEndpointTrie {
root: TrieNode,
}
impl HttpEndpointTrie {
pub fn new() -> Self {
Self {
root: TrieNode::new(),
}
}
pub fn insert(&mut self, rule: &HttpEndpointMatchRule) {
let mut node = &mut self.root;
for ch in rule.url_prefix.chars() {
node = node
.children
.entry(ch)
.or_insert_with(|| Box::new(TrieNode::new()));
}
node.keep_segments = Some(rule.keep_segments);
}
pub fn find_matching_rule(&self, input: &str) -> usize {
const DEFAULT_KEEP_SEGMENTS: usize = 2;
let mut node = &self.root;
let mut keep_segments = node.keep_segments.unwrap_or(DEFAULT_KEEP_SEGMENTS);
let has_rules = node.keep_segments.is_some() || !node.children.is_empty(); // if no rules are set, keep_segments defaults to DEFAULT_KEEP_SEGMENTS: 2
let mut matched = node.keep_segments.is_some(); // if it has a rule, and the prefix is "", any path is matched
for c in input.chars() {
if let Some(child) = node.children.get(&c) {
keep_segments = child.keep_segments.unwrap_or(keep_segments);
if !matched {
matched = child.keep_segments.is_some(); // if the child is a leaf, then matched
}
node = child.as_ref();
} else {
break;
}
}
if !matched && has_rules {
0
} else {
keep_segments
}
}
}
impl From<&HttpEndpoint> for HttpEndpointTrie {
fn from(v: &HttpEndpoint) -> Self {
let mut t = Self::new();
v.match_rules
.iter()
.filter(|r| r.keep_segments > 0)
.for_each(|r| t.insert(r));
t
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum Operator {
Equal,
Prefix,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BlacklistTrieNode {
children: HashMap<char, Box<BlacklistTrieNode>>,
operator: Option<Operator>,
}
impl BlacklistTrieNode {
pub fn is_on_blacklist(&self, input: &str) -> bool {
if input.is_empty() {
return false;
}
let mut node = self;
for c in input.chars() {
node = match node.children.get(&c) {
Some(child) => child,
None => return false,
};
if let Some(op) = &node.operator {
if op == &Operator::Prefix {
return true;
}
}
}
// If we've reached the end of the input and the last node has an operator,
// it must be because we matched a complete word, not a prefix.
if let Some(o) = node.operator {
o == Operator::Equal
} else {
false
}
}
}
#[derive(Clone, Default, Eq, PartialEq)]
pub struct BlacklistTrie {
config: Vec<TagFilterOperator>,
pub endpoint: BlacklistTrieNode,