|
| 1 | +// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +use vmm::logger::{IncMetric, METRICS}; |
| 5 | +use vmm::rpc_interface::VmmAction; |
| 6 | +use vmm::vmm_config::pmem::PmemConfig; |
| 7 | + |
| 8 | +use super::super::parsed_request::{ParsedRequest, RequestError, checked_id}; |
| 9 | +use super::{Body, StatusCode}; |
| 10 | + |
| 11 | +pub(crate) fn parse_put_pmem( |
| 12 | + body: &Body, |
| 13 | + id_from_path: Option<&str>, |
| 14 | +) -> Result<ParsedRequest, RequestError> { |
| 15 | + METRICS.put_api_requests.pmem_count.inc(); |
| 16 | + let id = if let Some(id) = id_from_path { |
| 17 | + checked_id(id)? |
| 18 | + } else { |
| 19 | + METRICS.put_api_requests.pmem_fails.inc(); |
| 20 | + return Err(RequestError::EmptyID); |
| 21 | + }; |
| 22 | + |
| 23 | + let device_cfg = serde_json::from_slice::<PmemConfig>(body.raw()).inspect_err(|_| { |
| 24 | + METRICS.put_api_requests.pmem_fails.inc(); |
| 25 | + })?; |
| 26 | + |
| 27 | + if id != device_cfg.id { |
| 28 | + METRICS.put_api_requests.pmem_fails.inc(); |
| 29 | + Err(RequestError::Generic( |
| 30 | + StatusCode::BadRequest, |
| 31 | + "The id from the path does not match the id from the body!".to_string(), |
| 32 | + )) |
| 33 | + } else { |
| 34 | + Ok(ParsedRequest::new_sync(VmmAction::InsertPmemDevice( |
| 35 | + device_cfg, |
| 36 | + ))) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +#[cfg(test)] |
| 41 | +mod tests { |
| 42 | + use super::*; |
| 43 | + use crate::api_server::parsed_request::tests::vmm_action_from_request; |
| 44 | + |
| 45 | + #[test] |
| 46 | + fn test_parse_put_pmem_request() { |
| 47 | + parse_put_pmem(&Body::new("invalid_payload"), None).unwrap_err(); |
| 48 | + parse_put_pmem(&Body::new("invalid_payload"), Some("id")).unwrap_err(); |
| 49 | + |
| 50 | + let body = r#"{ |
| 51 | + "id": "bar", |
| 52 | + }"#; |
| 53 | + parse_put_pmem(&Body::new(body), Some("1")).unwrap_err(); |
| 54 | + let body = r#"{ |
| 55 | + "foo": "1", |
| 56 | + }"#; |
| 57 | + parse_put_pmem(&Body::new(body), Some("1")).unwrap_err(); |
| 58 | + |
| 59 | + let body = r#"{ |
| 60 | + "id": "1000", |
| 61 | + "path_on_host": "dummy", |
| 62 | + "root_device": true, |
| 63 | + "read_only": true |
| 64 | + }"#; |
| 65 | + let r = vmm_action_from_request(parse_put_pmem(&Body::new(body), Some("1000")).unwrap()); |
| 66 | + |
| 67 | + let expected_config = PmemConfig { |
| 68 | + id: "1000".to_string(), |
| 69 | + path_on_host: "dummy".to_string(), |
| 70 | + root_device: true, |
| 71 | + read_only: true, |
| 72 | + }; |
| 73 | + assert_eq!(r, VmmAction::InsertPmemDevice(expected_config)); |
| 74 | + } |
| 75 | +} |
0 commit comments