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    pub async fn list_container_images(
131        &self,
132        params: ListContainerImagesOptionalParams,
133    ) -> Result<
134        crate::datadogV2::model::ContainerImagesResponse,
135        datadog::Error<ListContainerImagesError>,
136    > {
137        match self.list_container_images_with_http_info(params).await {
138            Ok(response_content) => {
139                if let Some(e) = response_content.entity {
140                    Ok(e)
141                } else {
142                    Err(datadog::Error::Serde(serde::de::Error::custom(
143                        "response content was None",
144                    )))
145                }
146            }
147            Err(err) => Err(err),
148        }
149    }
150
151    pub fn list_container_images_with_pagination(
152        &self,
153        mut params: ListContainerImagesOptionalParams,
154    ) -> impl Stream<
155        Item = Result<
156            crate::datadogV2::model::ContainerImageItem,
157            datadog::Error<ListContainerImagesError>,
158        >,
159    > + '_ {
160        try_stream! {
161            let mut page_size: i32 = 1000;
162            if params.page_size.is_none() {
163                params.page_size = Some(page_size);
164            } else {
165                page_size = params.page_size.unwrap().clone();
166            }
167            loop {
168                let resp = self.list_container_images(params.clone()).await?;
169                let Some(data) = resp.data else { break };
170
171                let r = data;
172                let count = r.len();
173                for team in r {
174                    yield team;
175                }
176
177                if count < page_size as usize {
178                    break;
179                }
180                let Some(meta) = resp.meta else { break };
181                let Some(pagination) = meta.pagination else { break };
182                let Some(next_cursor) = pagination.next_cursor else { break };
183
184                params.page_cursor = Some(next_cursor);
185            }
186        }
187    }
188
189    /// Get all Container Images for your organization.
190    pub async fn list_container_images_with_http_info(
191        &self,
192        params: ListContainerImagesOptionalParams,
193    ) -> Result<
194        datadog::ResponseContent<crate::datadogV2::model::ContainerImagesResponse>,
195        datadog::Error<ListContainerImagesError>,
196    > {
197        let local_configuration = &self.config;
198        let operation_id = "v2.list_container_images";
199
200        // unbox and build optional parameters
201        let filter_tags = params.filter_tags;
202        let group_by = params.group_by;
203        let sort = params.sort;
204        let page_size = params.page_size;
205        let page_cursor = params.page_cursor;
206
207        let local_client = &self.client;
208
209        let local_uri_str = format!(
210            "{}/api/v2/container_images",
211            local_configuration.get_operation_host(operation_id)
212        );
213        let mut local_req_builder =
214            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
215
216        if let Some(ref local_query_param) = filter_tags {
217            local_req_builder =
218                local_req_builder.query(&[("filter[tags]", &local_query_param.to_string())]);
219        };
220        if let Some(ref local_query_param) = group_by {
221            local_req_builder =
222                local_req_builder.query(&[("group_by", &local_query_param.to_string())]);
223        };
224        if let Some(ref local_query_param) = sort {
225            local_req_builder =
226                local_req_builder.query(&[("sort", &local_query_param.to_string())]);
227        };
228        if let Some(ref local_query_param) = page_size {
229            local_req_builder =
230                local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
231        };
232        if let Some(ref local_query_param) = page_cursor {
233            local_req_builder =
234                local_req_builder.query(&[("page[cursor]", &local_query_param.to_string())]);
235        };
236
237        // build headers
238        let mut headers = HeaderMap::new();
239        headers.insert("Accept", HeaderValue::from_static("application/json"));
240
241        // build user agent
242        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
243            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
244            Err(e) => {
245                log::warn!("Failed to parse user agent header: {e}, falling back to default");
246                headers.insert(
247                    reqwest::header::USER_AGENT,
248                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
249                )
250            }
251        };
252
253        // build auth
254        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
255            headers.insert(
256                "DD-API-KEY",
257                HeaderValue::from_str(local_key.key.as_str())
258                    .expect("failed to parse DD-API-KEY header"),
259            );
260        };
261        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
262            headers.insert(
263                "DD-APPLICATION-KEY",
264                HeaderValue::from_str(local_key.key.as_str())
265                    .expect("failed to parse DD-APPLICATION-KEY header"),
266            );
267        };
268
269        local_req_builder = local_req_builder.headers(headers);
270        let local_req = local_req_builder.build()?;
271        log::debug!("request content: {:?}", local_req.body());
272        let local_resp = local_client.execute(local_req).await?;
273
274        let local_status = local_resp.status();
275        let local_content = local_resp.text().await?;
276        log::debug!("response content: {}", local_content);
277
278        if !local_status.is_client_error() && !local_status.is_server_error() {
279            match serde_json::from_str::<crate::datadogV2::model::ContainerImagesResponse>(
280                &local_content,
281            ) {
282                Ok(e) => {
283                    return Ok(datadog::ResponseContent {
284                        status: local_status,
285                        content: local_content,
286                        entity: Some(e),
287                    })
288                }
289                Err(e) => return Err(datadog::Error::Serde(e)),
290            };
291        } else {
292            let local_entity: Option<ListContainerImagesError> =
293                serde_json::from_str(&local_content).ok();
294            let local_error = datadog::ResponseContent {
295                status: local_status,
296                content: local_content,
297                entity: local_entity,
298            };
299            Err(datadog::Error::ResponseError(local_error))
300        }
301    }
302}