-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathremote_config.rs
More file actions
823 lines (758 loc) · 32 KB
/
Copy pathremote_config.rs
File metadata and controls
823 lines (758 loc) · 32 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
use crate::sidecar::MaybeShmLimiter;
use datadog_ffe::rules_based::{Configuration, UniversalFlagConfig};
use datadog_live_debugger::debugger_defs::{DebuggerData, DebuggerPayload};
use datadog_live_debugger::{FilterList, LiveDebuggingData, ServiceConfiguration};
use datadog_live_debugger_ffi::data::Probe;
use datadog_live_debugger_ffi::evaluator::{ddog_register_expr_evaluator, Evaluator};
use datadog_live_debugger_ffi::send_data::{
ddog_debugger_diagnostics_create_unboxed, ddog_snapshot_redacted_type,
};
use libdd_remote_config::config::dynamic::{Configs, DynamicConfigFile, TracingSamplingRuleProvenance};
use libdd_remote_config::fetch::ConfigInvariants;
use libdd_remote_config::{
default_registry, RemoteConfigCapabilities, RemoteConfigParsed, RemoteConfigProduct, Target,
};
use datadog_sidecar::service::blocking::SidecarTransport;
use datadog_sidecar::service::{InstanceId, QueueId};
use datadog_sidecar::shm_remote_config::{RemoteConfigManager, RemoteConfigUpdate};
use datadog_sidecar_ffi::ddog_sidecar_send_debugger_diagnostics;
use libdd_common::tag::Tag;
use libdd_common::Endpoint;
use libdd_common_ffi::slice::AsBytes;
use libdd_common_ffi::{CharSlice, MaybeError};
use itertools::Itertools;
use regex_automata::dfa::regex::Regex;
use serde::Serialize;
use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::ffi::c_char;
use std::mem;
use std::ptr::NonNull;
use std::sync::Arc;
use tracing::debug;
use crate::bytes::{ZendString, OwnedZendString, dangling_zend_string};
pub const DYANMIC_CONFIG_UPDATE_UNMODIFIED: *mut ZendString = 1isize as *mut ZendString;
#[repr(C)]
pub enum DynamicConfigUpdateMode {
Read,
ReadWrite,
Write,
Restore,
}
pub type DynamicConfigUpdate = for<'a> extern "C" fn(
config: CharSlice,
value: OwnedZendString,
mode: DynamicConfigUpdateMode,
) -> *mut ZendString;
static mut LIVE_DEBUGGER_CALLBACKS: Option<LiveDebuggerCallbacks> = None;
static mut DYNAMIC_CONFIG_UPDATE: Option<DynamicConfigUpdate> = None;
type VecRemoteConfigProduct = libdd_common_ffi::Vec<RemoteConfigProduct>;
#[no_mangle]
pub static mut DATADOG_REMOTE_CONFIG_PRODUCTS: VecRemoteConfigProduct = libdd_common_ffi::Vec::new();
type VecRemoteConfigCapabilities = libdd_common_ffi::Vec<RemoteConfigCapabilities>;
#[no_mangle]
pub static mut DATADOG_REMOTE_CONFIG_CAPABILITIES: VecRemoteConfigCapabilities =
libdd_common_ffi::Vec::new();
struct ActiveDynamicConfig {
priority: u8,
configs: Vec<Configs>,
}
#[derive(Default)]
struct DynamicConfig {
active_configs: HashMap<String, ActiveDynamicConfig>,
merged_configs: Vec<Configs>,
old_config_values: HashMap<String, Option<OwnedZendString>>,
}
fn compute_merged_configs(active_configs: &HashMap<String, ActiveDynamicConfig>) -> Vec<Configs> {
let mut sorted: Vec<_> = active_configs.values().collect();
sorted.sort_by_key(|c| c.priority);
let mut seen = HashSet::new();
let mut merged = vec![];
for entry in sorted {
for config in &entry.configs {
if seen.insert(mem::discriminant(config)) {
merged.push(config.clone());
}
}
}
merged
}
pub struct RemoteConfigState {
manager: RemoteConfigManager,
live_debugger: LiveDebuggerState,
dynamic_config: DynamicConfig,
}
#[repr(C)]
pub struct LiveDebuggerSetup<'a> {
pub evaluator: &'a Evaluator,
pub callbacks: LiveDebuggerCallbacks,
}
#[repr(C)]
#[derive(Clone)]
pub struct LiveDebuggerCallbacks {
pub set_probe: extern "C" fn(probe: Probe, limiter: &MaybeShmLimiter) -> i64,
pub remove_probe: extern "C" fn(id: i64),
}
#[derive(Default)]
pub struct LiveDebuggerState {
pub spans_map: HashMap<String, i64>,
pub active: HashMap<String, Box<(RemoteConfigParsed, MaybeShmLimiter)>>, // Box<> for stable heap address!
pub config_id: String,
pub allow_dfa: Option<Regex>,
pub deny_dfa: Option<Regex>,
pub di_enabled: bool,
}
/// Flags selecting which Remote Config products/capabilities to subscribe to.
///
/// Passed as a single C-ABI struct so call sites can use designated initializers
/// and name the flags, instead of a positional sequence of bool args.
#[repr(C)]
pub struct RemoteConfigFlags {
pub live_debugging_enabled: bool,
pub appsec_activation: bool,
pub appsec_config: bool,
pub ffe_enabled: bool,
}
#[no_mangle]
#[allow(static_mut_refs)]
pub unsafe extern "C" fn ddog_init_remote_config(flags: RemoteConfigFlags) {
let RemoteConfigFlags {
live_debugging_enabled,
appsec_activation,
appsec_config,
ffe_enabled,
} = flags;
mem::take(&mut DATADOG_REMOTE_CONFIG_PRODUCTS);
mem::take(&mut DATADOG_REMOTE_CONFIG_CAPABILITIES);
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::ApmTracing);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::ApmTracingCustomTags);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::ApmTracingEnabled);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::ApmTracingHttpHeaderTags);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::ApmTracingLogsInjection);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::ApmTracingSampleRate);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::ApmTracingSampleRules);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::ApmTracingMulticonfig);
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::AsmFeatures);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::AsmAutoUserInstrumMode);
if appsec_activation {
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::AsmActivation);
}
if ffe_enabled {
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::FfeFlags);
DATADOG_REMOTE_CONFIG_CAPABILITIES.push(RemoteConfigCapabilities::FfeFlagConfigurationRules);
}
if live_debugging_enabled {
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::LiveDebugging)
}
if appsec_config {
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::AsmData);
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::AsmDd);
DATADOG_REMOTE_CONFIG_PRODUCTS.push(RemoteConfigProduct::Asm);
[
RemoteConfigCapabilities::AsmIpBlocking,
RemoteConfigCapabilities::AsmDdRules,
RemoteConfigCapabilities::AsmExclusions,
RemoteConfigCapabilities::AsmRequestBlocking,
RemoteConfigCapabilities::AsmResponseBlocking,
RemoteConfigCapabilities::AsmUserBlocking,
RemoteConfigCapabilities::AsmCustomRules,
RemoteConfigCapabilities::AsmCustomBlockingResponse,
RemoteConfigCapabilities::AsmTrustedIps,
RemoteConfigCapabilities::AsmRaspLfi,
RemoteConfigCapabilities::AsmRaspSsrf,
RemoteConfigCapabilities::AsmRaspSqli,
RemoteConfigCapabilities::AsmTraceTaggingRules,
RemoteConfigCapabilities::AsmDdMulticonfig,
RemoteConfigCapabilities::AsmEndpointFingerprint,
RemoteConfigCapabilities::AsmSessionFingerprint,
RemoteConfigCapabilities::AsmNetworkFingerprint,
RemoteConfigCapabilities::AsmHeaderFingerprint,
RemoteConfigCapabilities::AsmProcessorOverrides,
RemoteConfigCapabilities::AsmCustomDataScanners,
RemoteConfigCapabilities::AsmRawResponseBody,
]
.iter()
.for_each(|c| DATADOG_REMOTE_CONFIG_CAPABILITIES.push(*c));
}
}
// Per-thread state
#[no_mangle]
pub unsafe extern "C" fn ddog_init_remote_config_state(
endpoint: &Endpoint,
di_enabled: bool,
) -> Box<RemoteConfigState> {
#[allow(clippy::expect_used)]
let registry = Arc::new(
default_registry()
.with::<LiveDebuggingData>()
.expect("LiveDebugger is distinct from default products")
.with::<UniversalFlagConfig>()
.expect("FFE is distinct from default products"),
);
Box::new(RemoteConfigState {
manager: RemoteConfigManager::new_with_registry(ConfigInvariants {
language: "php".to_string(),
tracer_version: include_str!("../VERSION").trim().into(),
endpoint: endpoint.clone(),
agentless: None,
}, registry),
live_debugger: LiveDebuggerState {
di_enabled,
..Default::default()
},
dynamic_config: Default::default(),
})
}
#[derive(Serialize)]
struct SampleRule<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<&'a str>,
service: &'a str,
resource: &'a str,
#[serde(skip_serializing_if = "HashMap::is_empty")]
tags: HashMap<&'a str, &'a str>,
#[serde(rename = "_provenance")]
provenance: TracingSamplingRuleProvenance,
sample_rate: f64,
}
fn bool_config(value: &bool) -> Cow<'static, str> {
Cow::Borrowed(if *value { "1" } else { "0" })
}
fn map_config_name(config: &Configs) -> &'static str {
match config {
Configs::TracingHeaderTags(_) => "datadog.trace.header_tags",
Configs::TracingSamplingRate(_) => "datadog.trace.sample_rate",
Configs::LogInjectionEnabled(_) => "datadog.logs_injection",
Configs::TracingTags(_) => "datadog.tags",
Configs::TracingEnabled(_) => "datadog.trace.enabled",
Configs::TracingSamplingRules(_) => "datadog.trace.sampling_rules",
Configs::DynamicInstrumentationEnabled(_) => "datadog.dynamic_instrumentation.enabled",
Configs::ExceptionReplayEnabled(_) => "datadog.exception_replay_enabled",
Configs::CodeOriginEnabled(_) => "datadog.code_origin_for_spans_enabled",
}
}
fn map_config_value(config: &Configs) -> Cow<'_, str> {
match config {
Configs::TracingHeaderTags(tags) => tags.iter().map(|(k, _)| k).join(",").into(),
Configs::TracingSamplingRate(rate) => rate.to_string().into(),
Configs::LogInjectionEnabled(enabled) => bool_config(enabled),
Configs::TracingTags(tags) => tags.join(",").into(),
Configs::TracingEnabled(enabled) => bool_config(enabled),
Configs::TracingSamplingRules(rules) => {
let map: Vec<_> = rules
.iter()
.map(|r| SampleRule {
name: r.name.as_deref(),
service: r.service.as_str(),
resource: r.resource.as_str(),
tags: r
.tags
.iter()
.map(|t| (t.key.as_str(), t.value_glob.as_str()))
.collect(),
provenance: r.provenance,
sample_rate: r.sample_rate,
})
.collect();
serde_json::to_string(&map).unwrap().into()
}
Configs::DynamicInstrumentationEnabled(enabled) => bool_config(enabled),
Configs::ExceptionReplayEnabled(enabled) => bool_config(enabled),
Configs::CodeOriginEnabled(enabled) => bool_config(enabled),
}
}
fn use_rc_config<'a>(config: &Configs, user_value: &'a [u8], _rc_value: &'a str) -> bool {
match config {
Configs::DynamicInstrumentationEnabled(_) | Configs::ExceptionReplayEnabled(_) | Configs::CodeOriginEnabled(_) => {
let user_str = String::from_utf8_lossy(user_value);
user_str.parse::<i32>().unwrap_or(0) != 0 || user_str.eq_ignore_ascii_case("true") || user_str.eq_ignore_ascii_case("yes") || user_str.eq_ignore_ascii_case("on")
},
_ => true,
}
}
fn reset_old_config(name: &str, val: Option<OwnedZendString>) {
unsafe {
if let Some(val) = val {
DYNAMIC_CONFIG_UPDATE.unwrap()(name.into(), val, DynamicConfigUpdateMode::Write);
} else {
DYNAMIC_CONFIG_UPDATE.unwrap()(name.into(), dangling_zend_string(), DynamicConfigUpdateMode::Restore);
}
}
}
fn remove_old_configs(remote_config: &mut RemoteConfigState) {
for (name, val) in remote_config.dynamic_config.old_config_values.drain() {
reset_old_config(name.as_str(), val);
}
remote_config.dynamic_config.active_configs.clear();
remote_config.dynamic_config.merged_configs.clear();
}
fn insert_new_configs(
old_config_values: &mut HashMap<String, Option<OwnedZendString>>,
old_configs: &mut Vec<Configs>,
new_configs: Vec<Configs>,
) {
let mut found_configs = HashSet::new();
for config in new_configs.iter() {
let (name, val) = (map_config_name(config), map_config_value(config));
let (is_update, merged) = {
let old_value = old_config_values.get(name);
let user_value = if let Some(old_zstr) = old_value {
old_zstr.as_ref().map(|v| v.0)
} else {
let val = unsafe { DYNAMIC_CONFIG_UPDATE.unwrap()(name.into(), dangling_zend_string(), DynamicConfigUpdateMode::Read) };
if val == DYANMIC_CONFIG_UPDATE_UNMODIFIED {
None
} else {
Some(NonNull::new(val).unwrap())
}
};
(old_value.is_some(), user_value.map(|v| {
if use_rc_config(config, unsafe { v.as_ref() }.as_ref(), val.as_ref()) {
val.as_ref().into()
} else {
OwnedZendString::from_copy(v)
}
}).unwrap_or_else(|| val.as_ref().into()))
};
let original = unsafe { DYNAMIC_CONFIG_UPDATE }.unwrap()(name.into(), merged, if is_update { DynamicConfigUpdateMode::Write } else { DynamicConfigUpdateMode::ReadWrite });
if let Some(original) = NonNull::new(original) {
old_config_values.insert(name.into(), if original.as_ptr() == DYANMIC_CONFIG_UPDATE_UNMODIFIED { None } else { Some(OwnedZendString(original)) });
}
found_configs.insert(mem::discriminant(config));
}
for config in old_configs.iter() {
if !found_configs.contains(&mem::discriminant(config)) {
let name = map_config_name(config);
if let Some(val) = old_config_values.remove(name) {
reset_old_config(name, val);
}
}
}
*old_configs = new_configs;
}
#[no_mangle]
pub extern "C" fn ddog_remote_config_current_generation(remote_config: &RemoteConfigState) -> u64 {
remote_config.manager.current_remote_config_generation()
}
#[no_mangle]
pub extern "C" fn ddog_remote_config_get_path(remote_config: &RemoteConfigState) -> *const c_char {
remote_config
.manager
.active_reader
.as_ref()
.map(|r| r.get_path().as_ptr())
.unwrap_or(std::ptr::null())
}
#[no_mangle]
pub extern "C" fn ddog_process_remote_configs(remote_config: &mut RemoteConfigState) -> bool {
let mut has_updates = false;
loop {
match remote_config.manager.fetch_update() {
RemoteConfigUpdate::None => break,
RemoteConfigUpdate::Add {
value,
limiter_index,
} => {
if let Some(data) = value.data {
match value.path.product() {
RemoteConfigProduct::LiveDebugging => {
let val = Box::new((data, MaybeShmLimiter::open(limiter_index)));
let rc_ref: &mut RemoteConfigState = unsafe { mem::transmute(remote_config as *mut _) }; // sigh, borrow checker
let config_id = value.path.config_id();
let entry = remote_config.live_debugger.active.entry(config_id.to_string());
let (parsed, limiter) = match entry {
Entry::Occupied(mut e) => {
e.insert(val);
let r = e.into_mut();
(&r.0, &r.1)
}
Entry::Vacant(e) => {
let r = e.insert(val);
(&r.0, &r.1)
}
};
if let Some(debugger) = parsed.downcast::<LiveDebuggingData>() {
apply_config(rc_ref, config_id, debugger, limiter);
}
}
RemoteConfigProduct::ApmTracing => {
if let Some(config_data) = data.downcast::<DynamicConfigFile>() {
let priority = config_data.priority();
let configs: Vec<Configs> = config_data.lib_config.clone().into();
if !configs.is_empty() {
remote_config.dynamic_config.active_configs
.insert(value.path.config_id().to_string(), ActiveDynamicConfig { priority, configs });
let merged = compute_merged_configs(&remote_config.dynamic_config.active_configs);
insert_new_configs(
&mut remote_config.dynamic_config.old_config_values,
&mut remote_config.dynamic_config.merged_configs,
merged,
);
}
}
}
RemoteConfigProduct::FfeFlags => {
debug!("Received FFE flags configuration");
if let Some(ufc) = data.downcast::<UniversalFlagConfig>() {
if let Ok(ufc_owned) = UniversalFlagConfig::from_json(ufc.to_json().to_vec()) {
crate::ffe::store_config(Configuration::from_server_response(ufc_owned));
}
}
}
_ => {}
}
}
}
RemoteConfigUpdate::Remove(path) => match path.product() {
RemoteConfigProduct::LiveDebugging => {
if let Some(boxed) = remote_config.live_debugger.active.remove(path.config_id()) {
if let Some(debugger) = boxed.0.downcast::<LiveDebuggingData>() {
remove_config(remote_config, path.config_id(), debugger);
}
}
}
RemoteConfigProduct::ApmTracing => {
if remote_config.dynamic_config.active_configs.remove(path.config_id()).is_some() {
if remote_config.dynamic_config.active_configs.is_empty() {
remove_old_configs(remote_config);
} else {
let merged = compute_merged_configs(&remote_config.dynamic_config.active_configs);
insert_new_configs(
&mut remote_config.dynamic_config.old_config_values,
&mut remote_config.dynamic_config.merged_configs,
merged,
);
}
}
}
RemoteConfigProduct::FfeFlags => {
debug!("FFE flags configuration removed");
crate::ffe::clear_config();
}
_ => (),
},
}
has_updates = true
}
has_updates
}
fn apply_config(
remote_config: &mut RemoteConfigState,
config_id: &str,
debugger: &LiveDebuggingData,
limiter: &MaybeShmLimiter,
) {
if let Some(callbacks) = unsafe { &LIVE_DEBUGGER_CALLBACKS } {
match debugger {
LiveDebuggingData::Probe(probe) => {
debug!("Applying live debugger probe {probe:?}");
if remote_config.live_debugger.di_enabled {
// Tear down any hook already installed for this config before
// replacing it, so it isn't left dangling into the dropped config.
if let Some(old_hook_id) =
remote_config.live_debugger.spans_map.remove(config_id)
{
(callbacks.remove_probe)(old_hook_id);
}
let hook_id = (callbacks.set_probe)(probe.into(), limiter);
if hook_id >= 0 {
// Key by config_id, not probe.id: distinct configs can share a
// probe id, so a probe.id key would orphan a hook on removal (UAF).
remote_config
.live_debugger
.spans_map
.insert(config_id.to_string(), hook_id);
}
}
// If di_enabled is false, probe is stored in `active` but hook is not installed.
// It will be installed when di_enabled transitions to true.
}
LiveDebuggingData::ServiceConfiguration(config) => {
debug!("Applying live debugger service config {config:?}");
fn build_regex(list: &FilterList) -> Option<Regex> {
if list.classes.is_empty() && list.package_prefixes.is_empty() {
None
} else {
let mut regex = "".to_string();
for s in list.classes.iter() {
if !regex.is_empty() {
regex.push('|');
}
regex.push_str(®ex::escape(s.as_str()));
}
for s in list.package_prefixes.iter() {
if !regex.is_empty() {
regex.push('|');
}
regex.push_str(®ex::escape(s.as_str()));
regex.push_str(".*");
}
Some(Regex::new(regex.as_str()).unwrap())
}
}
remote_config.live_debugger.config_id = config.id.clone();
remote_config.live_debugger.allow_dfa = build_regex(&config.allow);
remote_config.live_debugger.deny_dfa = build_regex(&config.deny);
}
}
}
}
fn remove_config(remote_config: &mut RemoteConfigState, config_id: &str, debugger: &LiveDebuggingData) {
if let Some(callbacks) = unsafe { &LIVE_DEBUGGER_CALLBACKS } {
match debugger {
LiveDebuggingData::Probe(probe) => {
if let Some(id) = remote_config.live_debugger.spans_map.remove(config_id) {
debug!("Removing live debugger probe {} (config {})", probe.id, config_id);
(callbacks.remove_probe)(id);
}
}
LiveDebuggingData::ServiceConfiguration(ServiceConfiguration { id, .. }) => {
// There can only be one active service configuration, but I don't want to rely on the order of adding and removing service configurations
if id == &remote_config.live_debugger.config_id {
debug!("Resetting live-debugger service config");
remote_config.live_debugger.allow_dfa = None;
remote_config.live_debugger.deny_dfa = None;
}
}
}
}
}
/// Returns all loaded remote config entries as a JSON object:
/// { "config_id": "content_summary", ... }
/// For live debugger entries the value is the probe ID (or "service_config").
/// For dynamic config entries the value is "apm_tracing".
/// The returned pointer must be freed with `ddog_remote_config_loaded_configs_free`.
#[no_mangle]
pub extern "C" fn ddog_remote_config_get_loaded_configs(remote_config: &RemoteConfigState) -> *mut c_char {
let mut entries: Vec<(String, String)> = Vec::new();
for (config_id, boxed) in &remote_config.live_debugger.active {
if let Some(debugger) = boxed.0.downcast::<LiveDebuggingData>() {
let value = match debugger {
LiveDebuggingData::Probe(p) => format!(r#"{{"type":"probe","id":"{}"}}"#, p.id),
LiveDebuggingData::ServiceConfiguration(sc) => format!(r#"{{"type":"service_config","id":"{}"}}"#, sc.id),
};
entries.push((config_id.clone(), value));
}
}
for config_id in remote_config.dynamic_config.active_configs.keys() {
entries.push((config_id.clone(), r#"{"type":"apm_tracing"}"#.to_string()));
}
entries.sort_unstable_by(|a, b| a.0.cmp(&b.0));
let json_pairs: Vec<String> = entries
.into_iter()
.map(|(k, v)| format!(r#"{}:{}"#, serde_json::to_string(&k).unwrap_or_default(), v))
.collect();
let json = format!("{{{}}}", json_pairs.join(","));
std::ffi::CString::new(json).unwrap_or_default().into_raw()
}
#[no_mangle]
pub extern "C" fn ddog_remote_config_loaded_configs_free(ptr: *mut c_char) {
if !ptr.is_null() {
drop(unsafe { std::ffi::CString::from_raw(ptr) });
}
}
#[no_mangle]
pub extern "C" fn ddog_type_can_be_instrumented(
remote_config: &RemoteConfigState,
typename: CharSlice,
) -> bool {
if ddog_snapshot_redacted_type(typename) {
return false;
}
if let Some(regex) = &remote_config.live_debugger.allow_dfa {
if !regex.is_match(typename.as_bytes()) {
return false;
}
}
if let Some(regex) = &remote_config.live_debugger.deny_dfa {
if regex.is_match(typename.as_bytes()) {
return false;
}
}
true
}
#[no_mangle]
pub extern "C" fn ddog_global_log_probe_limiter_inc(remote_config: &RemoteConfigState) -> bool {
if let Some(boxed) = remote_config
.live_debugger
.active
.get(&remote_config.live_debugger.config_id)
{
if let Some(LiveDebuggingData::ServiceConfiguration(config)) = boxed.0.downcast::<LiveDebuggingData>() {
boxed.1.inc(config.sampling_snapshots_per_second)
} else {
true
}
} else {
true
}
}
#[no_mangle]
pub unsafe extern "C" fn ddog_CharSlice_to_owned(str: CharSlice) -> *mut Vec<c_char> {
Box::into_raw(Box::new(str.as_slice().into()))
}
#[no_mangle]
pub extern "C" fn ddog_remote_configs_service_env_change(
remote_config: &mut RemoteConfigState,
service: CharSlice,
env: CharSlice,
version: CharSlice,
tags: &libdd_common_ffi::Vec<Tag>,
process_tags: &libdd_common_ffi::Vec<Tag>,
) -> bool {
let new_target = Target::new(
service.to_utf8_lossy().to_string(),
env.to_utf8_lossy().to_string(),
version.to_utf8_lossy().to_string(),
tags.as_slice().iter().map(|t| t.to_string()).collect(),
process_tags.as_slice().iter().map(|t| t.to_string()).collect(),
);
if let Some(target) = remote_config.manager.get_target() {
if **target == new_target {
return false;
}
}
remote_config.manager.track_target(&Arc::new(new_target));
// Caller must call ddog_process_remote_configs if true.
// We don't call it here to allow the caller delaying the call as necessary.
true
}
#[no_mangle]
pub unsafe extern "C" fn ddog_remote_config_alter_dynamic_config(
remote_config: &mut RemoteConfigState,
config: CharSlice,
new_value: OwnedZendString,
) -> bool {
if let Some(entry) = remote_config
.dynamic_config
.old_config_values
.get_mut(config.try_to_utf8().unwrap())
{
let mut ret = false;
let config_name = config.to_utf8_lossy();
for config in remote_config.dynamic_config.merged_configs.iter() {
let name = map_config_name(config);
if name == config_name.as_ref() {
let val = map_config_value(config);
if !use_rc_config(config, new_value.as_ref().as_ref(), val.as_ref()) {
ret = true;
}
break;
}
}
*entry = Some(new_value);
return ret;
}
true
}
#[no_mangle]
pub unsafe extern "C" fn ddog_setup_remote_config(
update_config: DynamicConfigUpdate,
setup: &LiveDebuggerSetup,
) {
ddog_register_expr_evaluator(setup.evaluator);
DYNAMIC_CONFIG_UPDATE = Some(update_config);
LIVE_DEBUGGER_CALLBACKS = Some(setup.callbacks.clone());
}
/// Enable or disable dynamic instrumentation.
/// When disabling: all installed probe hooks are removed (but kept in `active` for reinstallation).
/// When enabling: all probes in `active` that have no installed hook are (re-)installed.
#[no_mangle]
pub extern "C" fn ddog_set_dynamic_instrumentation_enabled(
remote_config: &mut RemoteConfigState,
enabled: bool,
) {
if remote_config.live_debugger.di_enabled == enabled {
return;
}
remote_config.live_debugger.di_enabled = enabled;
if let Some(callbacks) = unsafe { &LIVE_DEBUGGER_CALLBACKS } {
if !enabled {
// Remove all installed probe hooks; keep `active` intact for reinstallation.
for (_, hook_id) in remote_config.live_debugger.spans_map.drain() {
(callbacks.remove_probe)(hook_id);
}
} else {
// Reinstall all probes in `active`, keyed by config_id (like apply/remove).
for (config_id, boxed) in remote_config.live_debugger.active.iter() {
if let Some(LiveDebuggingData::Probe(probe)) = boxed.0.downcast::<LiveDebuggingData>() {
let hook_id = (callbacks.set_probe)(probe.into(), &boxed.1);
if hook_id >= 0 {
remote_config
.live_debugger
.spans_map
.insert(config_id.clone(), hook_id);
}
}
}
}
}
}
#[no_mangle]
pub extern "C" fn ddog_rshutdown_remote_config(remote_config: &mut RemoteConfigState) {
remote_config.live_debugger.spans_map.clear();
remote_config.dynamic_config.old_config_values.clear();
remote_config.dynamic_config.active_configs.clear();
remote_config.dynamic_config.merged_configs.clear();
remote_config.manager.unload_configs(&[
RemoteConfigProduct::ApmTracing,
RemoteConfigProduct::LiveDebugging,
]);
}
#[no_mangle]
pub extern "C" fn ddog_shutdown_remote_config(_: Box<RemoteConfigState>) {}
/// Free the FFI-owned allocations in a `Probe` (the `tags` vec and the nested
/// span-decoration / log allocations) by consuming it; borrowed `CharSlice`s are
/// left untouched. Called from `dd_probe_dtor` when a probe is uninstalled.
#[no_mangle]
pub extern "C" fn ddog_drop_probe(_: Probe) {}
#[no_mangle]
pub extern "C" fn ddog_log_debugger_data(payloads: &Vec<DebuggerPayload>) {
if !payloads.is_empty() {
debug!(
"Submitting debugger data: {}",
serde_json::to_string(payloads).unwrap()
);
}
}
#[no_mangle]
pub extern "C" fn ddog_log_debugger_datum(payload: &DebuggerPayload) {
debug!(
"Submitting debugger data: {}",
serde_json::to_string(payload).unwrap()
);
}
#[no_mangle]
pub unsafe extern "C" fn ddog_send_debugger_diagnostics<'a>(
remote_config_state: &RemoteConfigState,
transport: &mut Box<SidecarTransport>,
instance_id: &InstanceId,
queue_id: QueueId,
probe: &'a Probe,
timestamp: u64,
) -> MaybeError {
let service = Cow::Borrowed(
remote_config_state
.manager
.get_target()
.map_or("", |t| t.service()),
);
let mut payload = ddog_debugger_diagnostics_create_unboxed(
probe,
service,
Cow::Borrowed(&instance_id.runtime_id),
timestamp,
);
let DebuggerData::Diagnostics(ref mut diagnostics) = payload.debugger else {
unreachable!();
};
diagnostics.parent_id = Some(Cow::Borrowed(
remote_config_state.manager.current_runtime_id.as_str(),
));
debug!(
"Submitting debugger diagnostics data: {:?}",
serde_json::to_string(&payload).unwrap()
);
ddog_sidecar_send_debugger_diagnostics(transport, instance_id, queue_id, payload)
}