datadog_api_client/datadogV2/api/
api_cloud_network_monitoring.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/// GetAggregatedConnectionsOptionalParams is a struct for passing parameters to the method [`CloudNetworkMonitoringAPI::get_aggregated_connections`]
9#[non_exhaustive]
10#[derive(Clone, Default, Debug)]
11pub struct GetAggregatedConnectionsOptionalParams {
12    /// Unix timestamp (number of seconds since epoch) of the start of the query window. If not provided, the start of the query window is 15 minutes before the `to` timestamp. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
13    pub from: Option<i64>,
14    /// Unix timestamp (number of seconds since epoch) of the end of the query window. If not provided, the end of the query window is the current time. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
15    pub to: Option<i64>,
16    /// Comma-separated list of fields to group connections by. The maximum number of group_by(s) is 10.
17    pub group_by: Option<String>,
18    /// Comma-separated list of tags to filter connections by.
19    pub tags: Option<String>,
20    /// The number of connections to be returned. The maximum value is 7500. The default is 100.
21    pub limit: Option<i32>,
22}
23
24impl GetAggregatedConnectionsOptionalParams {
25    /// Unix timestamp (number of seconds since epoch) of the start of the query window. If not provided, the start of the query window is 15 minutes before the `to` timestamp. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
26    pub fn from(mut self, value: i64) -> Self {
27        self.from = Some(value);
28        self
29    }
30    /// Unix timestamp (number of seconds since epoch) of the end of the query window. If not provided, the end of the query window is the current time. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
31    pub fn to(mut self, value: i64) -> Self {
32        self.to = Some(value);
33        self
34    }
35    /// Comma-separated list of fields to group connections by. The maximum number of group_by(s) is 10.
36    pub fn group_by(mut self, value: String) -> Self {
37        self.group_by = Some(value);
38        self
39    }
40    /// Comma-separated list of tags to filter connections by.
41    pub fn tags(mut self, value: String) -> Self {
42        self.tags = Some(value);
43        self
44    }
45    /// The number of connections to be returned. The maximum value is 7500. The default is 100.
46    pub fn limit(mut self, value: i32) -> Self {
47        self.limit = Some(value);
48        self
49    }
50}
51
52/// GetAggregatedDnsOptionalParams is a struct for passing parameters to the method [`CloudNetworkMonitoringAPI::get_aggregated_dns`]
53#[non_exhaustive]
54#[derive(Clone, Default, Debug)]
55pub struct GetAggregatedDnsOptionalParams {
56    /// Unix timestamp (number of seconds since epoch) of the start of the query window. If not provided, the start of the query window is 15 minutes before the `to` timestamp. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
57    pub from: Option<i64>,
58    /// Unix timestamp (number of seconds since epoch) of the end of the query window. If not provided, the end of the query window is the current time. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
59    pub to: Option<i64>,
60    /// Comma-separated list of fields to group DNS traffic by. The server side defaults to `network.dns_query` if unspecified. `server_ungrouped` may be used if groups are not desired. The maximum number of group_by(s) is 10.
61    pub group_by: Option<String>,
62    /// Comma-separated list of tags to filter DNS traffic by.
63    pub tags: Option<String>,
64    /// The number of aggregated DNS entries to be returned. The maximum value is 7500. The default is 100.
65    pub limit: Option<i32>,
66}
67
68impl GetAggregatedDnsOptionalParams {
69    /// Unix timestamp (number of seconds since epoch) of the start of the query window. If not provided, the start of the query window is 15 minutes before the `to` timestamp. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
70    pub fn from(mut self, value: i64) -> Self {
71        self.from = Some(value);
72        self
73    }
74    /// Unix timestamp (number of seconds since epoch) of the end of the query window. If not provided, the end of the query window is the current time. If neither `from` nor `to` are provided, the query window is `[now - 15m, now]`.
75    pub fn to(mut self, value: i64) -> Self {
76        self.to = Some(value);
77        self
78    }
79    /// Comma-separated list of fields to group DNS traffic by. The server side defaults to `network.dns_query` if unspecified. `server_ungrouped` may be used if groups are not desired. The maximum number of group_by(s) is 10.
80    pub fn group_by(mut self, value: String) -> Self {
81        self.group_by = Some(value);
82        self
83    }
84    /// Comma-separated list of tags to filter DNS traffic by.
85    pub fn tags(mut self, value: String) -> Self {
86        self.tags = Some(value);
87        self
88    }
89    /// The number of aggregated DNS entries to be returned. The maximum value is 7500. The default is 100.
90    pub fn limit(mut self, value: i32) -> Self {
91        self.limit = Some(value);
92        self
93    }
94}
95
96/// GetAggregatedConnectionsError is a struct for typed errors of method [`CloudNetworkMonitoringAPI::get_aggregated_connections`]
97#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(untagged)]
99pub enum GetAggregatedConnectionsError {
100    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
101    UnknownValue(serde_json::Value),
102}
103
104/// GetAggregatedDnsError is a struct for typed errors of method [`CloudNetworkMonitoringAPI::get_aggregated_dns`]
105#[derive(Debug, Clone, Serialize, Deserialize)]
106#[serde(untagged)]
107pub enum GetAggregatedDnsError {
108    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
109    UnknownValue(serde_json::Value),
110}
111
112/// The Cloud Network Monitoring API allows you to fetch aggregated connections and DNS traffic with their attributes. See the [Cloud Network Monitoring page](<https://docs.datadoghq.com/network_monitoring/cloud_network_monitoring/>) and [DNS Monitoring page](<https://docs.datadoghq.com/network_monitoring/dns/>) for more information.
113#[derive(Debug, Clone)]
114pub struct CloudNetworkMonitoringAPI {
115    config: datadog::Configuration,
116    client: reqwest_middleware::ClientWithMiddleware,
117}
118
119impl Default for CloudNetworkMonitoringAPI {
120    fn default() -> Self {
121        Self::with_config(datadog::Configuration::default())
122    }
123}
124
125impl CloudNetworkMonitoringAPI {
126    pub fn new() -> Self {
127        Self::default()
128    }
129    pub fn with_config(config: datadog::Configuration) -> Self {
130        let mut reqwest_client_builder = reqwest::Client::builder();
131
132        if let Some(proxy_url) = &config.proxy_url {
133            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
134            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
135        }
136
137        let mut middleware_client_builder =
138            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
139
140        if config.enable_retry {
141            struct RetryableStatus;
142            impl reqwest_retry::RetryableStrategy for RetryableStatus {
143                fn handle(
144                    &self,
145                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
146                ) -> Option<reqwest_retry::Retryable> {
147                    match res {
148                        Ok(success) => reqwest_retry::default_on_request_success(success),
149                        Err(_) => None,
150                    }
151                }
152            }
153            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
154                .build_with_max_retries(config.max_retries);
155
156            let retry_middleware =
157                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
158                    backoff_policy,
159                    RetryableStatus,
160                );
161
162            middleware_client_builder = middleware_client_builder.with(retry_middleware);
163        }
164
165        let client = middleware_client_builder.build();
166
167        Self { config, client }
168    }
169
170    pub fn with_client_and_config(
171        config: datadog::Configuration,
172        client: reqwest_middleware::ClientWithMiddleware,
173    ) -> Self {
174        Self { config, client }
175    }
176
177    /// Get all aggregated connections.
178    pub async fn get_aggregated_connections(
179        &self,
180        params: GetAggregatedConnectionsOptionalParams,
181    ) -> Result<
182        crate::datadogV2::model::SingleAggregatedConnectionResponseArray,
183        datadog::Error<GetAggregatedConnectionsError>,
184    > {
185        match self.get_aggregated_connections_with_http_info(params).await {
186            Ok(response_content) => {
187                if let Some(e) = response_content.entity {
188                    Ok(e)
189                } else {
190                    Err(datadog::Error::Serde(serde::de::Error::custom(
191                        "response content was None",
192                    )))
193                }
194            }
195            Err(err) => Err(err),
196        }
197    }
198
199    /// Get all aggregated connections.
200    pub async fn get_aggregated_connections_with_http_info(
201        &self,
202        params: GetAggregatedConnectionsOptionalParams,
203    ) -> Result<
204        datadog::ResponseContent<crate::datadogV2::model::SingleAggregatedConnectionResponseArray>,
205        datadog::Error<GetAggregatedConnectionsError>,
206    > {
207        let local_configuration = &self.config;
208        let operation_id = "v2.get_aggregated_connections";
209
210        // unbox and build optional parameters
211        let from = params.from;
212        let to = params.to;
213        let group_by = params.group_by;
214        let tags = params.tags;
215        let limit = params.limit;
216
217        let local_client = &self.client;
218
219        let local_uri_str = format!(
220            "{}/api/v2/network/connections/aggregate",
221            local_configuration.get_operation_host(operation_id)
222        );
223        let mut local_req_builder =
224            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
225
226        if let Some(ref local_query_param) = from {
227            local_req_builder =
228                local_req_builder.query(&[("from", &local_query_param.to_string())]);
229        };
230        if let Some(ref local_query_param) = to {
231            local_req_builder = local_req_builder.query(&[("to", &local_query_param.to_string())]);
232        };
233        if let Some(ref local_query_param) = group_by {
234            local_req_builder =
235                local_req_builder.query(&[("group_by", &local_query_param.to_string())]);
236        };
237        if let Some(ref local_query_param) = tags {
238            local_req_builder =
239                local_req_builder.query(&[("tags", &local_query_param.to_string())]);
240        };
241        if let Some(ref local_query_param) = limit {
242            local_req_builder =
243                local_req_builder.query(&[("limit", &local_query_param.to_string())]);
244        };
245
246        // build headers
247        let mut headers = HeaderMap::new();
248        headers.insert("Accept", HeaderValue::from_static("application/json"));
249
250        // build user agent
251        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
252            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
253            Err(e) => {
254                log::warn!("Failed to parse user agent header: {e}, falling back to default");
255                headers.insert(
256                    reqwest::header::USER_AGENT,
257                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
258                )
259            }
260        };
261
262        // build auth
263        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
264            headers.insert(
265                "DD-API-KEY",
266                HeaderValue::from_str(local_key.key.as_str())
267                    .expect("failed to parse DD-API-KEY header"),
268            );
269        };
270        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
271            headers.insert(
272                "DD-APPLICATION-KEY",
273                HeaderValue::from_str(local_key.key.as_str())
274                    .expect("failed to parse DD-APPLICATION-KEY header"),
275            );
276        };
277
278        local_req_builder = local_req_builder.headers(headers);
279        let local_req = local_req_builder.build()?;
280        log::debug!("request content: {:?}", local_req.body());
281        let local_resp = local_client.execute(local_req).await?;
282
283        let local_status = local_resp.status();
284        let local_content = local_resp.text().await?;
285        log::debug!("response content: {}", local_content);
286
287        if !local_status.is_client_error() && !local_status.is_server_error() {
288            match serde_json::from_str::<
289                crate::datadogV2::model::SingleAggregatedConnectionResponseArray,
290            >(&local_content)
291            {
292                Ok(e) => {
293                    return Ok(datadog::ResponseContent {
294                        status: local_status,
295                        content: local_content,
296                        entity: Some(e),
297                    })
298                }
299                Err(e) => return Err(datadog::Error::Serde(e)),
300            };
301        } else {
302            let local_entity: Option<GetAggregatedConnectionsError> =
303                serde_json::from_str(&local_content).ok();
304            let local_error = datadog::ResponseContent {
305                status: local_status,
306                content: local_content,
307                entity: local_entity,
308            };
309            Err(datadog::Error::ResponseError(local_error))
310        }
311    }
312
313    /// Get all aggregated DNS traffic.
314    pub async fn get_aggregated_dns(
315        &self,
316        params: GetAggregatedDnsOptionalParams,
317    ) -> Result<
318        crate::datadogV2::model::SingleAggregatedDnsResponseArray,
319        datadog::Error<GetAggregatedDnsError>,
320    > {
321        match self.get_aggregated_dns_with_http_info(params).await {
322            Ok(response_content) => {
323                if let Some(e) = response_content.entity {
324                    Ok(e)
325                } else {
326                    Err(datadog::Error::Serde(serde::de::Error::custom(
327                        "response content was None",
328                    )))
329                }
330            }
331            Err(err) => Err(err),
332        }
333    }
334
335    /// Get all aggregated DNS traffic.
336    pub async fn get_aggregated_dns_with_http_info(
337        &self,
338        params: GetAggregatedDnsOptionalParams,
339    ) -> Result<
340        datadog::ResponseContent<crate::datadogV2::model::SingleAggregatedDnsResponseArray>,
341        datadog::Error<GetAggregatedDnsError>,
342    > {
343        let local_configuration = &self.config;
344        let operation_id = "v2.get_aggregated_dns";
345
346        // unbox and build optional parameters
347        let from = params.from;
348        let to = params.to;
349        let group_by = params.group_by;
350        let tags = params.tags;
351        let limit = params.limit;
352
353        let local_client = &self.client;
354
355        let local_uri_str = format!(
356            "{}/api/v2/network/dns/aggregate",
357            local_configuration.get_operation_host(operation_id)
358        );
359        let mut local_req_builder =
360            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
361
362        if let Some(ref local_query_param) = from {
363            local_req_builder =
364                local_req_builder.query(&[("from", &local_query_param.to_string())]);
365        };
366        if let Some(ref local_query_param) = to {
367            local_req_builder = local_req_builder.query(&[("to", &local_query_param.to_string())]);
368        };
369        if let Some(ref local_query_param) = group_by {
370            local_req_builder =
371                local_req_builder.query(&[("group_by", &local_query_param.to_string())]);
372        };
373        if let Some(ref local_query_param) = tags {
374            local_req_builder =
375                local_req_builder.query(&[("tags", &local_query_param.to_string())]);
376        };
377        if let Some(ref local_query_param) = limit {
378            local_req_builder =
379                local_req_builder.query(&[("limit", &local_query_param.to_string())]);
380        };
381
382        // build headers
383        let mut headers = HeaderMap::new();
384        headers.insert("Accept", HeaderValue::from_static("application/json"));
385
386        // build user agent
387        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
388            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
389            Err(e) => {
390                log::warn!("Failed to parse user agent header: {e}, falling back to default");
391                headers.insert(
392                    reqwest::header::USER_AGENT,
393                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
394                )
395            }
396        };
397
398        // build auth
399        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
400            headers.insert(
401                "DD-API-KEY",
402                HeaderValue::from_str(local_key.key.as_str())
403                    .expect("failed to parse DD-API-KEY header"),
404            );
405        };
406        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
407            headers.insert(
408                "DD-APPLICATION-KEY",
409                HeaderValue::from_str(local_key.key.as_str())
410                    .expect("failed to parse DD-APPLICATION-KEY header"),
411            );
412        };
413
414        local_req_builder = local_req_builder.headers(headers);
415        let local_req = local_req_builder.build()?;
416        log::debug!("request content: {:?}", local_req.body());
417        let local_resp = local_client.execute(local_req).await?;
418
419        let local_status = local_resp.status();
420        let local_content = local_resp.text().await?;
421        log::debug!("response content: {}", local_content);
422
423        if !local_status.is_client_error() && !local_status.is_server_error() {
424            match serde_json::from_str::<crate::datadogV2::model::SingleAggregatedDnsResponseArray>(
425                &local_content,
426            ) {
427                Ok(e) => {
428                    return Ok(datadog::ResponseContent {
429                        status: local_status,
430                        content: local_content,
431                        entity: Some(e),
432                    })
433                }
434                Err(e) => return Err(datadog::Error::Serde(e)),
435            };
436        } else {
437            let local_entity: Option<GetAggregatedDnsError> =
438                serde_json::from_str(&local_content).ok();
439            let local_error = datadog::ResponseContent {
440                status: local_status,
441                content: local_content,
442                entity: local_entity,
443            };
444            Err(datadog::Error::ResponseError(local_error))
445        }
446    }
447}