Skip to main content

datadog_agent_commons/ipc/client/
agent_version.rs

1//! The version of the core Agent, from its command API.
2//!
3//! The command API serves REST endpoints on the same port as the gRPC IPC API, behind the same authentication: the
4//! bearer token and the IPC mTLS identity. The gRPC API has no version RPC, so the version comes from
5//! `GET /agent/version`, which returns the Agent's `version.Agent()`.
6
7use std::time::Duration;
8
9use bytes::Bytes;
10use http::{header, Request, StatusCode, Uri};
11use http_body_util::{BodyExt as _, Empty};
12use saluki_error::{generic_error, ErrorContext as _, GenericError};
13use saluki_io::net::client::http::HttpClient;
14use serde::Deserialize;
15
16use crate::ipc::{config::RemoteAgentClientConfiguration, tls::build_ipc_client_ipc_tls_config};
17
18const AGENT_VERSION_PATH: &str = "/agent/version";
19const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
20
21/// The version of the core Agent, as the running Agent reports it.
22///
23/// Unlike [`crate::agent_version`], which ADP was built against, this is the Agent ADP is running alongside.
24#[derive(Clone, Debug, Default, Eq, PartialEq)]
25pub struct RunningAgentVersion {
26    /// Version string, such as `7.81.0` or `7.81.0-devel+git.12.abcdef0`.
27    ///
28    /// This is the Agent's `version.RunningAgentVersion`, which the trace-agent, built alongside it, reports too.
29    pub version: String,
30
31    /// Short hash of the commit the Agent was built from.
32    pub commit: String,
33}
34
35/// The Agent's `version.Version`, as `/agent/version` serializes it.
36#[derive(Deserialize)]
37#[serde(rename_all = "PascalCase")]
38struct VersionResponse {
39    major: i64,
40    minor: i64,
41    patch: i64,
42    #[serde(default)]
43    pre: String,
44    #[serde(default)]
45    meta: String,
46    #[serde(default)]
47    commit: String,
48}
49
50impl From<VersionResponse> for RunningAgentVersion {
51    /// Rebuilds the version string the Agent parsed its version from: `MAJOR.MINOR.PATCH`, then `-PRE` and `+META`
52    /// when present.
53    fn from(response: VersionResponse) -> Self {
54        let mut version = format!("{}.{}.{}", response.major, response.minor, response.patch);
55        if !response.pre.is_empty() {
56            version.push('-');
57            version.push_str(&response.pre);
58        }
59        if !response.meta.is_empty() {
60            version.push('+');
61            version.push_str(&response.meta);
62        }
63        Self {
64            version,
65            commit: response.commit,
66        }
67    }
68}
69
70/// Fetches the version of the core Agent from its command API.
71///
72/// # Errors
73///
74/// If the authentication token or IPC certificate can't be read, the Agent can't be reached, or it answers with an
75/// error status or an unexpected body, an error is returned. The request isn't retried.
76pub async fn fetch_agent_version(config: &RemoteAgentClientConfiguration) -> Result<RunningAgentVersion, GenericError> {
77    let token_path = config.auth.auth_token_file_path();
78    let token = tokio::fs::read_to_string(token_path).await.with_error_context(|| {
79        format!(
80            "Failed to read the Agent authentication token from '{}'.",
81            token_path.display()
82        )
83    })?;
84    let tls_config = build_ipc_client_ipc_tls_config(config.auth.ipc_cert_file_path()).await?;
85
86    let builder = HttpClient::builder()
87        .with_client_tls_config(tls_config)
88        .with_request_timeout(REQUEST_TIMEOUT);
89    #[cfg(target_os = "linux")]
90    let builder = match config.vsock_addr() {
91        Some(addr) => builder.with_vsock_addr(addr),
92        None => builder,
93    };
94    let mut client = builder.build()?;
95
96    let request = version_request(&config.endpoint(), token.trim())?;
97    // The client's timeout ends once the headers arrive, so the body needs its own bound.
98    let (status, body) = tokio::time::timeout(REQUEST_TIMEOUT, async {
99        let response = client
100            .send(request)
101            .await
102            .error_context("Failed to query the Agent version.")?;
103        let status = response.status();
104        let body = response
105            .into_body()
106            .collect()
107            .await
108            .error_context("Failed to read the Agent version response.")?
109            .to_bytes();
110        Ok::<_, GenericError>((status, body))
111    })
112    .await
113    .map_err(|_| generic_error!("Timed out querying the Agent version after {REQUEST_TIMEOUT:?}."))??;
114    parse_version_response(status, &body)
115}
116
117/// Builds the `/agent/version` request for the command API at `endpoint`.
118fn version_request(endpoint: &Uri, token: &str) -> Result<Request<Empty<Bytes>>, GenericError> {
119    let uri = Uri::builder()
120        .scheme(endpoint.scheme_str().unwrap_or("https"))
121        .authority(
122            endpoint
123                .authority()
124                .ok_or_else(|| generic_error!("The Agent command API endpoint has no authority."))?
125                .clone(),
126        )
127        .path_and_query(AGENT_VERSION_PATH)
128        .build()
129        .error_context("Failed to build the Agent version URI.")?;
130
131    // Unlike the gRPC API, the command API only accepts the `Bearer` scheme spelled with a capital letter.
132    Request::get(uri)
133        .header(header::AUTHORIZATION, format!("Bearer {token}"))
134        .body(Empty::new())
135        .error_context("Failed to build the Agent version request.")
136}
137
138fn parse_version_response(status: StatusCode, body: &[u8]) -> Result<RunningAgentVersion, GenericError> {
139    if !status.is_success() {
140        return Err(generic_error!(
141            "The Agent answered the version request with status {status}."
142        ));
143    }
144    let response: VersionResponse =
145        serde_json::from_slice(body).error_context("The Agent version response is not a version.")?;
146    Ok(response.into())
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn the_version_string_is_rebuilt_from_its_parts() {
155        let cases = [
156            (
157                r#"{"Major":7,"Minor":81,"Patch":0,"Pre":"","Meta":"","Commit":"abc1234"}"#,
158                "7.81.0",
159            ),
160            (
161                r#"{"Major":7,"Minor":81,"Patch":0,"Pre":"rc.2","Meta":"","Commit":"abc1234"}"#,
162                "7.81.0-rc.2",
163            ),
164            (
165                r#"{"Major":7,"Minor":81,"Patch":0,"Pre":"devel","Meta":"git.12.abc1234","Commit":"abc1234"}"#,
166                "7.81.0-devel+git.12.abc1234",
167            ),
168        ];
169        for (body, version) in cases {
170            let parsed = parse_version_response(StatusCode::OK, body.as_bytes()).expect("version should parse");
171            assert_eq!(
172                parsed,
173                RunningAgentVersion {
174                    version: version.to_string(),
175                    commit: "abc1234".to_string(),
176                }
177            );
178        }
179    }
180
181    #[test]
182    fn an_error_status_or_unexpected_body_is_an_error() {
183        let body = br#"{"Major":7,"Minor":81,"Patch":0}"#;
184        assert!(parse_version_response(StatusCode::UNAUTHORIZED, body).is_err());
185        assert!(parse_version_response(StatusCode::OK, b"not json").is_err());
186        assert!(parse_version_response(StatusCode::OK, b"{}").is_err());
187    }
188
189    #[test]
190    fn the_request_targets_the_command_api_with_a_bearer_token() {
191        let endpoint: Uri = "https://127.0.0.1:5001".parse().unwrap();
192        let request = version_request(&endpoint, "token").expect("request should build");
193
194        assert_eq!(request.uri(), "https://127.0.0.1:5001/agent/version");
195        assert_eq!(request.headers()[header::AUTHORIZATION], "Bearer token");
196    }
197}