1use crate::datadog;
5use flate2::{
6 write::{GzEncoder, ZlibEncoder},
7 Compression,
8};
9use reqwest::header::{HeaderMap, HeaderValue};
10use serde::{Deserialize, Serialize};
11use std::io::Write;
12
13#[non_exhaustive]
15#[derive(Clone, Default, Debug)]
16pub struct GetHostTotalsOptionalParams {
17 pub from: Option<i64>,
19}
20
21impl GetHostTotalsOptionalParams {
22 pub fn from(mut self, value: i64) -> Self {
24 self.from = Some(value);
25 self
26 }
27}
28
29#[non_exhaustive]
31#[derive(Clone, Default, Debug)]
32pub struct ListHostsOptionalParams {
33 pub filter: Option<String>,
35 pub sort_field: Option<String>,
37 pub sort_dir: Option<String>,
39 pub start: Option<i64>,
41 pub count: Option<i64>,
43 pub from: Option<i64>,
45 pub include_muted_hosts_data: Option<bool>,
47 pub include_hosts_metadata: Option<bool>,
49}
50
51impl ListHostsOptionalParams {
52 pub fn filter(mut self, value: String) -> Self {
54 self.filter = Some(value);
55 self
56 }
57 pub fn sort_field(mut self, value: String) -> Self {
59 self.sort_field = Some(value);
60 self
61 }
62 pub fn sort_dir(mut self, value: String) -> Self {
64 self.sort_dir = Some(value);
65 self
66 }
67 pub fn start(mut self, value: i64) -> Self {
69 self.start = Some(value);
70 self
71 }
72 pub fn count(mut self, value: i64) -> Self {
74 self.count = Some(value);
75 self
76 }
77 pub fn from(mut self, value: i64) -> Self {
79 self.from = Some(value);
80 self
81 }
82 pub fn include_muted_hosts_data(mut self, value: bool) -> Self {
84 self.include_muted_hosts_data = Some(value);
85 self
86 }
87 pub fn include_hosts_metadata(mut self, value: bool) -> Self {
89 self.include_hosts_metadata = Some(value);
90 self
91 }
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
96#[serde(untagged)]
97pub enum GetHostTotalsError {
98 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
99 UnknownValue(serde_json::Value),
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize)]
104#[serde(untagged)]
105pub enum ListHostsError {
106 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
107 UnknownValue(serde_json::Value),
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
112#[serde(untagged)]
113pub enum MuteHostError {
114 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
115 UnknownValue(serde_json::Value),
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
120#[serde(untagged)]
121pub enum UnmuteHostError {
122 APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
123 UnknownValue(serde_json::Value),
124}
125
126#[derive(Debug, Clone)]
128pub struct HostsAPI {
129 config: datadog::Configuration,
130 client: reqwest_middleware::ClientWithMiddleware,
131}
132
133impl Default for HostsAPI {
134 fn default() -> Self {
135 Self::with_config(datadog::Configuration::default())
136 }
137}
138
139impl HostsAPI {
140 pub fn new() -> Self {
141 Self::default()
142 }
143 pub fn with_config(config: datadog::Configuration) -> Self {
144 let mut reqwest_client_builder = reqwest::Client::builder();
145
146 if let Some(proxy_url) = &config.proxy_url {
147 let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
148 reqwest_client_builder = reqwest_client_builder.proxy(proxy);
149 }
150
151 let mut middleware_client_builder =
152 reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
153
154 if config.enable_retry {
155 struct RetryableStatus;
156 impl reqwest_retry::RetryableStrategy for RetryableStatus {
157 fn handle(
158 &self,
159 res: &Result<reqwest::Response, reqwest_middleware::Error>,
160 ) -> Option<reqwest_retry::Retryable> {
161 match res {
162 Ok(success) => reqwest_retry::default_on_request_success(success),
163 Err(_) => None,
164 }
165 }
166 }
167 let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
168 .build_with_max_retries(config.max_retries);
169
170 let retry_middleware =
171 reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
172 backoff_policy,
173 RetryableStatus,
174 );
175
176 middleware_client_builder = middleware_client_builder.with(retry_middleware);
177 }
178
179 let client = middleware_client_builder.build();
180
181 Self { config, client }
182 }
183
184 pub fn with_client_and_config(
185 config: datadog::Configuration,
186 client: reqwest_middleware::ClientWithMiddleware,
187 ) -> Self {
188 Self { config, client }
189 }
190
191 pub async fn get_host_totals(
194 &self,
195 params: GetHostTotalsOptionalParams,
196 ) -> Result<crate::datadogV1::model::HostTotals, datadog::Error<GetHostTotalsError>> {
197 match self.get_host_totals_with_http_info(params).await {
198 Ok(response_content) => {
199 if let Some(e) = response_content.entity {
200 Ok(e)
201 } else {
202 Err(datadog::Error::Serde(serde::de::Error::custom(
203 "response content was None",
204 )))
205 }
206 }
207 Err(err) => Err(err),
208 }
209 }
210
211 pub async fn get_host_totals_with_http_info(
214 &self,
215 params: GetHostTotalsOptionalParams,
216 ) -> Result<
217 datadog::ResponseContent<crate::datadogV1::model::HostTotals>,
218 datadog::Error<GetHostTotalsError>,
219 > {
220 let local_configuration = &self.config;
221 let operation_id = "v1.get_host_totals";
222
223 let from = params.from;
225
226 let local_client = &self.client;
227
228 let local_uri_str = format!(
229 "{}/api/v1/hosts/totals",
230 local_configuration.get_operation_host(operation_id)
231 );
232 let mut local_req_builder =
233 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
234
235 if let Some(ref local_query_param) = from {
236 local_req_builder =
237 local_req_builder.query(&[("from", &local_query_param.to_string())]);
238 };
239
240 let mut headers = HeaderMap::new();
242 headers.insert("Accept", HeaderValue::from_static("application/json"));
243
244 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
246 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
247 Err(e) => {
248 log::warn!("Failed to parse user agent header: {e}, falling back to default");
249 headers.insert(
250 reqwest::header::USER_AGENT,
251 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
252 )
253 }
254 };
255
256 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
258 headers.insert(
259 "DD-API-KEY",
260 HeaderValue::from_str(local_key.key.as_str())
261 .expect("failed to parse DD-API-KEY header"),
262 );
263 };
264 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
265 headers.insert(
266 "DD-APPLICATION-KEY",
267 HeaderValue::from_str(local_key.key.as_str())
268 .expect("failed to parse DD-APPLICATION-KEY header"),
269 );
270 };
271
272 local_req_builder = local_req_builder.headers(headers);
273 let local_req = local_req_builder.build()?;
274 log::debug!("request content: {:?}", local_req.body());
275 let local_resp = local_client.execute(local_req).await?;
276
277 let local_status = local_resp.status();
278 let local_content = local_resp.text().await?;
279 log::debug!("response content: {}", local_content);
280
281 if !local_status.is_client_error() && !local_status.is_server_error() {
282 match serde_json::from_str::<crate::datadogV1::model::HostTotals>(&local_content) {
283 Ok(e) => {
284 return Ok(datadog::ResponseContent {
285 status: local_status,
286 content: local_content,
287 entity: Some(e),
288 })
289 }
290 Err(e) => return Err(datadog::Error::Serde(e)),
291 };
292 } else {
293 let local_entity: Option<GetHostTotalsError> =
294 serde_json::from_str(&local_content).ok();
295 let local_error = datadog::ResponseContent {
296 status: local_status,
297 content: local_content,
298 entity: local_entity,
299 };
300 Err(datadog::Error::ResponseError(local_error))
301 }
302 }
303
304 pub async fn list_hosts(
310 &self,
311 params: ListHostsOptionalParams,
312 ) -> Result<crate::datadogV1::model::HostListResponse, datadog::Error<ListHostsError>> {
313 match self.list_hosts_with_http_info(params).await {
314 Ok(response_content) => {
315 if let Some(e) = response_content.entity {
316 Ok(e)
317 } else {
318 Err(datadog::Error::Serde(serde::de::Error::custom(
319 "response content was None",
320 )))
321 }
322 }
323 Err(err) => Err(err),
324 }
325 }
326
327 pub async fn list_hosts_with_http_info(
333 &self,
334 params: ListHostsOptionalParams,
335 ) -> Result<
336 datadog::ResponseContent<crate::datadogV1::model::HostListResponse>,
337 datadog::Error<ListHostsError>,
338 > {
339 let local_configuration = &self.config;
340 let operation_id = "v1.list_hosts";
341
342 let filter = params.filter;
344 let sort_field = params.sort_field;
345 let sort_dir = params.sort_dir;
346 let start = params.start;
347 let count = params.count;
348 let from = params.from;
349 let include_muted_hosts_data = params.include_muted_hosts_data;
350 let include_hosts_metadata = params.include_hosts_metadata;
351
352 let local_client = &self.client;
353
354 let local_uri_str = format!(
355 "{}/api/v1/hosts",
356 local_configuration.get_operation_host(operation_id)
357 );
358 let mut local_req_builder =
359 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
360
361 if let Some(ref local_query_param) = filter {
362 local_req_builder =
363 local_req_builder.query(&[("filter", &local_query_param.to_string())]);
364 };
365 if let Some(ref local_query_param) = sort_field {
366 local_req_builder =
367 local_req_builder.query(&[("sort_field", &local_query_param.to_string())]);
368 };
369 if let Some(ref local_query_param) = sort_dir {
370 local_req_builder =
371 local_req_builder.query(&[("sort_dir", &local_query_param.to_string())]);
372 };
373 if let Some(ref local_query_param) = start {
374 local_req_builder =
375 local_req_builder.query(&[("start", &local_query_param.to_string())]);
376 };
377 if let Some(ref local_query_param) = count {
378 local_req_builder =
379 local_req_builder.query(&[("count", &local_query_param.to_string())]);
380 };
381 if let Some(ref local_query_param) = from {
382 local_req_builder =
383 local_req_builder.query(&[("from", &local_query_param.to_string())]);
384 };
385 if let Some(ref local_query_param) = include_muted_hosts_data {
386 local_req_builder = local_req_builder
387 .query(&[("include_muted_hosts_data", &local_query_param.to_string())]);
388 };
389 if let Some(ref local_query_param) = include_hosts_metadata {
390 local_req_builder = local_req_builder
391 .query(&[("include_hosts_metadata", &local_query_param.to_string())]);
392 };
393
394 let mut headers = HeaderMap::new();
396 headers.insert("Accept", HeaderValue::from_static("application/json"));
397
398 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
400 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
401 Err(e) => {
402 log::warn!("Failed to parse user agent header: {e}, falling back to default");
403 headers.insert(
404 reqwest::header::USER_AGENT,
405 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
406 )
407 }
408 };
409
410 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
412 headers.insert(
413 "DD-API-KEY",
414 HeaderValue::from_str(local_key.key.as_str())
415 .expect("failed to parse DD-API-KEY header"),
416 );
417 };
418 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
419 headers.insert(
420 "DD-APPLICATION-KEY",
421 HeaderValue::from_str(local_key.key.as_str())
422 .expect("failed to parse DD-APPLICATION-KEY header"),
423 );
424 };
425
426 local_req_builder = local_req_builder.headers(headers);
427 let local_req = local_req_builder.build()?;
428 log::debug!("request content: {:?}", local_req.body());
429 let local_resp = local_client.execute(local_req).await?;
430
431 let local_status = local_resp.status();
432 let local_content = local_resp.text().await?;
433 log::debug!("response content: {}", local_content);
434
435 if !local_status.is_client_error() && !local_status.is_server_error() {
436 match serde_json::from_str::<crate::datadogV1::model::HostListResponse>(&local_content)
437 {
438 Ok(e) => {
439 return Ok(datadog::ResponseContent {
440 status: local_status,
441 content: local_content,
442 entity: Some(e),
443 })
444 }
445 Err(e) => return Err(datadog::Error::Serde(e)),
446 };
447 } else {
448 let local_entity: Option<ListHostsError> = serde_json::from_str(&local_content).ok();
449 let local_error = datadog::ResponseContent {
450 status: local_status,
451 content: local_content,
452 entity: local_entity,
453 };
454 Err(datadog::Error::ResponseError(local_error))
455 }
456 }
457
458 pub async fn mute_host(
460 &self,
461 host_name: String,
462 body: crate::datadogV1::model::HostMuteSettings,
463 ) -> Result<crate::datadogV1::model::HostMuteResponse, datadog::Error<MuteHostError>> {
464 match self.mute_host_with_http_info(host_name, body).await {
465 Ok(response_content) => {
466 if let Some(e) = response_content.entity {
467 Ok(e)
468 } else {
469 Err(datadog::Error::Serde(serde::de::Error::custom(
470 "response content was None",
471 )))
472 }
473 }
474 Err(err) => Err(err),
475 }
476 }
477
478 pub async fn mute_host_with_http_info(
480 &self,
481 host_name: String,
482 body: crate::datadogV1::model::HostMuteSettings,
483 ) -> Result<
484 datadog::ResponseContent<crate::datadogV1::model::HostMuteResponse>,
485 datadog::Error<MuteHostError>,
486 > {
487 let local_configuration = &self.config;
488 let operation_id = "v1.mute_host";
489
490 let local_client = &self.client;
491
492 let local_uri_str = format!(
493 "{}/api/v1/host/{host_name}/mute",
494 local_configuration.get_operation_host(operation_id),
495 host_name = datadog::urlencode(host_name)
496 );
497 let mut local_req_builder =
498 local_client.request(reqwest::Method::POST, local_uri_str.as_str());
499
500 let mut headers = HeaderMap::new();
502 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
503 headers.insert("Accept", HeaderValue::from_static("application/json"));
504
505 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
507 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
508 Err(e) => {
509 log::warn!("Failed to parse user agent header: {e}, falling back to default");
510 headers.insert(
511 reqwest::header::USER_AGENT,
512 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
513 )
514 }
515 };
516
517 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
519 headers.insert(
520 "DD-API-KEY",
521 HeaderValue::from_str(local_key.key.as_str())
522 .expect("failed to parse DD-API-KEY header"),
523 );
524 };
525 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
526 headers.insert(
527 "DD-APPLICATION-KEY",
528 HeaderValue::from_str(local_key.key.as_str())
529 .expect("failed to parse DD-APPLICATION-KEY header"),
530 );
531 };
532
533 let output = Vec::new();
535 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
536 if body.serialize(&mut ser).is_ok() {
537 if let Some(content_encoding) = headers.get("Content-Encoding") {
538 match content_encoding.to_str().unwrap_or_default() {
539 "gzip" => {
540 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
541 let _ = enc.write_all(ser.into_inner().as_slice());
542 match enc.finish() {
543 Ok(buf) => {
544 local_req_builder = local_req_builder.body(buf);
545 }
546 Err(e) => return Err(datadog::Error::Io(e)),
547 }
548 }
549 "deflate" => {
550 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
551 let _ = enc.write_all(ser.into_inner().as_slice());
552 match enc.finish() {
553 Ok(buf) => {
554 local_req_builder = local_req_builder.body(buf);
555 }
556 Err(e) => return Err(datadog::Error::Io(e)),
557 }
558 }
559 "zstd1" => {
560 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
561 let _ = enc.write_all(ser.into_inner().as_slice());
562 match enc.finish() {
563 Ok(buf) => {
564 local_req_builder = local_req_builder.body(buf);
565 }
566 Err(e) => return Err(datadog::Error::Io(e)),
567 }
568 }
569 _ => {
570 local_req_builder = local_req_builder.body(ser.into_inner());
571 }
572 }
573 } else {
574 local_req_builder = local_req_builder.body(ser.into_inner());
575 }
576 }
577
578 local_req_builder = local_req_builder.headers(headers);
579 let local_req = local_req_builder.build()?;
580 log::debug!("request content: {:?}", local_req.body());
581 let local_resp = local_client.execute(local_req).await?;
582
583 let local_status = local_resp.status();
584 let local_content = local_resp.text().await?;
585 log::debug!("response content: {}", local_content);
586
587 if !local_status.is_client_error() && !local_status.is_server_error() {
588 match serde_json::from_str::<crate::datadogV1::model::HostMuteResponse>(&local_content)
589 {
590 Ok(e) => {
591 return Ok(datadog::ResponseContent {
592 status: local_status,
593 content: local_content,
594 entity: Some(e),
595 })
596 }
597 Err(e) => return Err(datadog::Error::Serde(e)),
598 };
599 } else {
600 let local_entity: Option<MuteHostError> = serde_json::from_str(&local_content).ok();
601 let local_error = datadog::ResponseContent {
602 status: local_status,
603 content: local_content,
604 entity: local_entity,
605 };
606 Err(datadog::Error::ResponseError(local_error))
607 }
608 }
609
610 pub async fn unmute_host(
612 &self,
613 host_name: String,
614 ) -> Result<crate::datadogV1::model::HostMuteResponse, datadog::Error<UnmuteHostError>> {
615 match self.unmute_host_with_http_info(host_name).await {
616 Ok(response_content) => {
617 if let Some(e) = response_content.entity {
618 Ok(e)
619 } else {
620 Err(datadog::Error::Serde(serde::de::Error::custom(
621 "response content was None",
622 )))
623 }
624 }
625 Err(err) => Err(err),
626 }
627 }
628
629 pub async fn unmute_host_with_http_info(
631 &self,
632 host_name: String,
633 ) -> Result<
634 datadog::ResponseContent<crate::datadogV1::model::HostMuteResponse>,
635 datadog::Error<UnmuteHostError>,
636 > {
637 let local_configuration = &self.config;
638 let operation_id = "v1.unmute_host";
639
640 let local_client = &self.client;
641
642 let local_uri_str = format!(
643 "{}/api/v1/host/{host_name}/unmute",
644 local_configuration.get_operation_host(operation_id),
645 host_name = datadog::urlencode(host_name)
646 );
647 let mut local_req_builder =
648 local_client.request(reqwest::Method::POST, local_uri_str.as_str());
649
650 let mut headers = HeaderMap::new();
652 headers.insert("Accept", HeaderValue::from_static("application/json"));
653
654 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
656 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
657 Err(e) => {
658 log::warn!("Failed to parse user agent header: {e}, falling back to default");
659 headers.insert(
660 reqwest::header::USER_AGENT,
661 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
662 )
663 }
664 };
665
666 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
668 headers.insert(
669 "DD-API-KEY",
670 HeaderValue::from_str(local_key.key.as_str())
671 .expect("failed to parse DD-API-KEY header"),
672 );
673 };
674 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
675 headers.insert(
676 "DD-APPLICATION-KEY",
677 HeaderValue::from_str(local_key.key.as_str())
678 .expect("failed to parse DD-APPLICATION-KEY header"),
679 );
680 };
681
682 local_req_builder = local_req_builder.headers(headers);
683 let local_req = local_req_builder.build()?;
684 log::debug!("request content: {:?}", local_req.body());
685 let local_resp = local_client.execute(local_req).await?;
686
687 let local_status = local_resp.status();
688 let local_content = local_resp.text().await?;
689 log::debug!("response content: {}", local_content);
690
691 if !local_status.is_client_error() && !local_status.is_server_error() {
692 match serde_json::from_str::<crate::datadogV1::model::HostMuteResponse>(&local_content)
693 {
694 Ok(e) => {
695 return Ok(datadog::ResponseContent {
696 status: local_status,
697 content: local_content,
698 entity: Some(e),
699 })
700 }
701 Err(e) => return Err(datadog::Error::Serde(e)),
702 };
703 } else {
704 let local_entity: Option<UnmuteHostError> = serde_json::from_str(&local_content).ok();
705 let local_error = datadog::ResponseContent {
706 status: local_status,
707 content: local_content,
708 entity: local_entity,
709 };
710 Err(datadog::Error::ResponseError(local_error))
711 }
712 }
713}