datadog_api_client/datadogV2/api/
api_container_images.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 async_stream::try_stream;
6use futures_core::stream::Stream;
7use reqwest::header::{HeaderMap, HeaderValue};
8use serde::{Deserialize, Serialize};
9
10/// ListContainerImagesOptionalParams is a struct for passing parameters to the method [`ContainerImagesAPI::list_container_images`]
11#[non_exhaustive]
12#[derive(Clone, Default, Debug)]
13pub struct ListContainerImagesOptionalParams {
14    /// Comma-separated list of tags to filter Container Images by.
15    pub filter_tags: Option<String>,
16    /// Comma-separated list of tags to group Container Images by.
17    pub group_by: Option<String>,
18    /// Attribute to sort Container Images by.
19    pub sort: Option<String>,
20    /// Maximum number of results returned.
21    pub page_size: Option<i32>,
22    /// String to query the next page of results.
23    /// This key is provided with each valid response from the API in `meta.pagination.next_cursor`.
24    pub page_cursor: Option<String>,
25}
26
27impl ListContainerImagesOptionalParams {
28    /// Comma-separated list of tags to filter Container Images by.
29    pub fn filter_tags(mut self, value: String) -> Self {
30        self.filter_tags = Some(value);
31        self
32    }
33    /// Comma-separated list of tags to group Container Images by.
34    pub fn group_by(mut self, value: String) -> Self {
35        self.group_by = Some(value);
36        self
37    }
38    /// Attribute to sort Container Images by.
39    pub fn sort(mut self, value: String) -> Self {
40        self.sort = Some(value);
41        self
42    }
43    /// Maximum number of results returned.
44    pub fn page_size(mut self, value: i32) -> Self {
45        self.page_size = Some(value);
46        self
47    }
48    /// String to query the next page of results.
49    /// This key is provided with each valid response from the API in `meta.pagination.next_cursor`.
50    pub fn page_cursor(mut self, value: String) -> Self {
51        self.page_cursor = Some(value);
52        self
53    }
54}
55
56/// ListContainerImagesError is a struct for typed errors of method [`ContainerImagesAPI::list_container_images`]
57#[derive(Debug, Clone, Serialize, Deserialize)]
58#[serde(untagged)]
59pub enum ListContainerImagesError {
60    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
61    UnknownValue(serde_json::Value),
62}
63
64/// The Container Images API allows you to query Container Image data for your organization. See the [Container Images View page](<https://docs.datadoghq.com/infrastructure/containers/container_images/>) for more information.
65#[derive(Debug, Clone)]
66pub struct ContainerImagesAPI {
67    config: datadog::Configuration,
68    client: reqwest_middleware::ClientWithMiddleware,
69}
70
71impl Default for ContainerImagesAPI {
72    fn default() -> Self {
73        Self::with_config(datadog::Configuration::default())
74    }
75}
76
77impl ContainerImagesAPI {
78    pub fn new() -> Self {
79        Self::default()
80    }
81    pub fn with_config(config: datadog::Configuration) -> Self {
82        let mut reqwest_client_builder = reqwest::Client::builder();
83
84        if let Some(proxy_url) = &config.proxy_url {
85            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
86            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
87        }
88
89        let mut middleware_client_builder =
90            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
91
92        if config.enable_retry {
93            struct RetryableStatus;
94            impl reqwest_retry::RetryableStrategy for RetryableStatus {
95                fn handle(
96                    &self,
97                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
98                ) -> Option<reqwest_retry::Retryable> {
99                    match res {
100                        Ok(success) => reqwest_retry::default_on_request_success(success),
101                        Err(_) => None,
102                    }
103                }
104            }
105            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
106                .build_with_max_retries(config.max_retries);
107
108            let retry_middleware =
109                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
110                    backoff_policy,
111                    RetryableStatus,
112                );
113
114            middleware_client_builder = middleware_client_builder.with(retry_middleware);
115        }
116
117        let client = middleware_client_builder.build();
118
119        Self { config, client }
120    }
121
122    pub fn with_client_and_config(
123        config: datadog::Configuration,
124        client: reqwest_middleware::ClientWithMiddleware,
125    ) -> Self {
126        Self { config, client }
127    }
128
129    /// Get all Container Images for your organization.
130    /// **Note**: To enrich the data returned by this endpoint with security scans, see the new [api/v2/security/scanned-assets-metadata](<https://docs.datadoghq.com/api/latest/security-monitoring/#list-scanned-assets-metadata>) endpoint.
131    pub async fn list_container_images(
132        &self,
133        params: ListContainerImagesOptionalParams,
134    ) -> Result<
135        crate::datadogV2::model::ContainerImagesResponse,
136        datadog::Error<ListContainerImagesError>,
137    > {
138        match self.list_container_images_with_http_info(params).await {
139            Ok(response_content) => {
140                if let Some(e) = response_content.entity {
141                    Ok(e)
142                } else {
143                    Err(datadog::Error::Serde(serde::de::Error::custom(
144                        "response content was None",
145                    )))
146                }
147            }
148            Err(err) => Err(err),
149        }
150    }
151
152    pub fn list_container_images_with_pagination(
153        &self,
154        mut params: ListContainerImagesOptionalParams,
155    ) -> impl Stream<
156        Item = Result<
157            crate::datadogV2::model::ContainerImageItem,
158            datadog::Error<ListContainerImagesError>,
159        >,
160    > + '_ {
161        try_stream! {
162            let mut page_size: i32 = 1000;
163            if params.page_size.is_none() {
164                params.page_size = Some(page_size);
165            } else {
166                page_size = params.page_size.unwrap().clone();
167            }
168            loop {
169                let resp = self.list_container_images(params.clone()).await?;
170                let Some(data) = resp.data else { break };
171
172                let r = data;
173                let count = r.len();
174                for team in r {
175                    yield team;
176                }
177
178                if count < page_size as usize {
179                    break;
180                }
181                let Some(meta) = resp.meta else { break };
182                let Some(pagination) = meta.pagination else { break };
183                let Some(next_cursor) = pagination.next_cursor else { break };
184
185                params.page_cursor = Some(next_cursor);
186            }
187        }
188    }
189
190    /// Get all Container Images for your organization.
191    /// **Note**: To enrich the data returned by this endpoint with security scans, see the new [api/v2/security/scanned-assets-metadata](<https://docs.datadoghq.com/api/latest/security-monitoring/#list-scanned-assets-metadata>) endpoint.
192    pub async fn list_container_images_with_http_info(
193        &self,
194        params: ListContainerImagesOptionalParams,
195    ) -> Result<
196        datadog::ResponseContent<crate::datadogV2::model::ContainerImagesResponse>,
197        datadog::Error<ListContainerImagesError>,
198    > {
199        let local_configuration = &self.config;
200        let operation_id = "v2.list_container_images";
201
202        // unbox and build optional parameters
203        let filter_tags = params.filter_tags;
204        let group_by = params.group_by;
205        let sort = params.sort;
206        let page_size = params.page_size;
207        let page_cursor = params.page_cursor;
208
209        let local_client = &self.client;
210
211        let local_uri_str = format!(
212            "{}/api/v2/container_images",
213            local_configuration.get_operation_host(operation_id)
214        );
215        let mut local_req_builder =
216            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
217
218        if let Some(ref local_query_param) = filter_tags {
219            local_req_builder =
220                local_req_builder.query(&[("filter[tags]", &local_query_param.to_string())]);
221        };
222        if let Some(ref local_query_param) = group_by {
223            local_req_builder =
224                local_req_builder.query(&[("group_by", &local_query_param.to_string())]);
225        };
226        if let Some(ref local_query_param) = sort {
227            local_req_builder =
228                local_req_builder.query(&[("sort", &local_query_param.to_string())]);
229        };
230        if let Some(ref local_query_param) = page_size {
231            local_req_builder =
232                local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
233        };
234        if let Some(ref local_query_param) = page_cursor {
235            local_req_builder =
236                local_req_builder.query(&[("page[cursor]", &local_query_param.to_string())]);
237        };
238
239        // build headers
240        let mut headers = HeaderMap::new();
241        headers.insert("Accept", HeaderValue::from_static("application/json"));
242
243        // build user agent
244        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
245            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
246            Err(e) => {
247                log::warn!("Failed to parse user agent header: {e}, falling back to default");
248                headers.insert(
249                    reqwest::header::USER_AGENT,
250                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
251                )
252            }
253        };
254
255        // build auth
256        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
257            headers.insert(
258                "DD-API-KEY",
259                HeaderValue::from_str(local_key.key.as_str())
260                    .expect("failed to parse DD-API-KEY header"),
261            );
262        };
263        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
264            headers.insert(
265                "DD-APPLICATION-KEY",
266                HeaderValue::from_str(local_key.key.as_str())
267                    .expect("failed to parse DD-APPLICATION-KEY header"),
268            );
269        };
270
271        local_req_builder = local_req_builder.headers(headers);
272        let local_req = local_req_builder.build()?;
273        log::debug!("request content: {:?}", local_req.body());
274        let local_resp = local_client.execute(local_req).await?;
275
276        let local_status = local_resp.status();
277        let local_content = local_resp.text().await?;
278        log::debug!("response content: {}", local_content);
279
280        if !local_status.is_client_error() && !local_status.is_server_error() {
281            match serde_json::from_str::<crate::datadogV2::model::ContainerImagesResponse>(
282                &local_content,
283            ) {
284                Ok(e) => {
285                    return Ok(datadog::ResponseContent {
286                        status: local_status,
287                        content: local_content,
288                        entity: Some(e),
289                    })
290                }
291                Err(e) => return Err(datadog::Error::Serde(e)),
292            };
293        } else {
294            let local_entity: Option<ListContainerImagesError> =
295                serde_json::from_str(&local_content).ok();
296            let local_error = datadog::ResponseContent {
297                status: local_status,
298                content: local_content,
299                entity: local_entity,
300            };
301            Err(datadog::Error::ResponseError(local_error))
302        }
303    }
304}