datadog_api_client/datadogV2/api/
api_csm_agents.rs

1// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
2// This product includes software developed at Datadog (https://www.datadoghq.com/).
3// Copyright 2019-Present Datadog, Inc.
4use crate::datadog;
5use reqwest::header::{HeaderMap, HeaderValue};
6use serde::{Deserialize, Serialize};
7
8/// ListAllCSMAgentsOptionalParams is a struct for passing parameters to the method [`CSMAgentsAPI::list_all_csm_agents`]
9#[non_exhaustive]
10#[derive(Clone, Default, Debug)]
11pub struct ListAllCSMAgentsOptionalParams {
12    /// The page index for pagination (zero-based).
13    pub page: Option<i32>,
14    /// The number of items to include in a single page.
15    pub size: Option<i32>,
16    /// A search query string to filter results (for example, `hostname:COMP-T2H4J27423`).
17    pub query: Option<String>,
18    /// The sort direction for results. Use `asc` for ascending or `desc` for descending.
19    pub order_direction: Option<crate::datadogV2::model::OrderDirection>,
20}
21
22impl ListAllCSMAgentsOptionalParams {
23    /// The page index for pagination (zero-based).
24    pub fn page(mut self, value: i32) -> Self {
25        self.page = Some(value);
26        self
27    }
28    /// The number of items to include in a single page.
29    pub fn size(mut self, value: i32) -> Self {
30        self.size = Some(value);
31        self
32    }
33    /// A search query string to filter results (for example, `hostname:COMP-T2H4J27423`).
34    pub fn query(mut self, value: String) -> Self {
35        self.query = Some(value);
36        self
37    }
38    /// The sort direction for results. Use `asc` for ascending or `desc` for descending.
39    pub fn order_direction(mut self, value: crate::datadogV2::model::OrderDirection) -> Self {
40        self.order_direction = Some(value);
41        self
42    }
43}
44
45/// ListAllCSMServerlessAgentsOptionalParams is a struct for passing parameters to the method [`CSMAgentsAPI::list_all_csm_serverless_agents`]
46#[non_exhaustive]
47#[derive(Clone, Default, Debug)]
48pub struct ListAllCSMServerlessAgentsOptionalParams {
49    /// The page index for pagination (zero-based).
50    pub page: Option<i32>,
51    /// The number of items to include in a single page.
52    pub size: Option<i32>,
53    /// A search query string to filter results (for example, `hostname:COMP-T2H4J27423`).
54    pub query: Option<String>,
55    /// The sort direction for results. Use `asc` for ascending or `desc` for descending.
56    pub order_direction: Option<crate::datadogV2::model::OrderDirection>,
57}
58
59impl ListAllCSMServerlessAgentsOptionalParams {
60    /// The page index for pagination (zero-based).
61    pub fn page(mut self, value: i32) -> Self {
62        self.page = Some(value);
63        self
64    }
65    /// The number of items to include in a single page.
66    pub fn size(mut self, value: i32) -> Self {
67        self.size = Some(value);
68        self
69    }
70    /// A search query string to filter results (for example, `hostname:COMP-T2H4J27423`).
71    pub fn query(mut self, value: String) -> Self {
72        self.query = Some(value);
73        self
74    }
75    /// The sort direction for results. Use `asc` for ascending or `desc` for descending.
76    pub fn order_direction(mut self, value: crate::datadogV2::model::OrderDirection) -> Self {
77        self.order_direction = Some(value);
78        self
79    }
80}
81
82/// ListAllCSMAgentsError is a struct for typed errors of method [`CSMAgentsAPI::list_all_csm_agents`]
83#[derive(Debug, Clone, Serialize, Deserialize)]
84#[serde(untagged)]
85pub enum ListAllCSMAgentsError {
86    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
87    UnknownValue(serde_json::Value),
88}
89
90/// ListAllCSMServerlessAgentsError is a struct for typed errors of method [`CSMAgentsAPI::list_all_csm_serverless_agents`]
91#[derive(Debug, Clone, Serialize, Deserialize)]
92#[serde(untagged)]
93pub enum ListAllCSMServerlessAgentsError {
94    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
95    UnknownValue(serde_json::Value),
96}
97
98/// Datadog Cloud Security Management (CSM) delivers real-time threat detection
99/// and continuous configuration audits across your entire cloud infrastructure,
100/// all in a unified view for seamless collaboration and faster remediation.
101/// Go to <https://docs.datadoghq.com/security/cloud_security_management> to learn more
102#[derive(Debug, Clone)]
103pub struct CSMAgentsAPI {
104    config: datadog::Configuration,
105    client: reqwest_middleware::ClientWithMiddleware,
106}
107
108impl Default for CSMAgentsAPI {
109    fn default() -> Self {
110        Self::with_config(datadog::Configuration::default())
111    }
112}
113
114impl CSMAgentsAPI {
115    pub fn new() -> Self {
116        Self::default()
117    }
118    pub fn with_config(config: datadog::Configuration) -> Self {
119        let mut reqwest_client_builder = reqwest::Client::builder();
120
121        if let Some(proxy_url) = &config.proxy_url {
122            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
123            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
124        }
125
126        let mut middleware_client_builder =
127            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
128
129        if config.enable_retry {
130            struct RetryableStatus;
131            impl reqwest_retry::RetryableStrategy for RetryableStatus {
132                fn handle(
133                    &self,
134                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
135                ) -> Option<reqwest_retry::Retryable> {
136                    match res {
137                        Ok(success) => reqwest_retry::default_on_request_success(success),
138                        Err(_) => None,
139                    }
140                }
141            }
142            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
143                .build_with_max_retries(config.max_retries);
144
145            let retry_middleware =
146                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
147                    backoff_policy,
148                    RetryableStatus,
149                );
150
151            middleware_client_builder = middleware_client_builder.with(retry_middleware);
152        }
153
154        let client = middleware_client_builder.build();
155
156        Self { config, client }
157    }
158
159    pub fn with_client_and_config(
160        config: datadog::Configuration,
161        client: reqwest_middleware::ClientWithMiddleware,
162    ) -> Self {
163        Self { config, client }
164    }
165
166    /// Get the list of all CSM Agents running on your hosts and containers.
167    pub async fn list_all_csm_agents(
168        &self,
169        params: ListAllCSMAgentsOptionalParams,
170    ) -> Result<crate::datadogV2::model::CsmAgentsResponse, datadog::Error<ListAllCSMAgentsError>>
171    {
172        match self.list_all_csm_agents_with_http_info(params).await {
173            Ok(response_content) => {
174                if let Some(e) = response_content.entity {
175                    Ok(e)
176                } else {
177                    Err(datadog::Error::Serde(serde::de::Error::custom(
178                        "response content was None",
179                    )))
180                }
181            }
182            Err(err) => Err(err),
183        }
184    }
185
186    /// Get the list of all CSM Agents running on your hosts and containers.
187    pub async fn list_all_csm_agents_with_http_info(
188        &self,
189        params: ListAllCSMAgentsOptionalParams,
190    ) -> Result<
191        datadog::ResponseContent<crate::datadogV2::model::CsmAgentsResponse>,
192        datadog::Error<ListAllCSMAgentsError>,
193    > {
194        let local_configuration = &self.config;
195        let operation_id = "v2.list_all_csm_agents";
196
197        // unbox and build optional parameters
198        let page = params.page;
199        let size = params.size;
200        let query = params.query;
201        let order_direction = params.order_direction;
202
203        let local_client = &self.client;
204
205        let local_uri_str = format!(
206            "{}/api/v2/csm/onboarding/agents",
207            local_configuration.get_operation_host(operation_id)
208        );
209        let mut local_req_builder =
210            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
211
212        if let Some(ref local_query_param) = page {
213            local_req_builder =
214                local_req_builder.query(&[("page", &local_query_param.to_string())]);
215        };
216        if let Some(ref local_query_param) = size {
217            local_req_builder =
218                local_req_builder.query(&[("size", &local_query_param.to_string())]);
219        };
220        if let Some(ref local_query_param) = query {
221            local_req_builder =
222                local_req_builder.query(&[("query", &local_query_param.to_string())]);
223        };
224        if let Some(ref local_query_param) = order_direction {
225            local_req_builder =
226                local_req_builder.query(&[("order_direction", &local_query_param.to_string())]);
227        };
228
229        // build headers
230        let mut headers = HeaderMap::new();
231        headers.insert("Accept", HeaderValue::from_static("application/json"));
232
233        // build user agent
234        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
235            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
236            Err(e) => {
237                log::warn!("Failed to parse user agent header: {e}, falling back to default");
238                headers.insert(
239                    reqwest::header::USER_AGENT,
240                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
241                )
242            }
243        };
244
245        // build auth
246        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
247            headers.insert(
248                "DD-API-KEY",
249                HeaderValue::from_str(local_key.key.as_str())
250                    .expect("failed to parse DD-API-KEY header"),
251            );
252        };
253        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
254            headers.insert(
255                "DD-APPLICATION-KEY",
256                HeaderValue::from_str(local_key.key.as_str())
257                    .expect("failed to parse DD-APPLICATION-KEY header"),
258            );
259        };
260
261        local_req_builder = local_req_builder.headers(headers);
262        let local_req = local_req_builder.build()?;
263        log::debug!("request content: {:?}", local_req.body());
264        let local_resp = local_client.execute(local_req).await?;
265
266        let local_status = local_resp.status();
267        let local_content = local_resp.text().await?;
268        log::debug!("response content: {}", local_content);
269
270        if !local_status.is_client_error() && !local_status.is_server_error() {
271            match serde_json::from_str::<crate::datadogV2::model::CsmAgentsResponse>(&local_content)
272            {
273                Ok(e) => {
274                    return Ok(datadog::ResponseContent {
275                        status: local_status,
276                        content: local_content,
277                        entity: Some(e),
278                    })
279                }
280                Err(e) => return Err(datadog::Error::Serde(e)),
281            };
282        } else {
283            let local_entity: Option<ListAllCSMAgentsError> =
284                serde_json::from_str(&local_content).ok();
285            let local_error = datadog::ResponseContent {
286                status: local_status,
287                content: local_content,
288                entity: local_entity,
289            };
290            Err(datadog::Error::ResponseError(local_error))
291        }
292    }
293
294    /// Get the list of all CSM Serverless Agents running on your hosts and containers.
295    pub async fn list_all_csm_serverless_agents(
296        &self,
297        params: ListAllCSMServerlessAgentsOptionalParams,
298    ) -> Result<
299        crate::datadogV2::model::CsmAgentsResponse,
300        datadog::Error<ListAllCSMServerlessAgentsError>,
301    > {
302        match self
303            .list_all_csm_serverless_agents_with_http_info(params)
304            .await
305        {
306            Ok(response_content) => {
307                if let Some(e) = response_content.entity {
308                    Ok(e)
309                } else {
310                    Err(datadog::Error::Serde(serde::de::Error::custom(
311                        "response content was None",
312                    )))
313                }
314            }
315            Err(err) => Err(err),
316        }
317    }
318
319    /// Get the list of all CSM Serverless Agents running on your hosts and containers.
320    pub async fn list_all_csm_serverless_agents_with_http_info(
321        &self,
322        params: ListAllCSMServerlessAgentsOptionalParams,
323    ) -> Result<
324        datadog::ResponseContent<crate::datadogV2::model::CsmAgentsResponse>,
325        datadog::Error<ListAllCSMServerlessAgentsError>,
326    > {
327        let local_configuration = &self.config;
328        let operation_id = "v2.list_all_csm_serverless_agents";
329
330        // unbox and build optional parameters
331        let page = params.page;
332        let size = params.size;
333        let query = params.query;
334        let order_direction = params.order_direction;
335
336        let local_client = &self.client;
337
338        let local_uri_str = format!(
339            "{}/api/v2/csm/onboarding/serverless/agents",
340            local_configuration.get_operation_host(operation_id)
341        );
342        let mut local_req_builder =
343            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
344
345        if let Some(ref local_query_param) = page {
346            local_req_builder =
347                local_req_builder.query(&[("page", &local_query_param.to_string())]);
348        };
349        if let Some(ref local_query_param) = size {
350            local_req_builder =
351                local_req_builder.query(&[("size", &local_query_param.to_string())]);
352        };
353        if let Some(ref local_query_param) = query {
354            local_req_builder =
355                local_req_builder.query(&[("query", &local_query_param.to_string())]);
356        };
357        if let Some(ref local_query_param) = order_direction {
358            local_req_builder =
359                local_req_builder.query(&[("order_direction", &local_query_param.to_string())]);
360        };
361
362        // build headers
363        let mut headers = HeaderMap::new();
364        headers.insert("Accept", HeaderValue::from_static("application/json"));
365
366        // build user agent
367        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
368            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
369            Err(e) => {
370                log::warn!("Failed to parse user agent header: {e}, falling back to default");
371                headers.insert(
372                    reqwest::header::USER_AGENT,
373                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
374                )
375            }
376        };
377
378        // build auth
379        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
380            headers.insert(
381                "DD-API-KEY",
382                HeaderValue::from_str(local_key.key.as_str())
383                    .expect("failed to parse DD-API-KEY header"),
384            );
385        };
386        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
387            headers.insert(
388                "DD-APPLICATION-KEY",
389                HeaderValue::from_str(local_key.key.as_str())
390                    .expect("failed to parse DD-APPLICATION-KEY header"),
391            );
392        };
393
394        local_req_builder = local_req_builder.headers(headers);
395        let local_req = local_req_builder.build()?;
396        log::debug!("request content: {:?}", local_req.body());
397        let local_resp = local_client.execute(local_req).await?;
398
399        let local_status = local_resp.status();
400        let local_content = local_resp.text().await?;
401        log::debug!("response content: {}", local_content);
402
403        if !local_status.is_client_error() && !local_status.is_server_error() {
404            match serde_json::from_str::<crate::datadogV2::model::CsmAgentsResponse>(&local_content)
405            {
406                Ok(e) => {
407                    return Ok(datadog::ResponseContent {
408                        status: local_status,
409                        content: local_content,
410                        entity: Some(e),
411                    })
412                }
413                Err(e) => return Err(datadog::Error::Serde(e)),
414            };
415        } else {
416            let local_entity: Option<ListAllCSMServerlessAgentsError> =
417                serde_json::from_str(&local_content).ok();
418            let local_error = datadog::ResponseContent {
419                status: local_status,
420                content: local_content,
421                entity: local_entity,
422            };
423            Err(datadog::Error::ResponseError(local_error))
424        }
425    }
426}