datadog_api_client/datadogV2/api/
api_aws_logs_integration.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/// ListAWSLogsServicesError is a struct for typed errors of method [`AWSLogsIntegrationAPI::list_aws_logs_services`]
9#[derive(Debug, Clone, Serialize, Deserialize)]
10#[serde(untagged)]
11pub enum ListAWSLogsServicesError {
12    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
13    UnknownValue(serde_json::Value),
14}
15
16/// Configure your Datadog-AWS-Logs integration directly through Datadog API.
17/// For more information, see the [AWS integration page](<https://docs.datadoghq.com/integrations/amazon_web_services/#log-collection>).
18#[derive(Debug, Clone)]
19pub struct AWSLogsIntegrationAPI {
20    config: datadog::Configuration,
21    client: reqwest_middleware::ClientWithMiddleware,
22}
23
24impl Default for AWSLogsIntegrationAPI {
25    fn default() -> Self {
26        Self::with_config(datadog::Configuration::default())
27    }
28}
29
30impl AWSLogsIntegrationAPI {
31    pub fn new() -> Self {
32        Self::default()
33    }
34    pub fn with_config(config: datadog::Configuration) -> Self {
35        let mut reqwest_client_builder = reqwest::Client::builder();
36
37        if let Some(proxy_url) = &config.proxy_url {
38            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
39            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
40        }
41
42        let mut middleware_client_builder =
43            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
44
45        if config.enable_retry {
46            struct RetryableStatus;
47            impl reqwest_retry::RetryableStrategy for RetryableStatus {
48                fn handle(
49                    &self,
50                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
51                ) -> Option<reqwest_retry::Retryable> {
52                    match res {
53                        Ok(success) => reqwest_retry::default_on_request_success(success),
54                        Err(_) => None,
55                    }
56                }
57            }
58            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
59                .build_with_max_retries(config.max_retries);
60
61            let retry_middleware =
62                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
63                    backoff_policy,
64                    RetryableStatus,
65                );
66
67            middleware_client_builder = middleware_client_builder.with(retry_middleware);
68        }
69
70        let client = middleware_client_builder.build();
71
72        Self { config, client }
73    }
74
75    pub fn with_client_and_config(
76        config: datadog::Configuration,
77        client: reqwest_middleware::ClientWithMiddleware,
78    ) -> Self {
79        Self { config, client }
80    }
81
82    /// Get a list of AWS services that can send logs to Datadog.
83    pub async fn list_aws_logs_services(
84        &self,
85    ) -> Result<
86        crate::datadogV2::model::AWSLogsServicesResponse,
87        datadog::Error<ListAWSLogsServicesError>,
88    > {
89        match self.list_aws_logs_services_with_http_info().await {
90            Ok(response_content) => {
91                if let Some(e) = response_content.entity {
92                    Ok(e)
93                } else {
94                    Err(datadog::Error::Serde(serde::de::Error::custom(
95                        "response content was None",
96                    )))
97                }
98            }
99            Err(err) => Err(err),
100        }
101    }
102
103    /// Get a list of AWS services that can send logs to Datadog.
104    pub async fn list_aws_logs_services_with_http_info(
105        &self,
106    ) -> Result<
107        datadog::ResponseContent<crate::datadogV2::model::AWSLogsServicesResponse>,
108        datadog::Error<ListAWSLogsServicesError>,
109    > {
110        let local_configuration = &self.config;
111        let operation_id = "v2.list_aws_logs_services";
112
113        let local_client = &self.client;
114
115        let local_uri_str = format!(
116            "{}/api/v2/integration/aws/logs/services",
117            local_configuration.get_operation_host(operation_id)
118        );
119        let mut local_req_builder =
120            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
121
122        // build headers
123        let mut headers = HeaderMap::new();
124        headers.insert("Accept", HeaderValue::from_static("application/json"));
125
126        // build user agent
127        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
128            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
129            Err(e) => {
130                log::warn!("Failed to parse user agent header: {e}, falling back to default");
131                headers.insert(
132                    reqwest::header::USER_AGENT,
133                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
134                )
135            }
136        };
137
138        // build auth
139        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
140            headers.insert(
141                "DD-API-KEY",
142                HeaderValue::from_str(local_key.key.as_str())
143                    .expect("failed to parse DD-API-KEY header"),
144            );
145        };
146        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
147            headers.insert(
148                "DD-APPLICATION-KEY",
149                HeaderValue::from_str(local_key.key.as_str())
150                    .expect("failed to parse DD-APPLICATION-KEY header"),
151            );
152        };
153
154        local_req_builder = local_req_builder.headers(headers);
155        let local_req = local_req_builder.build()?;
156        log::debug!("request content: {:?}", local_req.body());
157        let local_resp = local_client.execute(local_req).await?;
158
159        let local_status = local_resp.status();
160        let local_content = local_resp.text().await?;
161        log::debug!("response content: {}", local_content);
162
163        if !local_status.is_client_error() && !local_status.is_server_error() {
164            match serde_json::from_str::<crate::datadogV2::model::AWSLogsServicesResponse>(
165                &local_content,
166            ) {
167                Ok(e) => {
168                    return Ok(datadog::ResponseContent {
169                        status: local_status,
170                        content: local_content,
171                        entity: Some(e),
172                    })
173                }
174                Err(e) => return Err(datadog::Error::Serde(e)),
175            };
176        } else {
177            let local_entity: Option<ListAWSLogsServicesError> =
178                serde_json::from_str(&local_content).ok();
179            let local_error = datadog::ResponseContent {
180                status: local_status,
181                content: local_content,
182                entity: local_entity,
183            };
184            Err(datadog::Error::ResponseError(local_error))
185        }
186    }
187}