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