openstack_sdk/api/network/v2/router/
add_router_interface.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Adds an internal interface to a logical router. This means a specified
19//! subnet is attached to a router as an internal router interface.
20//!
21//! Specify the ID of a subnet or port in the request body:
22//!
23//! When you specify an IPv6 subnet, this operation adds the subnet to an
24//! existing internal port with same network ID, on the router. If a port with
25//! the same network ID does not exist, this operation creates a port on the
26//! router for that subnet.
27//!
28//! The limitation of one IPv4 subnet per router port remains, though a port
29//! can contain any number of IPv6 subnets that belong to the same network ID.
30//!
31//! When you use the `port-create` command to add a port and then call
32//! `router-interface-add` with this port ID, this operation adds the port to
33//! the router if the following conditions are met:
34//!
35//! If you specify both subnet ID and port ID, this operation returns the
36//! `Bad Request (400)` response code.
37//!
38//! If the port is already in use, this operation returns the `Conflict (409)`
39//! response code.
40//!
41//! This operation returns a port ID that is either:
42//!
43//! After you run this operation, the operation sets:
44//!
45//! Normal response codes: 200
46//!
47//! Error response codes: 400, 401, 404, 409
48//!
49use derive_builder::Builder;
50use http::{HeaderMap, HeaderName, HeaderValue};
51
52use crate::api::rest_endpoint_prelude::*;
53
54use std::borrow::Cow;
55
56#[derive(Builder, Debug, Clone)]
57#[builder(setter(strip_option))]
58pub struct Request<'a> {
59    /// The ID of the port. One of subnet_id or port_id must be specified.
60    #[builder(default, setter(into))]
61    pub(crate) port_id: Option<Cow<'a, str>>,
62
63    /// The ID of the subnet. One of subnet_id or port_id must be specified.
64    #[builder(default, setter(into))]
65    pub(crate) subnet_id: Option<Cow<'a, str>>,
66
67    /// id parameter for /v2.0/routers/{id} API
68    #[builder(default, setter(into))]
69    id: Cow<'a, str>,
70
71    #[builder(setter(name = "_headers"), default, private)]
72    _headers: Option<HeaderMap>,
73}
74impl<'a> Request<'a> {
75    /// Create a builder for the endpoint.
76    pub fn builder() -> RequestBuilder<'a> {
77        RequestBuilder::default()
78    }
79}
80
81impl<'a> RequestBuilder<'a> {
82    /// Add a single header to the Router.
83    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
84    where
85        K: Into<HeaderName>,
86        V: Into<HeaderValue>,
87    {
88        self._headers
89            .get_or_insert(None)
90            .get_or_insert_with(HeaderMap::new)
91            .insert(header_name.into(), header_value.into());
92        self
93    }
94
95    /// Add multiple headers.
96    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
97    where
98        I: Iterator<Item = T>,
99        T: Into<(Option<HeaderName>, HeaderValue)>,
100    {
101        self._headers
102            .get_or_insert(None)
103            .get_or_insert_with(HeaderMap::new)
104            .extend(iter.map(Into::into));
105        self
106    }
107}
108
109impl RestEndpoint for Request<'_> {
110    fn method(&self) -> http::Method {
111        http::Method::PUT
112    }
113
114    fn endpoint(&self) -> Cow<'static, str> {
115        format!("routers/{id}/add_router_interface", id = self.id.as_ref(),).into()
116    }
117
118    fn parameters(&self) -> QueryParams<'_> {
119        QueryParams::default()
120    }
121
122    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
123        let mut params = JsonBodyParams::default();
124
125        if let Some(val) = &self.port_id {
126            params.push("port_id", serde_json::to_value(val)?);
127        }
128        if let Some(val) = &self.subnet_id {
129            params.push("subnet_id", serde_json::to_value(val)?);
130        }
131
132        params.into_body()
133    }
134
135    fn service_type(&self) -> ServiceType {
136        ServiceType::Network
137    }
138
139    fn response_key(&self) -> Option<Cow<'static, str>> {
140        None
141    }
142
143    /// Returns headers to be set into the request
144    fn request_headers(&self) -> Option<&HeaderMap> {
145        self._headers.as_ref()
146    }
147
148    /// Returns required API version
149    fn api_version(&self) -> Option<ApiVersion> {
150        Some(ApiVersion::new(2, 0))
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    #[cfg(feature = "sync")]
158    use crate::api::Query;
159    use crate::test::client::FakeOpenStackClient;
160    use crate::types::ServiceType;
161    use http::{HeaderName, HeaderValue};
162    use httpmock::MockServer;
163    use serde_json::json;
164
165    #[test]
166    fn test_service_type() {
167        assert_eq!(
168            Request::builder().build().unwrap().service_type(),
169            ServiceType::Network
170        );
171    }
172
173    #[test]
174    fn test_response_key() {
175        assert!(Request::builder().build().unwrap().response_key().is_none())
176    }
177
178    #[cfg(feature = "sync")]
179    #[test]
180    fn endpoint() {
181        let server = MockServer::start();
182        let client = FakeOpenStackClient::new(server.base_url());
183        let mock = server.mock(|when, then| {
184            when.method(httpmock::Method::PUT)
185                .path(format!("/routers/{id}/add_router_interface", id = "id",));
186
187            then.status(200)
188                .header("content-type", "application/json")
189                .json_body(json!({ "dummy": {} }));
190        });
191
192        let endpoint = Request::builder().id("id").build().unwrap();
193        let _: serde_json::Value = endpoint.query(&client).unwrap();
194        mock.assert();
195    }
196
197    #[cfg(feature = "sync")]
198    #[test]
199    fn endpoint_headers() {
200        let server = MockServer::start();
201        let client = FakeOpenStackClient::new(server.base_url());
202        let mock = server.mock(|when, then| {
203            when.method(httpmock::Method::PUT)
204                .path(format!("/routers/{id}/add_router_interface", id = "id",))
205                .header("foo", "bar")
206                .header("not_foo", "not_bar");
207            then.status(200)
208                .header("content-type", "application/json")
209                .json_body(json!({ "dummy": {} }));
210        });
211
212        let endpoint = Request::builder()
213            .id("id")
214            .headers(
215                [(
216                    Some(HeaderName::from_static("foo")),
217                    HeaderValue::from_static("bar"),
218                )]
219                .into_iter(),
220            )
221            .header(
222                HeaderName::from_static("not_foo"),
223                HeaderValue::from_static("not_bar"),
224            )
225            .build()
226            .unwrap();
227        let _: serde_json::Value = endpoint.query(&client).unwrap();
228        mock.assert();
229    }
230}