From 50d847dac6da6c008b6ecdd7f697eae07ede9bdb Mon Sep 17 00:00:00 2001 From: LorenzoTettamanti Date: Mon, 23 Nov 2026 10:53:51 +0100 Subject: [PATCH 1/2] refactor(identity): remove experimental service discovery --- core/src/components/identity/Cargo.toml | 4 +- core/src/components/identity/src/lib.rs | 4 +- core/src/components/identity/src/main.rs | 49 --- core/src/components/identity/src/mod.rs | 4 +- .../identity/src/service_discovery.rs | 297 ------------------ 5 files changed, 3 insertions(+), 355 deletions(-) delete mode 100644 core/src/components/identity/src/service_discovery.rs diff --git a/core/src/components/identity/Cargo.toml b/core/src/components/identity/Cargo.toml index 4cf6c732..542cad6d 100644 --- a/core/src/components/identity/Cargo.toml +++ b/core/src/components/identity/Cargo.toml @@ -13,7 +13,6 @@ repository = "https://github.com/CortexFlow/CortexBrain" default = ["struct", "enums"] struct = [] enums = [] -experimental = ["struct", "enums"] [dependencies] aya = "0.13.1" @@ -33,8 +32,7 @@ cortexbrain-common = { version="0.1.4", features = [ "program-handlers", "network-structs", "monitoring-structs", - "buffer-reader", - "experimental" + "buffer-reader" ] } nix = { version = "0.30.1", features = ["net"] } kube = { version = "2.0.1", features = ["client"] } diff --git a/core/src/components/identity/src/lib.rs b/core/src/components/identity/src/lib.rs index ceaedc26..eadef2b9 100644 --- a/core/src/components/identity/src/lib.rs +++ b/core/src/components/identity/src/lib.rs @@ -1,3 +1 @@ -pub mod helpers; -#[cfg(feature = "experimental")] -pub mod service_discovery; \ No newline at end of file +pub mod helpers; \ No newline at end of file diff --git a/core/src/components/identity/src/main.rs b/core/src/components/identity/src/main.rs index 82a9d4a1..018a5ca7 100644 --- a/core/src/components/identity/src/main.rs +++ b/core/src/components/identity/src/main.rs @@ -4,12 +4,10 @@ * 1. TCP events tracker * 2. veth creation and deletion tracker * 3. TC (traffic control) tracker - * 4. [Experimental]: cgroup scanner * */ mod helpers; -mod service_discovery; use crate::helpers::{attach_and_register, get_veth_channels}; use aya::{ @@ -19,9 +17,6 @@ use aya::{ util::online_cpus, }; -#[cfg(feature = "experimental")] -use crate::helpers::scan_cgroup_cronjob; - use cortexbrain_common::{ buffer_type::BufferSize, constants, @@ -38,7 +33,6 @@ use std::{ path::Path, sync::{Arc, Mutex}, }; -#[cfg(not(feature = "experimental"))] use std::future::Future; use anyhow::{Context, Ok, anyhow}; @@ -372,7 +366,6 @@ fn start_event_consumers( ) } -#[cfg(not(feature = "experimental"))] enum ListenerExit { Veth(Result<(), tokio::task::JoinError>), Network(Result<(), tokio::task::JoinError>), @@ -380,7 +373,6 @@ enum ListenerExit { Shutdown, } -#[cfg(not(feature = "experimental"))] async fn wait_for_event_listener( veth: tokio::task::JoinHandle<()>, network: tokio::task::JoinHandle<()>, @@ -452,12 +444,6 @@ async fn event_listener(bpf_maps: BpfMapsData) -> Result<(), anyhow::Error> { }, ); - #[cfg(feature = "experimental")] - let scan_cgroup_cronjob = tokio::spawn(async move { - let _ = scan_cgroup_cronjob(180).await; - }); - - #[cfg(not(feature = "experimental"))] match wait_for_event_listener( veth_events_displayer, net_events_displayer, @@ -485,40 +471,6 @@ async fn event_listener(bpf_maps: BpfMapsData) -> Result<(), anyhow::Error> { info!("Triggered Exiting..."); } } - #[cfg(feature = "experimental")] - tokio::select! { - result = scan_cgroup_cronjob=>{ - match result{ - Err(e)=>error!("scan_cgroup_cronjob panicked {:?}",e), - std::result::Result::Ok(_) => info!("cgroup scan cronjob exited"), - } - } - result = veth_events_displayer=>{ - match result{ - Err(e)=>error!("veth_event_displayer panicked {:?}",e), - std::result::Result::Ok(_) => info!("Found new veth_event"), - } - } - - result = net_events_displayer=>{ - match result{ - Err(e)=>error!("net_event_displayer panicked {:?}",e), - std::result::Result::Ok(_) => info!("Found new net_event"), - } - } - - result = tcp_registry_events_displayer => { - match result{ - Err(e)=>error!("tcp_registry_events_displayer panicked {:?}",e), - std::result::Result::Ok(_)=>info!("Found new tcp_register event") - } - } - - _= signal::ctrl_c()=>{ - info!("Triggered Exiting..."); - } - - } Ok(()) } @@ -811,7 +763,6 @@ mod tests { assert_eq!(handles, ("veth", "network", "tcp")); } - #[cfg(not(feature = "experimental"))] #[tokio::test] async fn event_listener_observes_each_consumer_exit_and_shutdown() { for exit in ["veth", "network", "tcp", "shutdown"] { diff --git a/core/src/components/identity/src/mod.rs b/core/src/components/identity/src/mod.rs index ceaedc26..eadef2b9 100644 --- a/core/src/components/identity/src/mod.rs +++ b/core/src/components/identity/src/mod.rs @@ -1,3 +1 @@ -pub mod helpers; -#[cfg(feature = "experimental")] -pub mod service_discovery; \ No newline at end of file +pub mod helpers; \ No newline at end of file diff --git a/core/src/components/identity/src/service_discovery.rs b/core/src/components/identity/src/service_discovery.rs deleted file mode 100644 index bc43f3d7..00000000 --- a/core/src/components/identity/src/service_discovery.rs +++ /dev/null @@ -1,297 +0,0 @@ -#[cfg(feature = "experimental")] -use anyhow::Error; -#[cfg(feature = "experimental")] -use k8s_openapi::api::core::v1::Pod; -#[cfg(feature = "experimental")] -use kube::api::ObjectList; -#[cfg(feature = "experimental")] -use kube::{Api, Client}; -#[cfg(feature = "experimental")] -use std::fs; -#[cfg(feature = "experimental")] -use tokio::time; - -#[cfg(feature = "experimental")] -pub async fn scan_cgroup_paths(path: String) -> Result, Error> { - let mut cgroup_paths: Vec = Vec::new(); - let default_path = "/sys/fs/cgroup/kubepods.slice".to_string(); - - let target_path = if fs::metadata(&path).is_err() { - error!("Using default path: {}", &default_path); - default_path - } else { - path - }; - let entries = match fs::read_dir(&target_path) { - Ok(entries) => entries, - Err(e) => { - error!( - "Error reading cgroup directory {:?}: {}", - &target_path.clone(), - e - ); - return Ok(cgroup_paths); - } - }; - for entry in entries { - if let Ok(entry) = entry { - let path = entry.path(); - if path.is_dir() { - if let Some(path_str) = path.to_str() { - cgroup_paths.push(path_str.to_string()); - } - } - } - } - - Ok(cgroup_paths) -} - -#[cfg(feature = "experimental")] -struct ServiceIdentity { - uid: String, - container_id: String, -} - -#[cfg(feature = "experimental")] -pub async fn scan_cgroup_cronjob(time_delta: u64) -> Result<(), Error> { - let interval = std::time::Duration::from_secs(time_delta); - loop { - let scanned_paths = scan_cgroup_paths("/sys/fs/cgroup/kubelet.slice".to_string()) - .await - .expect("An error occured during the cgroup scan"); - //--> this should return : - // /sys/fs/cgroup/kubelet.slice/kubelet-kubepods.slice - // /sys/fs/cgroup/kubelet.slice/kubelet.service - let mut scanned_subpaths = Vec::::new(); - for path in scanned_paths { - //info!("Scanned cgroup path: {}", path); - // scan the subgroups - let subpaths = scan_cgroup_paths(path.to_string()).await; - match subpaths { - Ok(paths) => { - for subpath in paths { - scanned_subpaths.push(subpath); - } - // ---> this should return the cgroups files and also : - // kubelet-kubepods-burstable.slice - // kubelet-kubepods-besteffort.slice - - // this directories needs to be scanned again to get further information about the pods - // for example: - // kubelet-kubepods-besteffort-pod088f8704_24f0_4636_a8e2_13f75646f370.slice - // where pod088f8704_24f0_4636_a8e2_13f75646f370 is the pod UID - } - Err(e) => { - error!("An error occured during the cgroup subpath scan: {}", e); - continue; - } - } - } - - let mut scanned_subpaths_v2 = Vec::::new(); - // second cgroup scan level to get the pod UIDs - for scanned_subpath in &scanned_subpaths { - let subpaths_v2 = scan_cgroup_paths(scanned_subpath.to_string()).await; - match subpaths_v2 { - Ok(paths) => { - for sub2 in paths { - info!("Debugging sub2: {}", &sub2); //return e.g. /sys/fs/cgroup/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-podb8701d38_3791_422d_ad15_890ad1a0844b.slice/docker-f2e265659293676231ecb38fafccc97b1a42b75be192c32a602bc8ea579dc866.scope - scanned_subpaths_v2.push(sub2); - // this contains the addressed like this - //kubelet-kubepods-besteffort-pod088f8704_24f0_4636_a8e2_13f75646f370.slice - } - } - Err(e) => { - error!("An error occured during the cgroup subpath v2 scan: {}", e); - continue; - } - } - } - - let mut uids = Vec::::new(); - let mut identites = Vec::::new(); - - //read the subpaths to extract the pod uid - for subpath in scanned_subpaths_v2 { - let uid = extract_pod_uid(subpath.clone()) - .expect("An error occured during the extraction of pod UIDs"); - let container_id = extract_container_id(subpath.clone()) - .expect("An error occured during the extraction of the docker container id"); - debug!("Debugging extracted UID: {:?}", &uid); - // create a linked list for each service - let service_identity = ServiceIdentity { uid, container_id }; - identites.push(service_identity); //push the linked list in a vector of ServiceIdentity structure. Each struct contains the uid and the container id - } - - // get pod information from UID and store the info in an HashMqp for O(1) access - let service_map = get_pod_info().await?; - - //info!("Debugging Identites vector: {:?}", identites); - for service in identites { - let name = service_cache(service_map.clone(), service.uid.clone()); - let uid = service.uid; - let id = service.container_id; - info!( - "[Identity]: name: {:?} uid: {:?} docker container id {:?} ", - name, uid, id - ); - } - - info!( - "Cronjob completed a cgroup scan cycle. Next scan will be in {} seconds", - time_delta - ); - time::sleep(interval).await; - } -} -#[cfg(feature = "experimental")] -fn service_cache(service_map: HashMap, uid: String) -> String { - service_map.get(&uid).cloned().unwrap_or_else(|| { - error!("Service not found for uid: {}", uid); - "unknown".to_string() - }) -} -#[cfg(feature = "experimental")] -fn extract_container_id(cgroup_path: String) -> Result { - let splits: Vec<&str> = cgroup_path.split("/").collect(); - - let index = extract_target_from_splits(splits.clone(), "docker-")?; - let docker_id_split = splits[index] - .trim_start_matches("docker-") - .trim_end_matches(".scope"); - Ok(docker_id_split.to_string()) -} - -// IDEA: add cgroup docker process mapping in ServiceIdentity structure -#[cfg(feature = "experimental")] -fn extract_pod_uid(cgroup_path: String) -> Result { - // example of cgroup path: - // /sys/fs/cgroup/kubelet.slice/kubelet-kubepods.slice/kubelet-kubepods-besteffort.slice/kubelet-kubepods-besteffort-pod93580201_87d5_44e6_9779_f6153ca17637.slice - // or - // /sys/fs/cgroup/kubelet.slice/kubelet-kubepods.slice/kubelet-kubepods-burstable.slice/kubelet-kubepods-burstable-poddd3a1c6b_af40_41b1_8e1c_9e31fe8d96cb.slice - - // split the path by "/" - let splits: Vec<&str> = cgroup_path.split("/").collect(); - debug!("Debugging splits: {:?}", &splits); - - let index = extract_target_from_splits(splits.clone(), "-pod")?; - - let pod_split = splits[index] - .trim_start_matches("kubelet-kubepods-besteffort-") - .trim_start_matches("kubelet-kubepods-burstable-") - .trim_start_matches("kubepods-besteffort-") - .trim_start_matches("kubepods-burstable-"); - - let uid_ = pod_split - .trim_start_matches("pod") - .trim_end_matches(".slice"); //return uids with underscore (_) [ex.dd3a1c6b_af40_41b1_8e1c_9e31fe8d96cb] - - let uid = uid_.replace("_", "-"); - Ok(uid.to_string()) -} -#[cfg(feature = "experimental")] -fn extract_target_from_splits(splits: Vec<&str>, target: &str) -> Result { - for (index, split) in splits.iter().enumerate() { - // find the split that contains the word 'pod' - if split.contains(target) { - debug!("Target index; {}", index); - return Ok(index); - } - } - Err(Error::msg("'-pod' word not found in split")) -} - -/* unfortunately you cannot query the pods using the uids directly from ListParams */ -#[cfg(feature = "experimental")] -async fn query_all_pods() -> Result, Error> { - let client = Client::try_default() - .await - .expect("Cannot connect to kubernetes client"); - let pods: Api = Api::all(client); - let lp = kube::api::ListParams::default(); // default list params - let pod_list = pods - .list(&lp) - .await - .expect("An error occured during the pod list extraction"); - - Ok(pod_list) -} - -// fast pod caching system -#[cfg(feature = "experimental")] -async fn get_pod_info() -> Result, Error> { - let all_pods = query_all_pods().await?; - - let mut service_map = HashMap::::new(); - - for pod in all_pods { - if let (Some(name), Some(uid)) = (pod.metadata.name, pod.metadata.uid) { - service_map.insert(uid, name); - } - } // insert the pod name and uid from the KubeAPI - - Ok(service_map) -} - -#[cfg(feature = "experimental")] -mod tests { - use tracing_subscriber::fmt::format; - - use crate::helpers::{extract_container_id, extract_pod_uid, extract_target_from_splits}; - - #[test] - fn extract_uid_from_string() { - let cgroup_paths = vec!["/sys/fs/cgroup/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod231bd2d7_0f09_4781_a4e1_e4ea026342dd.slice".to_string(), - "/sys/fs/cgroup/kubelet.slice/kubelet-kubepods.slice/kubelet-kubepods-besteffort.slice/kubelet-kubepods-besteffort-pod231bd2d7_0f09_4781_a4e1_e4ea026342dd.slice".to_string()]; - - let mut uid_vec = Vec::::new(); - - for cgroup_path in cgroup_paths { - let uid = extract_pod_uid(cgroup_path) - .map_err(|e| format!("An error occured {}", e)) - .unwrap(); - uid_vec.push(uid); - } - - let check = vec![ - "231bd2d7-0f09-4781-a4e1-e4ea026342dd".to_string(), - "231bd2d7-0f09-4781-a4e1-e4ea026342dd".to_string(), - ]; - - assert_eq!(uid_vec, check); - } - - #[test] - fn test_extract_target_index() { - let cgroup_paths = vec!["/sys/fs/cgroup/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod231bd2d7_0f09_4781_a4e1_e4ea026342dd.slice".to_string(), - "/sys/fs/cgroup/kubelet.slice/kubelet-kubepods.slice/kubelet-kubepods-besteffort.slice/kubelet-kubepods-besteffort-pod231bd2d7_0f09_4781_a4e1_e4ea026342dd.slice".to_string()]; - - let mut index_vec = Vec::::new(); - for cgroup_path in cgroup_paths { - let splits: Vec<&str> = cgroup_path.split("/").collect(); - - let target_index = extract_target_from_splits(splits, "-pod").unwrap(); - index_vec.push(target_index); - } - let index_check = vec![6, 7]; - assert_eq!(index_vec, index_check); - } - - #[test] - fn extract_docker_id() { - let cgroup_paths = vec!["/sys/fs/cgroup/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod17fd3f7c_37e4_4009_8c38_e58b30691af3.slice/docker-13abd64c0ba349975a762476c9703b642d18077eabeb3aa1d941132048afc861.scope".to_string(), - "/sys/fs/cgroup/kubelet.slice/kubelet-kubepods.slice/kubelet-kubepods-besteffort.slice/kubelet-kubepods-besteffort-pod17fd3f7c_37e4_4009_8c38_e58b30691af3.slice/docker-13abd64c0ba349975a762476c9703b642d18077eabeb3aa1d941132048afc861.scope".to_string()]; - - let mut id_vec = Vec::::new(); - for cgroup_path in cgroup_paths { - let id = extract_container_id(cgroup_path).unwrap(); - id_vec.push(id); - } - let id_check = vec![ - "13abd64c0ba349975a762476c9703b642d18077eabeb3aa1d941132048afc861".to_string(), - "13abd64c0ba349975a762476c9703b642d18077eabeb3aa1d941132048afc861".to_string(), - ]; - assert_eq!(id_vec, id_check); - } -} From d219bc47570b31d03284361430184aae324eda67 Mon Sep 17 00:00:00 2001 From: LorenzoTettamanti Date: Mon, 23 Nov 2026 11:40:05 +0100 Subject: [PATCH 2/2] feat(identity): add OpenTelemetry connection metrics - share OTel metrics initialisation in cortexbrain-common - initialise metrics and service cache in the identity service - tag TCP events with direction and deduplicate flows by TTL - emit cortexbrain_identity_connections_total by direction --- Examples/run-with-docker/docker-compose.yaml | 46 +++-- cli/Cargo.lock | 2 - core/Cargo.lock | 31 +-- core/api/Cargo.toml | 2 +- core/common/Cargo.toml | 2 +- core/common/src/buffer_type.rs | 1 + core/common/src/constants.rs | 9 +- core/common/src/consumer.rs | 183 +++++++++++++++++- core/common/src/lib.rs | 1 + core/common/src/otel_init.rs | 122 ++++++++++++ core/common/src/otel_metrics.rs | 34 +++- core/common/src/semantic.rs | 5 + core/common/src/service_cache.rs | 73 +++---- core/common/tests/otel_metrics_contracts.rs | 30 +++ core/common/tests/public_contracts.rs | 1 + .../conntracker/src/data_structures.rs | 4 + core/src/components/conntracker/src/main.rs | 5 +- .../conntracker/src/tcp_analyzer.rs | 3 +- core/src/components/identity/Cargo.toml | 2 +- core/src/components/identity/src/main.rs | 154 +++++++++++---- core/src/components/metrics/src/helpers.rs | 2 +- core/src/components/metrics/src/otel_init.rs | 151 +-------------- helm/templates/configmap-role.yaml | 2 +- 23 files changed, 583 insertions(+), 282 deletions(-) create mode 100644 core/common/src/otel_init.rs diff --git a/Examples/run-with-docker/docker-compose.yaml b/Examples/run-with-docker/docker-compose.yaml index 167509c1..5d764873 100644 --- a/Examples/run-with-docker/docker-compose.yaml +++ b/Examples/run-with-docker/docker-compose.yaml @@ -28,26 +28,32 @@ services: networks: - cortexflow - #cortexflow-identity: - # image: lorenzotettamanti/cortexflow-identity:0.1.2 - # container_name: cortexflow-identity - # stop_signal: SIGINT - # restart: unless-stopped - # privileged: true - # pid: host - # init: true - # command: ["/usr/local/bin/cortexflow-identity-service"] - # volumes: - # - type: bind - # source: /sys/fs/bpf - # target: /sys/fs/bpf - # bind: - # propagation: shared - # - /lib/modules:/lib/modules:ro - # - /sys/kernel/debug:/sys/kernel/debug - # - /proc:/host/proc:ro - # networks: - # - cortexflow + cortexflow-identity: + image: lorenzotettamanti/cortexflow-identity:0.1.2 + container_name: cortexflow-identity + stop_signal: SIGINT + restart: unless-stopped + privileged: true + pid: host + init: true + command: ["/usr/local/bin/cortexflow-identity-service"] + environment: + - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 + - OTEL_EXPORTER_OTLP_PROTOCOL=grpc + - OTEL_SERVICE_NAME=cortexflow-identity + - OTEL_RESOURCE_ATTRIBUTES=service.namespace=cortexflow,service.version=0.1.5 + - DEFAULT_MAP_READING_TIME=100 + volumes: + - type: bind + source: /sys/fs/bpf + target: /sys/fs/bpf + bind: + propagation: shared + - /lib/modules:/lib/modules:ro + - /sys/kernel/debug:/sys/kernel/debug + - /proc:/host/proc:ro + networks: + - cortexflow otel-collector: image: otel/opentelemetry-collector-contrib:0.162.0 diff --git a/cli/Cargo.lock b/cli/Cargo.lock index 4c43dc7a..7f2666e9 100644 --- a/cli/Cargo.lock +++ b/cli/Cargo.lock @@ -427,8 +427,6 @@ checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" [[package]] name = "cortexbrain-common" version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a16980b59a1072feb4a503decf19a344b149e3a277b0ba0e5705fa4c8e7cf04" dependencies = [ "anyhow", "aya", diff --git a/core/Cargo.lock b/core/Cargo.lock index 5a137228..669b57f4 100644 --- a/core/Cargo.lock +++ b/core/Cargo.lock @@ -522,31 +522,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "cortexbrain-common" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a16980b59a1072feb4a503decf19a344b149e3a277b0ba0e5705fa4c8e7cf04" -dependencies = [ - "anyhow", - "aya 0.13.1", - "bytemuck", - "bytemuck_derive", - "bytes", - "k8s-openapi", - "kube", - "opentelemetry", - "opentelemetry-appender-tracing", - "opentelemetry-otlp", - "opentelemetry-stdout", - "opentelemetry_sdk", - "serde", - "serde_json", - "tokio", - "tracing", - "tracing-subscriber", -] - [[package]] name = "cortexflow-metrics" version = "0.1.1" @@ -556,7 +531,7 @@ dependencies = [ "aya-log", "bytemuck", "bytes", - "cortexbrain-common 0.1.4", + "cortexbrain-common", "libc", "nix 0.31.3", "opentelemetry", @@ -576,7 +551,7 @@ dependencies = [ "bytemuck", "bytemuck_derive", "chrono", - "cortexbrain-common 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "cortexbrain-common", "prost", "reqwest", "tokio", @@ -599,7 +574,7 @@ dependencies = [ "bytemuck", "bytemuck_derive", "bytes", - "cortexbrain-common 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "cortexbrain-common", "k8s-openapi", "kube", "nix 0.30.1", diff --git a/core/api/Cargo.toml b/core/api/Cargo.toml index 35b19681..4cb6985b 100644 --- a/core/api/Cargo.toml +++ b/core/api/Cargo.toml @@ -29,7 +29,7 @@ tonic = "0.14.0" tonic-prost = "0.14.0" tracing = "0.1.41" aya = "0.13.1" -cortexbrain-common = { version="0.1.4", features = [ +cortexbrain-common = { path="../common", features = [ "map-handlers", "network-structs", "buffer-reader", diff --git a/core/common/Cargo.toml b/core/common/Cargo.toml index 41405c05..e0b91f0e 100644 --- a/core/common/Cargo.toml +++ b/core/common/Cargo.toml @@ -28,7 +28,7 @@ opentelemetry = "0.32.0" opentelemetry_sdk = { version = "0.32.0", features = ["logs", "rt-tokio"] } opentelemetry-stdout = { version = "0.32.0", features = ["logs"] } opentelemetry-appender-tracing = "0.32.0" -opentelemetry-otlp = { version = "0.32.0", features = ["logs", "grpc-tonic"] } +opentelemetry-otlp = { version = "0.32.0", features = ["logs", "metrics", "grpc-tonic"] } bytemuck = "1.25.0" bytes = "1.12.1" bytemuck_derive = "1.10.2" diff --git a/core/common/src/buffer_type.rs b/core/common/src/buffer_type.rs index 7b41866e..e347ef37 100644 --- a/core/common/src/buffer_type.rs +++ b/core/common/src/buffer_type.rs @@ -89,6 +89,7 @@ pub struct TcpPacketRegistry { pub dst_port: u16, pub pid: u32, pub command: [u8; 16], + pub direction: u8, pub cgroup_id: u64, } #[cfg(feature = "network-structs")] diff --git a/core/common/src/constants.rs b/core/common/src/constants.rs index c656933c..e959ef5e 100644 --- a/core/common/src/constants.rs +++ b/core/common/src/constants.rs @@ -11,4 +11,11 @@ pub const PIN_MAP_PATH: &str = "PIN_MAP_PATH"; /// by searching the default system library directories. pub const LIBSSL_PATH: &str = "LIBSSL_PATH"; -pub const DEFAULT_MAP_READING_TIME : &str = "DEFAULT_MAP_READING_TIME"; +pub const DEFAULT_MAP_READING_TIME: &str = "DEFAULT_MAP_READING_TIME"; + +/// Direction of a connection observed by the identity service. +pub const CONNECTION_DIRECTION_INGRESS: u8 = 0; +pub const CONNECTION_DIRECTION_EGRESS: u8 = 1; + +/// Idle time after which a previously observed identity flow is considered new again. +pub const IDENTITY_FLOW_TTL_SECS: u64 = 300; diff --git a/core/common/src/consumer.rs b/core/common/src/consumer.rs index de83bc8c..269d6449 100644 --- a/core/common/src/consumer.rs +++ b/core/common/src/consumer.rs @@ -11,26 +11,102 @@ //! 3. Builds [`crate::metadata::Metadata`] (with optional Docker/K8s enrichment). //! 4. Records the observation through [`Metrics::record_*`]. +#[cfg(feature = "network-structs")] +use crate::buffer_type::{PacketLog, TcpPacketRegistry, VethLog}; #[cfg(feature = "monitoring-structs")] use crate::buffer_type::{ CpuFrequency, CpuIdle, MemAlloc, PacketLossMetrics, SchedStatRuntime, SchedStatWait, TimeStampMetrics, }; use crate::constants::DEFAULT_MAP_READING_TIME; -#[cfg(feature = "network-structs")] -use crate::buffer_type::{PacketLog, TcpPacketRegistry, VethLog}; #[cfg(feature = "monitoring-structs")] use crate::metadata::Metadata; #[cfg(feature = "monitoring-structs")] use crate::otel_metrics::Metrics; use crate::service_cache::ServiceCache; use bytes::BytesMut; +#[cfg(feature = "network-structs")] +use std::collections::HashMap; #[cfg(feature = "buffer-reader")] -use std::sync::Arc; +use std::sync::{Arc, Mutex}; +#[cfg(feature = "network-structs")] +use std::time::{Duration, Instant}; #[cfg(feature = "buffer-reader")] use tokio::sync::RwLock; use tracing::{error, info, warn}; +/// Key identifying a single directional flow observed by the identity service. +#[cfg(feature = "network-structs")] +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +struct IdentityFlowKey { + src_ip: u32, + dst_ip: u32, + src_port: u16, + dst_port: u16, + proto: u8, + direction: u8, +} + +/// Userspace tracker that de-duplicates identity flows for a configurable TTL. +/// +/// A flow is considered new when its 5-tuple (plus direction) has not been +/// observed for at least `ttl`. Active flows refresh their last-seen timestamp +/// on every observation. +#[cfg(feature = "network-structs")] +pub struct IdentityFlowTracker { + seen: HashMap, + ttl: Duration, + observations: u64, +} + +#[cfg(feature = "network-structs")] +impl IdentityFlowTracker { + pub fn new(ttl: Duration) -> Self { + Self { + seen: HashMap::new(), + ttl, + observations: 0, + } + } + + /// Returns `true` when the event starts a flow that was not observed + /// within the configured TTL. + pub fn observe(&mut self, event: &TcpPacketRegistry) -> bool { + self.observe_at(event, Instant::now()) + } + + fn observe_at(&mut self, event: &TcpPacketRegistry, now: Instant) -> bool { + self.observations = self.observations.wrapping_add(1); + if self.observations % 1024 == 0 { + self.evict_expired(now); + } + + let key = IdentityFlowKey { + src_ip: event.src_ip, + dst_ip: event.dst_ip, + src_port: event.src_port, + dst_port: event.dst_port, + proto: event.proto, + direction: event.direction, + }; + + if let Some(last_seen) = self.seen.get_mut(&key) { + if now.saturating_duration_since(*last_seen) < self.ttl { + *last_seen = now; + return false; + } + } + + self.seen.insert(key, now); + true + } + + fn evict_expired(&mut self, now: Instant) { + self.seen + .retain(|_, last_seen| now.saturating_duration_since(*last_seen) < self.ttl); + } +} + /// Discriminator for perf-buffer event types consumed by the collector. /// /// Each variant maps to an eBPF program output struct and a dedicated @@ -40,7 +116,9 @@ pub enum Consumer { #[cfg(feature = "network-structs")] PacketLog, #[cfg(feature = "network-structs")] - TcpPacketRegistry, + TcpPacketRegistry { + tracker: Arc>, + }, #[cfg(feature = "network-structs")] VethLog, #[cfg(feature = "monitoring-structs")] @@ -117,7 +195,15 @@ impl Consumer { /// Similar to [`read_packet_log`] but additionally prints the command name /// and cgroup ID extracted from the eBPF struct. #[cfg(feature = "network-structs")] - pub async fn read_tcp_registry_log(buffers: &mut [BytesMut], tot_events: i32, offset: i32) { + pub async fn read_tcp_registry_log( + buffers: &mut [BytesMut], + tot_events: i32, + offset: i32, + tracker: Arc>, + #[cfg(feature = "monitoring-structs")] exporter: &str, + #[cfg(feature = "monitoring-structs")] metrics: Arc, + #[cfg(feature = "monitoring-structs")] cache: Option>>, + ) { use crate::buffer_type::{IpProtocols, reverse_be_addr}; for i in offset..tot_events { @@ -164,6 +250,29 @@ impl Consumer { error!("Unknown protocol. Data maybe corrupted. Reason:{:?}", e); } } + + #[cfg(feature = "monitoring-structs")] + { + let is_new = tracker + .lock() + .map(|mut tracker| tracker.observe(&pl)) + .unwrap_or(false); + + if exporter == "otlp" && is_new { + let mut metadata = + Metadata::from_ebpf(Some(pl.pid), Some(pl.cgroup_id), &pl.command); + if let Some(cache) = &cache { + metadata.enrich(cache).await; + } + + metrics.record_identity_connection(pl.direction, &metadata); + } + } + + #[cfg(not(feature = "monitoring-structs"))] + { + let _ = &tracker; + } } } } @@ -763,6 +872,9 @@ pub async fn read_perf_buffer>( #[cfg(feature = "monitoring-structs")] metrics: Option>, cache: Option>>, ) { + #[cfg(not(feature = "monitoring-structs"))] + let _ = &cache; + loop { for buf in array_buffers.iter_mut() { match buf.read_events(&mut buffers) { @@ -781,9 +893,28 @@ pub async fn read_perf_buffer>( Consumer::read_packet_log(&mut buffers, tot_events, offset).await } #[cfg(feature = "network-structs")] - Consumer::TcpPacketRegistry => { - Consumer::read_tcp_registry_log(&mut buffers, tot_events, offset) - .await + Consumer::TcpPacketRegistry { ref tracker } => { + #[cfg(feature = "monitoring-structs")] + Consumer::read_tcp_registry_log( + &mut buffers, + tot_events, + offset, + tracker.clone(), + "otlp", + metrics + .clone() + .expect("Metrics required for TcpPacketRegistry"), + cache.clone(), + ) + .await; + #[cfg(not(feature = "monitoring-structs"))] + Consumer::read_tcp_registry_log( + &mut buffers, + tot_events, + offset, + tracker.clone(), + ) + .await; } #[cfg(feature = "network-structs")] Consumer::VethLog => { @@ -900,6 +1031,40 @@ pub async fn read_perf_buffer>( } } } - tokio::time::sleep(std::time::Duration::from_millis(std::env::var(DEFAULT_MAP_READING_TIME).ok().and_then(|v| v.parse::().ok()).unwrap_or(5000))).await; + tokio::time::sleep(std::time::Duration::from_millis( + std::env::var(DEFAULT_MAP_READING_TIME) + .ok() + .and_then(|v| v.parse::().ok()) + .unwrap_or(5000), + )) + .await; + } +} + +#[cfg(all(test, feature = "network-structs"))] +mod tests { + use super::*; + use bytemuck::Zeroable; + + fn event(src_port: u16, direction: u8) -> TcpPacketRegistry { + let mut event = TcpPacketRegistry::zeroed(); + event.src_ip = 1; + event.dst_ip = 2; + event.src_port = src_port; + event.dst_port = 3; + event.proto = 6; + event.direction = direction; + event + } + + #[test] + fn flow_tracker_deduplicates_until_the_ttl_expires() { + let mut tracker = IdentityFlowTracker::new(Duration::from_secs(60)); + let now = Instant::now(); + + assert!(tracker.observe_at(&event(100, 0), now)); + assert!(!tracker.observe_at(&event(100, 0), now + Duration::from_secs(1))); + assert!(tracker.observe_at(&event(100, 1), now + Duration::from_secs(1))); + assert!(tracker.observe_at(&event(100, 0), now + Duration::from_secs(61))); } } diff --git a/core/common/src/lib.rs b/core/common/src/lib.rs index 1ca47065..d6a09b0b 100644 --- a/core/common/src/lib.rs +++ b/core/common/src/lib.rs @@ -11,6 +11,7 @@ pub mod logger; pub mod map_handlers; #[cfg(feature = "monitoring-structs")] pub mod otel_metrics; +pub mod otel_init; #[cfg(feature = "program-handlers")] pub mod program_handlers; pub mod semantic; diff --git a/core/common/src/otel_init.rs b/core/common/src/otel_init.rs new file mode 100644 index 00000000..8bf5de78 --- /dev/null +++ b/core/common/src/otel_init.rs @@ -0,0 +1,122 @@ +//! Shared OpenTelemetry metrics initialisation. +//! +//! This module configures and bootstraps the OpenTelemetry SDK (OTel SDK) +//! for every CortexBrain service that exports metrics. Its goal is to expose +//! a [`Meter`] --- the primary entry-point for creating counters, gauges and +//! histograms --- backed by an OTLP metric exporter (gRPC or HTTP, depending +//! on configuration). +//! +//! `init_opentelemetry()` is invoked **once** per process, before any eBPF +//! program is loaded. The returned [`Meter`] is then passed to +//! [`crate::otel_metrics::Metrics::new`] and shared between the asynchronous +//! tasks that read eBPF perf-buffers. +//! +//! When the application exits, [`shutdown_opentelemetry`] flushes every +//! remaining aggregated metric to the OTLP collector before the process +//! terminates. + +use opentelemetry::global; +use opentelemetry::metrics::{Meter, MeterProvider}; +use opentelemetry_otlp::{MetricExporter, WithExportConfig}; +use opentelemetry_sdk::metrics::{PeriodicReader, SdkMeterProvider}; +use std::env; +use std::sync::OnceLock; +use std::time::Duration; + +/// Environment variable that holds the OTLP collector endpoint. +/// +/// Expected format: `"http://collector:4317"` for gRPC or `"http://collector:4318"` for HTTP. +pub const OTEL_EXPORTER_OTLP_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_ENDPOINT"; +pub const OTEL_EXPORTER_OTLP_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; + +/// Default OTLP endpoints used when [`OTEL_EXPORTER_OTLP_ENDPOINT`] is not +/// present in the environment. +pub const DEFAULT_OTLP_GRPC_ENDPOINT: &str = "http://localhost:4317"; +pub const DEFAULT_OTLP_HTTP_ENDPOINT: &str = "http://localhost:4318"; + +fn default_otlp_endpoint_from_protocol() -> &'static str { + match env::var(OTEL_EXPORTER_OTLP_PROTOCOL) + .ok() + .map(|value| value.to_ascii_lowercase()) + .as_deref() + { + Some("http/protobuf") | Some("http/json") => DEFAULT_OTLP_HTTP_ENDPOINT, + _ => DEFAULT_OTLP_GRPC_ENDPOINT, + } +} + +fn resolved_otlp_protocol() -> String { + env::var(OTEL_EXPORTER_OTLP_PROTOCOL) + .ok() + .map(|value| value.to_ascii_lowercase()) + .filter(|value| !value.trim().is_empty()) + .unwrap_or_else(|| "grpc".to_string()) +} + +/// Singleton that owns the concrete `SdkMeterProvider` instance. +/// +/// `OnceLock` guarantees single initialisation, avoiding accidentally creating +/// two providers (and two background export tasks) if `init_opentelemetry()` +/// were ever called twice. +static METER_PROVIDER: OnceLock = OnceLock::new(); + +/// Initialise the OpenTelemetry SDK, wire up the OTLP exporter, and return a +/// [`Meter`] registered under `meter_name`. +/// +/// 1. Read the endpoint from [`OTEL_EXPORTER_OTLP_ENDPOINT`] with the +/// protocol-aware defaults [`DEFAULT_OTLP_GRPC_ENDPOINT`] and +/// [`DEFAULT_OTLP_HTTP_ENDPOINT`]. +/// 2. Build a `MetricExporter` using the transport resolved by +/// `OTEL_EXPORTER_OTLP_PROTOCOL`. +/// 3. Wrap the exporter in a `PeriodicReader` that collects aggregated metrics +/// every 5 seconds and pushes them to the collector. +/// 4. Construct an `SdkMeterProvider` and register it as the global meter +/// provider. +/// 5. Keep a clone of the concrete provider in `METER_PROVIDER` so that +/// [`shutdown_opentelemetry`] can later call `SdkMeterProvider::shutdown()`. +/// 6. Create and return the `Meter` named `meter_name`. +pub fn init_opentelemetry(meter_name: &'static str) -> Result { + let endpoint = env::var(OTEL_EXPORTER_OTLP_ENDPOINT) + .unwrap_or_else(|_| default_otlp_endpoint_from_protocol().to_string()); + let protocol = resolved_otlp_protocol(); + + let exporter = match protocol.as_str() { + "http/protobuf" | "http/json" => MetricExporter::builder() + .with_http() + .with_endpoint(endpoint) + .with_timeout(Duration::from_secs(10)) + .build()?, + _ => MetricExporter::builder() + .with_tonic() + .with_endpoint(endpoint) + .with_timeout(Duration::from_secs(10)) + .build()?, + }; + + let reader = PeriodicReader::builder(exporter) + .with_interval(Duration::from_secs(5)) + .build(); + + let provider = SdkMeterProvider::builder().with_reader(reader).build(); + + // Make the provider globally discoverable. This clone is cheap because + // SdkMeterProvider is an Arc-backed handle. + global::set_meter_provider(provider.clone()); + + // Stash the concrete handle so shutdown_opentelemetry can flush. + METER_PROVIDER + .set(provider.clone()) + .map_err(|_| anyhow::anyhow!("OpenTelemetry meter provider already initialised"))?; + + let meter = provider.meter(meter_name); + Ok(meter) +} + +/// Flush every buffered metric to the OTLP collector and shut down the SDK. +pub fn shutdown_opentelemetry() { + if let Some(provider) = METER_PROVIDER.get() + && let Err(e) = provider.shutdown() + { + tracing::error!("Failed to shut down OpenTelemetry meter provider: {:?}", e); + } +} diff --git a/core/common/src/otel_metrics.rs b/core/common/src/otel_metrics.rs index 1680acef..013a63f7 100644 --- a/core/common/src/otel_metrics.rs +++ b/core/common/src/otel_metrics.rs @@ -14,6 +14,7 @@ use crate::buffer_type::{ CpuFrequency, CpuIdle, MemAlloc, PacketLossMetrics, SchedStatRuntime, SchedStatWait, SslEvent, TimeStampMetrics, }; +use crate::constants::{CONNECTION_DIRECTION_EGRESS, CONNECTION_DIRECTION_INGRESS}; use crate::metadata::Metadata; use crate::semantic::Semantic; use opentelemetry::KeyValue; @@ -67,9 +68,11 @@ pub struct Metrics { pub ssl_read_bytes: Gauge, pub ssl_write_bytes: Gauge, + + /// Unique connections detected by the identity service, partitioned by direction. + pub identity_connections_total: Counter, } -// TODO: add identity metrics with TC classifier packet counts // TODO: introduce a metric called total_tcp_packets total_udp_packets impl Metrics { /// Initialise all instruments backed by the supplied [`Meter`]. @@ -181,6 +184,11 @@ impl Metrics { .with_description(Semantic::SslWriteBytes.description()) .build(); + let identity_connections_total = meter + .u64_counter(Semantic::IdentityConnectionsTotal.title()) + .with_description(Semantic::IdentityConnectionsTotal.description()) + .build(); + Self { events_total, socket_events_total, @@ -198,6 +206,7 @@ impl Metrics { cpu_idle_state, ssl_read_bytes, ssl_write_bytes, + identity_connections_total, } } @@ -374,4 +383,27 @@ impl Metrics { self.events_total.add(1, &attrs); self.ssl_write_bytes.record(m.size as i64, &attrs); } + + /// Record a new unique connection observed by the identity service. + /// + /// The `direction` value follows the contract in + /// [`crate::constants::CONNECTION_DIRECTION_INGRESS`] and + /// [`crate::constants::CONNECTION_DIRECTION_EGRESS`]. + pub fn record_identity_connection(&self, direction: u8, metadata: &Metadata) { + let mut attrs = self.build_attrs(metadata); + + let direction = match direction { + CONNECTION_DIRECTION_INGRESS => "ingress", + CONNECTION_DIRECTION_EGRESS => "egress", + _ => "unknown", + }; + attrs.push(KeyValue::new("direction", direction)); + + debug!( + "Building attributes for identity connection metrics. Attributes: {:?}", + attrs + ); + + self.identity_connections_total.add(1, &attrs); + } } diff --git a/core/common/src/semantic.rs b/core/common/src/semantic.rs index 2536147c..ed3b2802 100644 --- a/core/common/src/semantic.rs +++ b/core/common/src/semantic.rs @@ -17,6 +17,7 @@ pub enum Semantic { CpuIdleState, SslReadBytes, SslWriteBytes, + IdentityConnectionsTotal, } impl Semantic { @@ -38,6 +39,7 @@ impl Semantic { Semantic::CpuIdleState => "cpu_idle_state", Semantic::SslReadBytes => "ssl_read_bytes", Semantic::SslWriteBytes => "ssl_write_bytes", + Semantic::IdentityConnectionsTotal => "cortexbrain_identity_connections_total", } } pub fn description(&self) -> &'static str { @@ -72,6 +74,9 @@ impl Semantic { } Semantic::SslReadBytes => "Total bytes requested by the ssl_read function", Semantic::SslWriteBytes => "Total bytes requested by the ssl_write function", + Semantic::IdentityConnectionsTotal => { + "Total number of unique connections detected by the identity service, partitioned by direction" + } } } } diff --git a/core/common/src/service_cache.rs b/core/common/src/service_cache.rs index 36106d61..bcb07c2e 100644 --- a/core/common/src/service_cache.rs +++ b/core/common/src/service_cache.rs @@ -5,7 +5,7 @@ use kube::{Api, Client}; use std::collections::HashMap; use tracing::debug; -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] pub struct ServiceCache { // service_map should maitain the Option Type. Since Option type can be also None // it's used to deal all the cases @@ -34,44 +34,48 @@ impl ServiceCache { let all_pods = self.query_all_pods_from_kubeapi().await?; debug!("Querying and updating all the pods"); + if let Some(map) = self.service_map.as_mut() { + map.clear(); + } for pod in all_pods { - if let (Some(name), Some(uid), Some(annotations), Some(namespace)) = ( - pod.metadata.name, - pod.metadata.uid, - pod.metadata.annotations, - pod.metadata.namespace, - ) { - // docs from kubernetes - // Annotations is an unstructured key value map stored with a resource that - // may be set by external tools to store and retrieve arbitrary metadata. - // They are not queryable and should be preserved when modifying objects. - //More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations + let (Some(name), Some(uid), Some(namespace)) = ( + pod.metadata.name.clone(), + pod.metadata.uid.clone(), + pod.metadata.namespace.clone(), + ) else { + continue; + }; + let annotations = pod.metadata.annotations.clone().unwrap_or_default(); + + // docs from kubernetes + // Annotations is an unstructured key value map stored with a resource that + // may be set by external tools to store and retrieve arbitrary metadata. + // They are not queryable and should be preserved when modifying objects. + //More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations - if let Some(map) = self.service_map.as_mut() { - // static pods are managed by the kubelet itself instead all the other pods - // are managed by controllers without the need of the API server - // the kubelet mirrors the static pods but the UID does not match the real signature of the pod (verified) - // so the algorithm check if the pod is static by checking if the annotations contains the word 'file' or 'http' - // reference for the labels: https://kubernetes.io/docs/reference/labels-annotations-taints/ - // and copies the config.hash (aka the signature of the static pod) into the service cache instead of the UID + if let Some(map) = self.service_map.as_mut() { + // static pods are managed by the kubelet itself instead all the other pods + // are managed by controllers without the need of the API server + // the kubelet mirrors the static pods but the UID does not match the real signature of the pod (verified) + // so the algorithm check if the pod is static by checking if the annotations contains the word 'file' or 'http' + // reference for the labels: https://kubernetes.io/docs/reference/labels-annotations-taints/ + // and copies the config.hash (aka the signature of the static pod) into the service cache instead of the UID - // more about static pods: https://medium.com/@iamsteffinissac/mastering-static-pods-in-kubernetes-bootstrapping-troubleshooting-mirror-pods-advanced-update-a35a5f95e329 + // more about static pods: https://medium.com/@iamsteffinissac/mastering-static-pods-in-kubernetes-bootstrapping-troubleshooting-mirror-pods-advanced-update-a35a5f95e329 - let is_static_pod = annotations - .get("kubernetes.io/config.source") - .is_some_and(|a| a == "file" || a == "http"); + let is_static_pod = annotations + .get("kubernetes.io/config.source") + .is_some_and(|a| a == "file" || a == "http"); - let key = if is_static_pod { - annotations - .get("kubernetes.io/config.hash") - .cloned() - .unwrap_or(uid) - } else { - uid - }; - let v = vec![name, namespace]; - map.insert(key, v); - } + let key = if is_static_pod { + annotations + .get("kubernetes.io/config.hash") + .cloned() + .unwrap_or(uid) + } else { + uid + }; + map.insert(key, vec![name, namespace]); } } // insert the pod name and uid from the KubeAPI } else { @@ -80,6 +84,7 @@ impl ServiceCache { Ok(()) } + pub async fn get_from_cache(&self, container_id: &str) -> Option<&Vec> { // pass a container_id and returns the object meta infos: /* pub struct ObjectMeta { diff --git a/core/common/tests/otel_metrics_contracts.rs b/core/common/tests/otel_metrics_contracts.rs index 78689957..390522c2 100644 --- a/core/common/tests/otel_metrics_contracts.rs +++ b/core/common/tests/otel_metrics_contracts.rs @@ -5,6 +5,7 @@ use cortexbrain_common::buffer_type::{ CpuFrequency, CpuIdle, MemAlloc, PacketLossMetrics, SchedStatRuntime, SchedStatWait, SslEvent, TimeStampMetrics, }; +use cortexbrain_common::constants::{CONNECTION_DIRECTION_EGRESS, CONNECTION_DIRECTION_INGRESS}; use cortexbrain_common::metadata::Metadata; use cortexbrain_common::otel_metrics::Metrics; use opentelemetry::KeyValue; @@ -204,3 +205,32 @@ fn cpu_idle_and_ssl_events_keep_their_dedicated_series() { point.value() == 2 && point.attributes().all(|attr| attr.key.as_str() != "cpu_id") })); } + +#[test] +fn identity_connections_are_prefixed_and_partitioned_by_direction() { + let metadata = Metadata::from_ebpf(Some(10), None, b"proxy"); + let snapshot = collect(|metrics| { + metrics.record_identity_connection(CONNECTION_DIRECTION_INGRESS, &metadata); + metrics.record_identity_connection(CONNECTION_DIRECTION_EGRESS, &metadata); + }); + + let AggregatedMetrics::U64(MetricData::Sum(sum)) = + metric(&snapshot, "cortexbrain_identity_connections_total").data() + else { + panic!("cortexbrain_identity_connections_total should be a u64 counter"); + }; + let points: Vec<_> = sum.data_points().collect(); + assert_eq!(points.len(), 2); + assert!(points.iter().any(|point| { + point.value() == 1 + && point + .attributes() + .any(|attr| attr == &KeyValue::new("direction", "ingress")) + })); + assert!(points.iter().any(|point| { + point.value() == 1 + && point + .attributes() + .any(|attr| attr == &KeyValue::new("direction", "egress")) + })); +} diff --git a/core/common/tests/public_contracts.rs b/core/common/tests/public_contracts.rs index 9afc3505..30f6d644 100644 --- a/core/common/tests/public_contracts.rs +++ b/core/common/tests/public_contracts.rs @@ -77,6 +77,7 @@ mod network_event_contracts { assert_eq!(offset_of!(TcpPacketRegistry, dst_port), 14); assert_eq!(offset_of!(TcpPacketRegistry, pid), 16); assert_eq!(offset_of!(TcpPacketRegistry, command), 20); + assert_eq!(offset_of!(TcpPacketRegistry, direction), 36); assert_eq!(offset_of!(TcpPacketRegistry, cgroup_id), 40); } } diff --git a/core/src/components/conntracker/src/data_structures.rs b/core/src/components/conntracker/src/data_structures.rs index c55cd3f4..62134052 100644 --- a/core/src/components/conntracker/src/data_structures.rs +++ b/core/src/components/conntracker/src/data_structures.rs @@ -58,6 +58,9 @@ pub struct VethLog { pub pid: u32, // 4 bytes: PID that triggered the event } +pub const DIRECTION_INGRESS: u8 = 0; +pub const DIRECTION_EGRESS: u8 = 1; + // TODO: write documentation about this structure #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -69,6 +72,7 @@ pub struct TcpPacketRegistry { pub dst_port: u16, pub pid: u32, pub command: [u8; 16], + pub direction: u8, pub cgroup_id: u64, } diff --git a/core/src/components/conntracker/src/main.rs b/core/src/components/conntracker/src/main.rs index 8438838f..a2673433 100644 --- a/core/src/components/conntracker/src/main.rs +++ b/core/src/components/conntracker/src/main.rs @@ -28,6 +28,7 @@ use aya_ebpf::{ programs::{ProbeContext, TcContext}, }; +use crate::data_structures::{DIRECTION_EGRESS, DIRECTION_INGRESS}; use crate::tc::try_identity_classifier; use crate::tcp_analyzer::try_tcp_analyzer; use crate::veth_tracer::try_veth_tracer; @@ -107,7 +108,7 @@ pub fn identity_classifier(ctx: TcContext) -> i32 { #[kprobe] pub fn tcp_message_tracer_connect(ctx: ProbeContext) -> u32 { - match try_tcp_analyzer(ctx) { + match try_tcp_analyzer(ctx, DIRECTION_EGRESS) { Ok(ret_val) => ret_val, Err(ret_val) => ret_val.try_into().unwrap_or(1), } @@ -115,7 +116,7 @@ pub fn tcp_message_tracer_connect(ctx: ProbeContext) -> u32 { #[kprobe] pub fn tcp_message_tracer_rcv(ctx: ProbeContext) -> u32 { - match try_tcp_analyzer(ctx) { + match try_tcp_analyzer(ctx, DIRECTION_INGRESS) { Ok(ret_val) => ret_val, Err(ret_val) => ret_val.try_into().unwrap_or(1), } diff --git a/core/src/components/conntracker/src/tcp_analyzer.rs b/core/src/components/conntracker/src/tcp_analyzer.rs index 9fe5d292..a6465b15 100644 --- a/core/src/components/conntracker/src/tcp_analyzer.rs +++ b/core/src/components/conntracker/src/tcp_analyzer.rs @@ -21,7 +21,7 @@ use crate::veth_tracer::{ read_linux_inner_struct, read_linux_inner_value }; // //in tcp_v4_recv skb->data -pub fn try_tcp_analyzer(ctx: ProbeContext) -> Result { +pub fn try_tcp_analyzer(ctx: ProbeContext, direction: u8) -> Result { let sk_buff_pointer: *const sk_buff = ctx.arg(0).ok_or(1i64)?; // first control: i'm, verifying that the pointer is not null if sk_buff_pointer.is_null() { @@ -72,6 +72,7 @@ pub fn try_tcp_analyzer(ctx: ProbeContext) -> Result { dst_port, pid, command, + direction, cgroup_id, }; unsafe { diff --git a/core/src/components/identity/Cargo.toml b/core/src/components/identity/Cargo.toml index 542cad6d..9fb125ad 100644 --- a/core/src/components/identity/Cargo.toml +++ b/core/src/components/identity/Cargo.toml @@ -27,7 +27,7 @@ tokio = { version = "1.48.0", features = [ ] } tracing = "0.1.41" bytemuck = { version = "1.23.0", features = ["derive"] } -cortexbrain-common = { version="0.1.4", features = [ +cortexbrain-common = { path="../../../common", features = [ "map-handlers", "program-handlers", "network-structs", diff --git a/core/src/components/identity/src/main.rs b/core/src/components/identity/src/main.rs index 018a5ca7..83817de5 100644 --- a/core/src/components/identity/src/main.rs +++ b/core/src/components/identity/src/main.rs @@ -20,26 +20,29 @@ use aya::{ use cortexbrain_common::{ buffer_type::BufferSize, constants, - consumer::Consumer, - consumer::read_perf_buffer, + consumer::{Consumer, IdentityFlowTracker, read_perf_buffer}, logger, map_handlers::BpfMapsData, map_handlers::{init_bpf_maps, map_manager, map_pinner, populate_blocklist}, + otel_init, + otel_metrics::Metrics, program_handlers::load_program, + service_cache::ServiceCache, }; +use std::future::Future; use std::{ collections::HashMap, convert::TryInto, path::Path, sync::{Arc, Mutex}, + time::Duration, }; -use std::future::Future; use anyhow::{Context, Ok, anyhow}; //use std::collections::HashMap; -use tokio::{fs, signal}; -use tracing::{error, info}; +use tokio::{fs, signal, sync::RwLock}; +use tracing::{error, info, warn}; // maps created by init_bpf_maps. event_listener requires veth_identity_map, events_map and TcpPacketRegistry const REQUIRED_MAPS: [&str; 5] = [ @@ -81,11 +84,18 @@ async fn main() -> Result<(), anyhow::Error> { info!("Starting identity service..."); info!("fetching data"); + let meter = otel_init::init_opentelemetry("identity") + .context("Failed to initialise OpenTelemetry metrics pipeline")?; + let metrics = Arc::new(Metrics::new(&meter)); + //init conntracker data path and bpf data let bpf = load_bpf_object(constants::BPF_PATH).await?; let pin_path = bpf_map_save_path(constants::PIN_MAP_PATH)?; - if run(bpf, pin_path, &IdentityOperations).await? == Outcome::MapsInitFailed { + let outcome = run(bpf, pin_path, &IdentityOperations, Some(metrics)).await; + otel_init::shutdown_opentelemetry(); + + if outcome? == Outcome::MapsInitFailed { let _ = signal::ctrl_c().await; let _ = otlp_provider.shutdown(); } @@ -113,7 +123,11 @@ trait StartupOperations { ifaces: Vec, ) -> Result<(), anyhow::Error>; async fn init_tcp(&self, bpf: Arc>) -> Result<(), anyhow::Error>; - async fn listen(&self, maps: BpfMapsData) -> Result<(), anyhow::Error>; + async fn listen( + &self, + maps: BpfMapsData, + metrics: Option>, + ) -> Result<(), anyhow::Error>; } struct IdentityOperations; @@ -159,8 +173,12 @@ impl StartupOperations for IdentityOperations { init_tcp_registry(bpf).await } - async fn listen(&self, maps: BpfMapsData) -> Result<(), anyhow::Error> { - event_listener(maps).await + async fn listen( + &self, + maps: BpfMapsData, + metrics: Option>, + ) -> Result<(), anyhow::Error> { + event_listener(maps, metrics).await } } @@ -168,6 +186,7 @@ async fn run( bpf: Arc>, pin_path: std::path::PathBuf, ops: &impl StartupOperations, + metrics: Option>, ) -> Result { let map_data = REQUIRED_MAPS.iter().map(|m| m.to_string()).collect(); match ops.init_maps(bpf.clone(), map_data) { @@ -201,7 +220,7 @@ async fn run( )?; } - ops.listen(maps).await.map_err(|e| { + ops.listen(maps, metrics).await.map_err(|e| { anyhow::anyhow!("Error inizializing event_listener. Reason: {}", e) })?; } @@ -355,6 +374,10 @@ fn start_event_consumers( tcp: T, mut start: impl FnMut(T, BufferSize, Consumer) -> H, ) -> (H, H, H) { + let flow_tracker = Arc::new(Mutex::new(IdentityFlowTracker::new(Duration::from_secs( + constants::IDENTITY_FLOW_TTL_SECS, + )))); + ( start(veth, BufferSize::VethEvents, Consumer::VethLog), start( @@ -362,7 +385,13 @@ fn start_event_consumers( BufferSize::ClassifierNetEvents, Consumer::PacketLog, ), - start(tcp, BufferSize::TcpEvents, Consumer::TcpPacketRegistry), + start( + tcp, + BufferSize::TcpEvents, + Consumer::TcpPacketRegistry { + tracker: flow_tracker, + }, + ), ) } @@ -394,7 +423,10 @@ async fn wait_for_event_listener( // perf_veth_array: contains is associated with the network events stored in the veth_map (veth_identity_map) // // -async fn event_listener(bpf_maps: BpfMapsData) -> Result<(), anyhow::Error> { +async fn event_listener( + bpf_maps: BpfMapsData, + metrics: Option>, +) -> Result<(), anyhow::Error> { info!("Preparing perf_buffers and perf_arrays"); //TODO: try to change from PerfEventArray to a RingBuffer data structure @@ -431,15 +463,39 @@ async fn event_listener(bpf_maps: BpfMapsData) -> Result<(), anyhow::Error> { (_tcp_registry_array, tcp_registry_buffers), ) = take_listener_maps(&mut maps)?; + let mut cache_obj = ServiceCache::default(); + cache_obj.init(); + if let Err(e) = cache_obj.populate_map_with_pod_info().await { + warn!("Service cache population failed: {}", e); + } + let cache = Arc::new(RwLock::new(cache_obj)); + + let cache_refresher = Arc::clone(&cache); + tokio::spawn(async move { + let mut interval = tokio::time::interval(Duration::from_secs(60)); + interval.tick().await; + loop { + interval.tick().await; + let mut cache_lock = cache_refresher.write().await; + if let Err(e) = cache_lock.populate_map_with_pod_info().await { + warn!("Service cache refresh failed: {}", e); + } + } + }); + + let consumer_metrics = metrics.clone(); + let consumer_cache = Arc::clone(&cache); let (veth_events_displayer, net_events_displayer, tcp_registry_events_displayer) = start_event_consumers( perf_veth_buffers, perf_net_events_buffers, tcp_registry_buffers, - |buffers, size, consumer| { + move |buffers, size, consumer| { let output = size.set_buffer(); + let metrics = consumer_metrics.clone(); + let cache = Arc::clone(&consumer_cache); tokio::spawn(async move { - read_perf_buffer(buffers, output, consumer, None, None).await; + read_perf_buffer(buffers, output, consumer, metrics, Some(cache)).await; }) }, ); @@ -674,8 +730,9 @@ mod tests { let maps = BpfMapsData { bpf_obj_names: vec![], bpf_obj_map: vec![], + bpf: empty_bpf().expect("minimal eBPF ELF should load"), }; - let err = event_listener(maps).await.unwrap_err(); + let err = event_listener(maps, None).await.unwrap_err(); assert!(err.to_string().contains("veth_identity_map")); } @@ -685,8 +742,9 @@ mod tests { let maps = BpfMapsData { bpf_obj_names: vec!["veth_identity_map".to_string()], bpf_obj_map: vec![], + bpf: empty_bpf().expect("minimal eBPF ELF should load"), }; - let err = event_listener(maps).await.unwrap_err(); + let err = event_listener(maps, None).await.unwrap_err(); assert!(err.to_string().contains("veth_identity_map")); } @@ -748,17 +806,18 @@ mod tests { #[test] fn event_listener_starts_consumers_with_matching_buffers() { let mut calls = Vec::new(); - let handles = start_event_consumers("veth", "network", "tcp", |buffers, size, consumer| { - let correct_pair = matches!( - (&size, &consumer), - (BufferSize::VethEvents, Consumer::VethLog) - | (BufferSize::ClassifierNetEvents, Consumer::PacketLog) - | (BufferSize::TcpEvents, Consumer::TcpPacketRegistry) - ); - assert!(correct_pair); - calls.push(buffers); - buffers - }); + let handles = + start_event_consumers("veth", "network", "tcp", |buffers, size, consumer| { + let correct_pair = matches!( + (&size, &consumer), + (BufferSize::VethEvents, Consumer::VethLog) + | (BufferSize::ClassifierNetEvents, Consumer::PacketLog) + | (BufferSize::TcpEvents, Consumer::TcpPacketRegistry { .. }) + ); + assert!(correct_pair); + calls.push(buffers); + buffers + }); assert_eq!(calls, ["veth", "network", "tcp"]); assert_eq!(handles, ("veth", "network", "tcp")); } @@ -822,7 +881,10 @@ mod tests { type Calls = std::cell::RefCell>; - fn recorder(calls: &Calls, fail_on: Option<&str>) -> impl Fn(Arc>, &str, &str) -> Result<(), anyhow::Error> { + fn recorder( + calls: &Calls, + fail_on: Option<&str>, + ) -> impl Fn(Arc>, &str, &str) -> Result<(), anyhow::Error> { let fail_on = fail_on.map(str::to_string); move |_, prog, sym| { calls.borrow_mut().push((prog.to_string(), sym.to_string())); @@ -837,12 +899,17 @@ mod tests { async fn init_veth_tracer_loads_both_programs_in_order() { let bpf = empty_bpf().expect("minimal eBPF ELF should load"); let calls = Calls::default(); - init_veth_tracer_with(bpf, recorder(&calls, None)).await.unwrap(); + init_veth_tracer_with(bpf, recorder(&calls, None)) + .await + .unwrap(); assert_eq!( *calls.borrow(), vec![ ("veth_creation_trace".into(), "register_netdevice".into()), - ("veth_deletion_trace".into(), "unregister_netdevice_queue".into()), + ( + "veth_deletion_trace".into(), + "unregister_netdevice_queue".into() + ), ] ); } @@ -873,7 +940,9 @@ mod tests { async fn init_tcp_registry_loads_both_programs_in_order() { let bpf = empty_bpf().expect("minimal eBPF ELF should load"); let calls = Calls::default(); - init_tcp_registry_with(bpf, recorder(&calls, None)).await.unwrap(); + init_tcp_registry_with(bpf, recorder(&calls, None)) + .await + .unwrap(); assert_eq!( *calls.borrow(), vec![ @@ -922,7 +991,10 @@ mod tests { let key = "CF_TEST_BPF_PATH_UNSET"; unsafe { std::env::remove_var(key) }; let err = load_bpf_object(key).await.err().unwrap(); - assert_eq!(err.to_string(), format!("{} environment variable required", key)); + assert_eq!( + err.to_string(), + format!("{} environment variable required", key) + ); } #[tokio::test] @@ -962,7 +1034,10 @@ mod tests { let key = "CF_TEST_PIN_PATH"; unsafe { std::env::remove_var(key) }; let err = bpf_map_save_path(key).unwrap_err(); - assert_eq!(err.to_string(), format!("{} environment variable required", key)); + assert_eq!( + err.to_string(), + format!("{} environment variable required", key) + ); unsafe { std::env::set_var(key, "/sys/fs/bpf/maps") }; assert_eq!( @@ -990,7 +1065,7 @@ mod tests { impl StartupOperations for MockStartup { fn init_maps( &self, - _: Arc>, + bpf: Arc>, names: Vec, ) -> Result { assert_eq!(names, REQUIRED_MAPS); @@ -998,6 +1073,7 @@ mod tests { Ok(BpfMapsData { bpf_obj_names: vec!["test_map".into()], bpf_obj_map: vec![], + bpf, }) } @@ -1038,7 +1114,11 @@ mod tests { self.step("tcp") } - async fn listen(&self, maps: BpfMapsData) -> Result<(), anyhow::Error> { + async fn listen( + &self, + maps: BpfMapsData, + _metrics: Option>, + ) -> Result<(), anyhow::Error> { assert_eq!(maps.bpf_obj_names, ["test_map"]); self.step("listen") } @@ -1052,7 +1132,7 @@ mod tests { }; let bpf = empty_bpf().expect("minimal eBPF ELF should load"); assert_eq!( - run(bpf, "/test/pin".into(), &ops).await.unwrap(), + run(bpf, "/test/pin".into(), &ops, None).await.unwrap(), Outcome::Finished ); assert_eq!( @@ -1092,7 +1172,7 @@ mod tests { fail_at: Some(stage), }; let bpf = empty_bpf().expect("minimal eBPF ELF should load"); - let result = run(bpf, "/test/pin".into(), &ops).await; + let result = run(bpf, "/test/pin".into(), &ops, None).await; match *stage { "init_maps" => assert_eq!(result.unwrap(), Outcome::MapsInitFailed), "pin_maps" => assert_eq!(result.unwrap(), Outcome::Finished), diff --git a/core/src/components/metrics/src/helpers.rs b/core/src/components/metrics/src/helpers.rs index 0023f400..4748af8e 100644 --- a/core/src/components/metrics/src/helpers.rs +++ b/core/src/components/metrics/src/helpers.rs @@ -77,7 +77,7 @@ pub async fn init_metrics_and_cache( ) -> Result<(Arc, Arc>), anyhow::Error> { let metrics = Arc::new(Metrics::new(meter)); - let mut cache_obj = ServiceCache { service_map: None }; + let mut cache_obj = ServiceCache::default(); cache_obj.init(); cache_obj.populate_map_with_pod_info().await?; let cache = Arc::new(tokio::sync::RwLock::new(cache_obj)); diff --git a/core/src/components/metrics/src/otel_init.rs b/core/src/components/metrics/src/otel_init.rs index 349c41b1..ff6be859 100644 --- a/core/src/components/metrics/src/otel_init.rs +++ b/core/src/components/metrics/src/otel_init.rs @@ -1,149 +1,16 @@ -//! docs -//! This module configures and bootstraps the OpenTelemetry SDK (OTel SDK) -//! within the `metrics` binary. Its goal is to expose a [`Meter`] --- the -//! primary entry-point for creating counters, gauges and histograms --- -//! backed by an OTLP metric exporter (gRPC or HTTP, depending on configuration). -//! -//! # Relationship to the rest of the crate -//! -//! `otel_init::init_opentelemetry()` is invoked **once** in [`main`], before -//! any eBPF program is loaded. The returned [`Meter`] is then passed through -//! the call chain into [`event_listener`](crate::helpers::event_listener) -//! where it is used by the async tasks that read eBPF perf-buffers. See -//! [`crate::helpers`] for the consumption side. -//! -//! When the application exits (either because `Ctrl-C` was received or because -//! an error bubbled up), [`shutdown_opentelemetry`] is called. This flushes -//! every remaining aggregated metric to the OTLP collector before the process -//! terminates. -//! +//! Thin wrapper around the shared OpenTelemetry metrics initialisation in +//! `cortexbrain-common`. The concrete implementation lives in +//! [`cortexbrain_common::otel_init`] so that every CortexBrain service uses the +//! same exporter configuration. -use opentelemetry::global; -use opentelemetry::metrics::{Meter, MeterProvider}; -use opentelemetry_otlp::{MetricExporter, WithExportConfig}; -use opentelemetry_sdk::metrics::{PeriodicReader, SdkMeterProvider}; -use std::env; -use std::sync::OnceLock; -use std::time::Duration; +use opentelemetry::metrics::Meter; -/// Environment variable that holds the OTLP collector endpoint. -/// -/// Expected format: `"http://collector:4317"` for gRPC or `"http://collector:4318"` for HTTP. -/// -pub const OTEL_EXPORTER_OTLP_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_ENDPOINT"; -pub const OTEL_EXPORTER_OTLP_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; - -/// Default OTLP endpoints used when [`OTEL_EXPORTER_OTLP_ENDPOINT`] is not -/// present in the environment. -/// -/// `DEFAULT_OTLP_GRPC_ENDPOINT` is selected for protocol `grpc` (or unknown), -/// while `DEFAULT_OTLP_HTTP_ENDPOINT` is selected for `http/protobuf` and -/// `http/json`. -pub const DEFAULT_OTLP_GRPC_ENDPOINT: &str = "http://localhost:4317"; -pub const DEFAULT_OTLP_HTTP_ENDPOINT: &str = "http://localhost:4318"; - -fn default_otlp_endpoint_from_protocol() -> &'static str { - match env::var(OTEL_EXPORTER_OTLP_PROTOCOL) - .ok() - .map(|value| value.to_ascii_lowercase()) - .as_deref() - { - Some("http/protobuf") | Some("http/json") => DEFAULT_OTLP_HTTP_ENDPOINT, - _ => DEFAULT_OTLP_GRPC_ENDPOINT, - } -} - -fn resolved_otlp_protocol() -> String { - env::var(OTEL_EXPORTER_OTLP_PROTOCOL) - .ok() - .map(|value| value.to_ascii_lowercase()) - .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| "grpc".to_string()) -} - -/// Singleton that owns the concrete `SdkMeterProvider` instance. -/// OnceLock guarantees single initialisation, we avoid accidentally creating two providers (and -/// two background export tasks) if `init_opentelemetry()` were ever called -/// twice. -/// -/// # Thread safety -/// -/// `OnceLock` is `Sync`, so the static can be read safely from any thread -/// or Tokio task once populated. -static METER_PROVIDER: OnceLock = OnceLock::new(); -/// docs: -/// Initialise the OpenTelemetry SDK, wire up the OTLP exporter, and -/// return a [`Meter`] ready for instrumenting the `metrics` crate. -/// -/// 1. Read the endpoint from [`OTEL_EXPORTER_OTLP_ENDPOINT`] with the -/// protocol-aware defaults [`DEFAULT_OTLP_GRPC_ENDPOINT`] and -/// [`DEFAULT_OTLP_HTTP_ENDPOINT`]. -/// 2. Build a `MetricExporter` using the transport resolved by -/// `OTEL_EXPORTER_OTLP_PROTOCOL`. -/// - `with_endpoint()` sets the target Collector URL. -/// - `with_timeout(Duration::from_secs(10))` caps each export RPC to 10 -/// seconds; if the Collector is unreachable the RPC aborts instead of -/// hanging indefinitely. -/// 3. Wrap the exporter in a `PeriodicReader`. The reader collects -/// aggregated metrics from every instrument every 5 seconds and hands -/// them to the exporter. This is the "push" model --- metrics leave the -/// process automatically without an external scraper. -/// 4. Construct an `SdkMeterProvider` and register it as the global -/// meter provider (`global::set_meter_provider`). The global handle is -/// needed for instrumenting code spawned in other Tokio tasks (see -/// [`helpers::event_listener`](crate::helpers::event_listener)). -/// 5. Keep a clone of the concrete provider in `METER_PROVIDER` so that -/// [`shutdown_opentelemetry`] can later call `SdkMeterProvider::shutdown()`. -/// 6. Create a `Meter named `"cortexbrain-metrics"` and return it. -/// -/// Potential causes of errors: -/// -/// * An invalid endpoint URL (malformed string). -/// * Network-level failure during exporter construction. -/// * The provider already having been initialised -/// +/// Initialise the OpenTelemetry metrics pipeline for the metrics service. pub fn init_opentelemetry() -> Result { - let endpoint = env::var(OTEL_EXPORTER_OTLP_ENDPOINT) - .unwrap_or_else(|_| default_otlp_endpoint_from_protocol().to_string()); - let protocol = resolved_otlp_protocol(); - - let exporter = match protocol.as_str() { - "http/protobuf" | "http/json" => MetricExporter::builder() - .with_http() - .with_endpoint(endpoint) - .with_timeout(Duration::from_secs(10)) - .build()?, - _ => MetricExporter::builder() - .with_tonic() - .with_endpoint(endpoint) - .with_timeout(Duration::from_secs(10)) - .build()?, - }; - - let reader = PeriodicReader::builder(exporter) - .with_interval(Duration::from_secs(5)) - .build(); - - let provider = SdkMeterProvider::builder().with_reader(reader).build(); - - // Make the provider globally discoverable. This clone is cheap because - // SdkMeterProvider is an Arc-backed handle. - global::set_meter_provider(provider.clone()); - - // Stash the concrete handle so shutdown_opentelemetry can flush. - METER_PROVIDER - .set(provider.clone()) - .map_err(|_| anyhow::anyhow!("OpenTelemetry meter provider already initialised"))?; - - let meter = provider.meter("cortexbrain-metrics"); - Ok(meter) + cortexbrain_common::otel_init::init_opentelemetry("cortexbrain-metrics") } -/// docs: + /// Flush every buffered metric to the OTLP collector and shut down the SDK. pub fn shutdown_opentelemetry() { - if let Some(provider) = METER_PROVIDER.get() - && let Err(e) = provider.shutdown() - { - tracing::error!("Failed to shut down OpenTelemetry meter provider: {:?}", e); - } + cortexbrain_common::otel_init::shutdown_opentelemetry() } diff --git a/helm/templates/configmap-role.yaml b/helm/templates/configmap-role.yaml index 70b4f76b..7718c4c1 100644 --- a/helm/templates/configmap-role.yaml +++ b/helm/templates/configmap-role.yaml @@ -4,7 +4,7 @@ metadata: name: configmap-reader rules: - apiGroups: [""] - resources: ["configmaps","services"] + resources: ["configmaps","services","pods"] verbs: ["get", "list","watch"] --- apiVersion: rbac.authorization.k8s.io/v1