|
| 1 | +// Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/ |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +use crate::one_way_shared_memory::{open_named_shm, OneWayShmReader, OneWayShmWriter}; |
| 4 | +use crate::primary_sidecar_identifier; |
| 5 | +use base64::prelude::BASE64_URL_SAFE_NO_PAD; |
| 6 | +use base64::Engine; |
| 7 | +use data_pipeline::agent_info::schema::AgentInfoStruct; |
| 8 | +use data_pipeline::agent_info::{fetch_info_with_state, FetchInfoStatus}; |
| 9 | +use datadog_ipc::platform::NamedShmHandle; |
| 10 | +use ddcommon::Endpoint; |
| 11 | +use futures::future::Shared; |
| 12 | +use futures::FutureExt; |
| 13 | +use http::uri::PathAndQuery; |
| 14 | +use manual_future::ManualFuture; |
| 15 | +use std::ffi::CString; |
| 16 | +use std::hash::{Hash, Hasher}; |
| 17 | +use std::sync::{Arc, Mutex}; |
| 18 | +use std::time::{Duration, Instant}; |
| 19 | +use tokio::time::sleep; |
| 20 | +use tracing::{error, warn}; |
| 21 | +use zwohash::{HashMap, ZwoHasher}; |
| 22 | + |
| 23 | +#[derive(Default, Clone)] |
| 24 | +pub struct AgentInfos(Arc<Mutex<HashMap<Endpoint, AgentInfoFetcher>>>); |
| 25 | + |
| 26 | +impl AgentInfos { |
| 27 | + pub fn query_for(&self, endpoint: Endpoint) -> AgentInfoGuard { |
| 28 | + let mut infos_guard = self.0.lock().unwrap(); |
| 29 | + if let Some(info) = infos_guard.get_mut(&endpoint) { |
| 30 | + info.rc += 1; |
| 31 | + } else { |
| 32 | + infos_guard.insert( |
| 33 | + endpoint.clone(), |
| 34 | + AgentInfoFetcher::new(self.clone(), endpoint.clone()), |
| 35 | + ); |
| 36 | + } |
| 37 | + |
| 38 | + AgentInfoGuard { |
| 39 | + infos: self.clone(), |
| 40 | + endpoint, |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +pub struct AgentInfoGuard { |
| 46 | + infos: AgentInfos, |
| 47 | + endpoint: Endpoint, |
| 48 | +} |
| 49 | + |
| 50 | +impl AgentInfoGuard { |
| 51 | + pub fn get(&self) -> Shared<ManualFuture<AgentInfoStruct>> { |
| 52 | + let infos_guard = self.infos.0.lock().unwrap(); |
| 53 | + let infos = infos_guard.get(&self.endpoint).unwrap(); |
| 54 | + infos.infos.clone() |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl Drop for AgentInfoGuard { |
| 59 | + fn drop(&mut self) { |
| 60 | + let mut infos_guard = self.infos.0.lock().unwrap(); |
| 61 | + let info = infos_guard.get_mut(&self.endpoint).unwrap(); |
| 62 | + info.last_update = Instant::now(); |
| 63 | + info.rc -= 1; |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +pub struct AgentInfoFetcher { |
| 68 | + last_update: Instant, |
| 69 | + rc: u32, |
| 70 | + infos: Shared<ManualFuture<AgentInfoStruct>>, |
| 71 | +} |
| 72 | + |
| 73 | +impl AgentInfoFetcher { |
| 74 | + fn new(agent_infos: AgentInfos, endpoint: Endpoint) -> AgentInfoFetcher { |
| 75 | + let (future, completer) = ManualFuture::new(); |
| 76 | + tokio::spawn(async move { |
| 77 | + let mut state: Option<String> = None; |
| 78 | + let mut writer = None; |
| 79 | + let mut completer = Some(completer); |
| 80 | + let mut fetch_endpoint = endpoint.clone(); |
| 81 | + let mut parts = fetch_endpoint.url.into_parts(); |
| 82 | + parts.path_and_query = Some(PathAndQuery::from_static("/info")); |
| 83 | + fetch_endpoint.url = hyper::Uri::from_parts(parts).unwrap(); |
| 84 | + loop { |
| 85 | + let fetched = fetch_info_with_state(&fetch_endpoint, state.as_deref()).await; |
| 86 | + let mut complete_fut = None; |
| 87 | + { |
| 88 | + let mut infos_guard = agent_infos.0.lock().unwrap(); |
| 89 | + let infos = infos_guard.get_mut(&endpoint).unwrap(); |
| 90 | + if infos.rc == 0 && infos.last_update.elapsed().as_secs() > 60 { |
| 91 | + break; |
| 92 | + } |
| 93 | + match fetched { |
| 94 | + Ok(FetchInfoStatus::SameState) => {} |
| 95 | + Ok(FetchInfoStatus::NewState(status)) => { |
| 96 | + state = Some(status.state_hash); |
| 97 | + if writer.is_none() { |
| 98 | + writer = match OneWayShmWriter::<NamedShmHandle>::new(info_path( |
| 99 | + &endpoint, |
| 100 | + )) { |
| 101 | + Ok(writer) => Some(writer), |
| 102 | + Err(e) => { |
| 103 | + error!("Failed acquiring an agent info writer: {e:?}"); |
| 104 | + None |
| 105 | + } |
| 106 | + }; |
| 107 | + } |
| 108 | + if let Some(ref writer) = writer { |
| 109 | + writer.write(&serde_json::to_vec(&status.info).unwrap()) |
| 110 | + } |
| 111 | + if let Some(completer) = completer { |
| 112 | + complete_fut = Some(completer.complete(status.info)); |
| 113 | + } else { |
| 114 | + infos.infos = ManualFuture::new_completed(status.info).shared(); |
| 115 | + } |
| 116 | + completer = None; |
| 117 | + } |
| 118 | + Err(e) => { |
| 119 | + warn!( |
| 120 | + "The agent info for {} could not be fetched: {}", |
| 121 | + fetch_endpoint.url, e |
| 122 | + ); |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + if let Some(complete_fut) = complete_fut.take() { |
| 127 | + complete_fut.await; |
| 128 | + } |
| 129 | + sleep(Duration::from_secs(60)).await; |
| 130 | + } |
| 131 | + agent_infos.0.lock().unwrap().remove(&endpoint); |
| 132 | + }); |
| 133 | + |
| 134 | + AgentInfoFetcher { |
| 135 | + last_update: Instant::now(), |
| 136 | + rc: 1, |
| 137 | + infos: future.shared(), |
| 138 | + } |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +fn info_path(endpoint: &Endpoint) -> CString { |
| 143 | + let mut hasher = ZwoHasher::default(); |
| 144 | + endpoint.hash(&mut hasher); |
| 145 | + let mut path = format!( |
| 146 | + "/ddinf{}-{}", |
| 147 | + primary_sidecar_identifier(), |
| 148 | + BASE64_URL_SAFE_NO_PAD.encode(hasher.finish().to_ne_bytes()), |
| 149 | + ); |
| 150 | + // datadog agent info, on macos we're restricted to 31 chars |
| 151 | + path.truncate(31); // should not be larger than 31 chars, but be sure. |
| 152 | + CString::new(path).unwrap() |
| 153 | +} |
| 154 | + |
| 155 | +pub struct AgentInfoReader { |
| 156 | + reader: OneWayShmReader<NamedShmHandle, CString>, |
| 157 | + info: Option<AgentInfoStruct>, |
| 158 | +} |
| 159 | + |
| 160 | +impl AgentInfoReader { |
| 161 | + pub fn new(endpoint: &Endpoint) -> AgentInfoReader { |
| 162 | + let path = info_path(endpoint); |
| 163 | + AgentInfoReader { |
| 164 | + reader: OneWayShmReader::new(open_named_shm(&path).ok(), path), |
| 165 | + info: None, |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + pub fn read(&mut self) -> (bool, &Option<AgentInfoStruct>) { |
| 170 | + let (updated, data) = self.reader.read(); |
| 171 | + if updated { |
| 172 | + match serde_json::from_slice(data) { |
| 173 | + Ok(info) => self.info = Some(info), |
| 174 | + Err(e) => error!("Failed deserializing the agent info: {e:?}"), |
| 175 | + } |
| 176 | + } |
| 177 | + (updated, &self.info) |
| 178 | + } |
| 179 | +} |
0 commit comments