openstack_sdk/api/compute/v2/server/
create_20.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//! Creates a server.
19//!
20//! The progress of this operation depends on the location of the requested
21//! image, network I/O, host load, selected flavor, and other factors.
22//!
23//! To check the progress of the request, make a `GET /servers/{id}` request.
24//! This call returns a progress attribute, which is a percentage value from 0
25//! to 100.
26//!
27//! The `Location` header returns the full URL to the newly created server and
28//! is available as a `self` and `bookmark` link in the server representation.
29//!
30//! When you create a server, the response shows only the server ID, its links,
31//! and the admin password. You can get additional attributes through
32//! subsequent `GET` requests on the server.
33//!
34//! Include the `block_device_mapping_v2` parameter in the create request body
35//! to boot a server from a volume.
36//!
37//! Include the `key_name` parameter in the create request body to add a
38//! keypair to the server when you create it. To create a keypair, make a
39//! [create keypair](https://docs.openstack.org/api-ref/compute/#create-or-import-keypair)
40//! request.
41//!
42//! **Preconditions**
43//!
44//! **Asynchronous postconditions**
45//!
46//! **Troubleshooting**
47//!
48//! Normal response codes: 202
49//!
50//! Error response codes: badRequest(400), unauthorized(401), forbidden(403),
51//! itemNotFound(404), conflict(409)
52//!
53use derive_builder::Builder;
54use http::{HeaderMap, HeaderName, HeaderValue};
55
56use crate::api::rest_endpoint_prelude::*;
57
58use serde::Deserialize;
59use serde::Serialize;
60use serde_json::Value;
61use std::borrow::Cow;
62use std::collections::BTreeMap;
63
64#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
65#[builder(setter(strip_option))]
66pub struct OsSchHntSchedulerHints<'a> {
67    /// Schedule the server on a host in the network specified with this
68    /// parameter and a cidr (`os:scheduler_hints.cidr`). It is available when
69    /// `SimpleCIDRAffinityFilter` is available on cloud side.
70    #[serde(skip_serializing_if = "Option::is_none")]
71    #[builder(default, setter(into))]
72    pub(crate) build_near_host_ip: Option<Cow<'a, str>>,
73
74    /// Schedule the server on a host in the network specified with an IP
75    /// address (`os:scheduler_hints:build_near_host_ip`) and this parameter.
76    /// If `os:scheduler_hints:build_near_host_ip` is specified and this
77    /// parameter is omitted, `/24` is used. It is available when
78    /// `SimpleCIDRAffinityFilter` is available on cloud side.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    #[builder(default, setter(into))]
81    pub(crate) cidr: Option<Cow<'a, str>>,
82
83    /// A list of cell routes or a cell route (string). Schedule the server in
84    /// a cell that is not specified. It is available when
85    /// `DifferentCellFilter` is available on cloud side that is cell v1
86    /// environment.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    #[builder(default, setter(into))]
89    pub(crate) different_cell: Option<Vec<Cow<'a, str>>>,
90
91    /// A list of server UUIDs or a server UUID. Schedule the server on a
92    /// different host from a set of servers. It is available when
93    /// `DifferentHostFilter` is available on cloud side.
94    #[serde(skip_serializing_if = "Option::is_none")]
95    #[builder(default, setter(into))]
96    pub(crate) different_host: Option<Vec<Cow<'a, str>>>,
97
98    /// The server group UUID. Schedule the server according to a policy of the
99    /// server group (`anti-affinity`, `affinity`, `soft-anti-affinity` or
100    /// `soft-affinity`). It is available when `ServerGroupAffinityFilter`,
101    /// `ServerGroupAntiAffinityFilter`, `ServerGroupSoftAntiAffinityWeigher`,
102    /// `ServerGroupSoftAffinityWeigher` are available on cloud side.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    #[builder(default, setter(into))]
105    pub(crate) group: Option<Cow<'a, str>>,
106
107    /// Schedule the server by using a custom filter in JSON format. For
108    /// example:
109    ///
110    /// ```text
111    /// "query": "[\">=\",\"$free_ram_mb\",1024]"
112    /// ```
113    ///
114    /// It is available when `JsonFilter` is available on cloud side.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    #[builder(default, setter(into))]
117    pub(crate) query: Option<Value>,
118
119    /// A list of server UUIDs or a server UUID. Schedule the server on the
120    /// same host as another server in a set of servers. It is available when
121    /// `SameHostFilter` is available on cloud side.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    #[builder(default, setter(into))]
124    pub(crate) same_host: Option<Vec<Cow<'a, str>>>,
125
126    /// A target cell name. Schedule the server in a host in the cell
127    /// specified. It is available when `TargetCellFilter` is available on
128    /// cloud side that is cell v1 environment.
129    #[serde(skip_serializing_if = "Option::is_none")]
130    #[builder(default, setter(into))]
131    pub(crate) target_cell: Option<Cow<'a, str>>,
132
133    #[builder(setter(name = "_properties"), default, private)]
134    #[serde(flatten)]
135    _properties: BTreeMap<Cow<'a, str>, Value>,
136}
137
138impl<'a> OsSchHntSchedulerHintsBuilder<'a> {
139    pub fn properties<I, K, V>(&mut self, iter: I) -> &mut Self
140    where
141        I: Iterator<Item = (K, V)>,
142        K: Into<Cow<'a, str>>,
143        V: Into<Value>,
144    {
145        self._properties
146            .get_or_insert_with(BTreeMap::new)
147            .extend(iter.map(|(k, v)| (k.into(), v.into())));
148        self
149    }
150}
151
152/// The dictionary of data to send to the scheduler. Alternatively, you can
153/// specify `OS-SCH-HNT:scheduler_hints` as the key in the request body.
154///
155/// Note
156///
157/// This is a top-level key in the request body, not part of the server portion
158/// of the request body.
159///
160/// There are a few caveats with scheduler hints:
161///
162/// - The request validation schema is per hint. For example, some require a
163///   single string value, and some accept a list of values.
164/// - Hints are only used based on the cloud scheduler configuration, which
165///   varies per deployment.
166/// - Hints are pluggable per deployment, meaning that a cloud can have custom
167///   hints which may not be available in another cloud.
168///
169/// For these reasons, it is important to consult each cloud’s user
170/// documentation to know what is available for scheduler hints.
171#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
172#[builder(setter(strip_option))]
173pub struct OsSchedulerHints<'a> {
174    /// Schedule the server on a host in the network specified with this
175    /// parameter and a cidr (`os:scheduler_hints.cidr`). It is available when
176    /// `SimpleCIDRAffinityFilter` is available on cloud side.
177    #[serde(skip_serializing_if = "Option::is_none")]
178    #[builder(default, setter(into))]
179    pub(crate) build_near_host_ip: Option<Cow<'a, str>>,
180
181    /// Schedule the server on a host in the network specified with an IP
182    /// address (`os:scheduler_hints:build_near_host_ip`) and this parameter.
183    /// If `os:scheduler_hints:build_near_host_ip` is specified and this
184    /// parameter is omitted, `/24` is used. It is available when
185    /// `SimpleCIDRAffinityFilter` is available on cloud side.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    #[builder(default, setter(into))]
188    pub(crate) cidr: Option<Cow<'a, str>>,
189
190    /// A list of cell routes or a cell route (string). Schedule the server in
191    /// a cell that is not specified. It is available when
192    /// `DifferentCellFilter` is available on cloud side that is cell v1
193    /// environment.
194    #[serde(skip_serializing_if = "Option::is_none")]
195    #[builder(default, setter(into))]
196    pub(crate) different_cell: Option<Vec<Cow<'a, str>>>,
197
198    /// A list of server UUIDs or a server UUID. Schedule the server on a
199    /// different host from a set of servers. It is available when
200    /// `DifferentHostFilter` is available on cloud side.
201    #[serde(skip_serializing_if = "Option::is_none")]
202    #[builder(default, setter(into))]
203    pub(crate) different_host: Option<Vec<Cow<'a, str>>>,
204
205    /// The server group UUID. Schedule the server according to a policy of the
206    /// server group (`anti-affinity`, `affinity`, `soft-anti-affinity` or
207    /// `soft-affinity`). It is available when `ServerGroupAffinityFilter`,
208    /// `ServerGroupAntiAffinityFilter`, `ServerGroupSoftAntiAffinityWeigher`,
209    /// `ServerGroupSoftAffinityWeigher` are available on cloud side.
210    #[serde(skip_serializing_if = "Option::is_none")]
211    #[builder(default, setter(into))]
212    pub(crate) group: Option<Cow<'a, str>>,
213
214    /// Schedule the server by using a custom filter in JSON format. For
215    /// example:
216    ///
217    /// ```text
218    /// "query": "[\">=\",\"$free_ram_mb\",1024]"
219    /// ```
220    ///
221    /// It is available when `JsonFilter` is available on cloud side.
222    #[serde(skip_serializing_if = "Option::is_none")]
223    #[builder(default, setter(into))]
224    pub(crate) query: Option<Value>,
225
226    /// A list of server UUIDs or a server UUID. Schedule the server on the
227    /// same host as another server in a set of servers. It is available when
228    /// `SameHostFilter` is available on cloud side.
229    #[serde(skip_serializing_if = "Option::is_none")]
230    #[builder(default, setter(into))]
231    pub(crate) same_host: Option<Vec<Cow<'a, str>>>,
232
233    /// A target cell name. Schedule the server in a host in the cell
234    /// specified. It is available when `TargetCellFilter` is available on
235    /// cloud side that is cell v1 environment.
236    #[serde(skip_serializing_if = "Option::is_none")]
237    #[builder(default, setter(into))]
238    pub(crate) target_cell: Option<Cow<'a, str>>,
239
240    #[builder(setter(name = "_properties"), default, private)]
241    #[serde(flatten)]
242    _properties: BTreeMap<Cow<'a, str>, Value>,
243}
244
245impl<'a> OsSchedulerHintsBuilder<'a> {
246    pub fn properties<I, K, V>(&mut self, iter: I) -> &mut Self
247    where
248        I: Iterator<Item = (K, V)>,
249        K: Into<Cow<'a, str>>,
250        V: Into<Value>,
251    {
252        self._properties
253            .get_or_insert_with(BTreeMap::new)
254            .extend(iter.map(|(k, v)| (k.into(), v.into())));
255        self
256    }
257}
258
259#[derive(Debug, Deserialize, Clone, Serialize)]
260pub enum OsDcfDiskConfig {
261    #[serde(rename = "AUTO")]
262    Auto,
263    #[serde(rename = "MANUAL")]
264    Manual,
265}
266
267#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
268#[builder(setter(strip_option))]
269pub struct BlockDeviceMapping<'a> {
270    #[serde(skip_serializing_if = "Option::is_none")]
271    #[builder(default, setter(into))]
272    pub(crate) connection_info: Option<Cow<'a, str>>,
273
274    /// Indicates whether a config drive enables metadata injection. The
275    /// config_drive setting provides information about a drive that the
276    /// instance can mount at boot time. The instance reads files from the
277    /// drive to get information that is normally available through the
278    /// metadata service. This metadata is different from the user data. Not
279    /// all cloud providers enable the `config_drive`. Read more in the
280    /// [OpenStack End User Guide](https://docs.openstack.org/nova/latest/user/config-drive.html).
281    #[serde(skip_serializing_if = "Option::is_none")]
282    #[builder(default, setter(into))]
283    pub(crate) delete_on_termination: Option<bool>,
284
285    #[serde(skip_serializing_if = "Option::is_none")]
286    #[builder(default, setter(into))]
287    pub(crate) device_name: Option<Cow<'a, str>>,
288
289    #[serde(skip_serializing_if = "Option::is_none")]
290    #[builder(default, setter(into))]
291    pub(crate) no_device: Option<Value>,
292
293    #[serde(skip_serializing_if = "Option::is_none")]
294    #[builder(default, setter(into))]
295    pub(crate) snapshot_id: Option<Cow<'a, str>>,
296
297    #[serde(skip_serializing_if = "Option::is_none")]
298    #[builder(default, setter(into))]
299    pub(crate) virtual_name: Option<Cow<'a, str>>,
300
301    #[serde(skip_serializing_if = "Option::is_none")]
302    #[builder(default, setter(into))]
303    pub(crate) volume_id: Option<Cow<'a, str>>,
304
305    #[serde(skip_serializing_if = "Option::is_none")]
306    #[builder(default, setter(into))]
307    pub(crate) volume_size: Option<i32>,
308}
309
310#[derive(Debug, Deserialize, Clone, Serialize)]
311pub enum DestinationType {
312    #[serde(rename = "local")]
313    Local,
314    #[serde(rename = "volume")]
315    Volume,
316}
317
318#[derive(Debug, Deserialize, Clone, Serialize)]
319pub enum SourceType {
320    #[serde(rename = "blank")]
321    Blank,
322    #[serde(rename = "image")]
323    Image,
324    #[serde(rename = "snapshot")]
325    Snapshot,
326    #[serde(rename = "volume")]
327    Volume,
328}
329
330#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
331#[builder(setter(strip_option))]
332pub struct BlockDeviceMappingV2<'a> {
333    #[serde(skip_serializing_if = "Option::is_none")]
334    #[builder(default, setter(into))]
335    pub(crate) boot_index: Option<Option<Cow<'a, str>>>,
336
337    #[serde(skip_serializing_if = "Option::is_none")]
338    #[builder(default, setter(into))]
339    pub(crate) connection_info: Option<Cow<'a, str>>,
340
341    #[serde(skip_serializing_if = "Option::is_none")]
342    #[builder(default, setter(into))]
343    pub(crate) delete_on_termination: Option<bool>,
344
345    #[serde(skip_serializing_if = "Option::is_none")]
346    #[builder(default)]
347    pub(crate) destination_type: Option<DestinationType>,
348
349    #[serde(skip_serializing_if = "Option::is_none")]
350    #[builder(default, setter(into))]
351    pub(crate) device_name: Option<Cow<'a, str>>,
352
353    #[serde(skip_serializing_if = "Option::is_none")]
354    #[builder(default, setter(into))]
355    pub(crate) device_type: Option<Cow<'a, str>>,
356
357    #[serde(skip_serializing_if = "Option::is_none")]
358    #[builder(default, setter(into))]
359    pub(crate) disk_bus: Option<Cow<'a, str>>,
360
361    #[serde(skip_serializing_if = "Option::is_none")]
362    #[builder(default, setter(into))]
363    pub(crate) guest_format: Option<Cow<'a, str>>,
364
365    #[serde(skip_serializing_if = "Option::is_none")]
366    #[builder(default, setter(into))]
367    pub(crate) image_id: Option<Cow<'a, str>>,
368
369    #[serde(skip_serializing_if = "Option::is_none")]
370    #[builder(default, setter(into))]
371    pub(crate) no_device: Option<Value>,
372
373    #[serde(skip_serializing_if = "Option::is_none")]
374    #[builder(default, setter(into))]
375    pub(crate) snapshot_id: Option<Cow<'a, str>>,
376
377    #[serde(skip_serializing_if = "Option::is_none")]
378    #[builder(default)]
379    pub(crate) source_type: Option<SourceType>,
380
381    #[serde(skip_serializing_if = "Option::is_none")]
382    #[builder(default, setter(into))]
383    pub(crate) uuid: Option<Cow<'a, str>>,
384
385    #[serde(skip_serializing_if = "Option::is_none")]
386    #[builder(default, setter(into))]
387    pub(crate) virtual_name: Option<Cow<'a, str>>,
388
389    #[serde(skip_serializing_if = "Option::is_none")]
390    #[builder(default, setter(into))]
391    pub(crate) volume_id: Option<Cow<'a, str>>,
392
393    #[serde(skip_serializing_if = "Option::is_none")]
394    #[builder(default, setter(into))]
395    pub(crate) volume_size: Option<i32>,
396}
397
398#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
399#[builder(setter(strip_option))]
400pub struct Networks<'a> {
401    /// Schedule the server on a host in the network specified with this
402    /// parameter and a cidr (`os:scheduler_hints.cidr`). It is available when
403    /// `SimpleCIDRAffinityFilter` is available on cloud side.
404    #[serde(skip_serializing_if = "Option::is_none")]
405    #[builder(default, setter(into))]
406    pub(crate) fixed_ip: Option<Cow<'a, str>>,
407
408    #[serde(skip_serializing_if = "Option::is_none")]
409    #[builder(default, setter(into))]
410    pub(crate) port: Option<Option<Cow<'a, str>>>,
411
412    #[serde(skip_serializing_if = "Option::is_none")]
413    #[builder(default, setter(into))]
414    pub(crate) uuid: Option<Cow<'a, str>>,
415}
416
417#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
418#[builder(setter(strip_option))]
419pub struct Personality<'a> {
420    #[serde(skip_serializing_if = "Option::is_none")]
421    #[builder(default, setter(into))]
422    pub(crate) contents: Option<Cow<'a, str>>,
423
424    #[serde(skip_serializing_if = "Option::is_none")]
425    #[builder(default, setter(into))]
426    pub(crate) path: Option<Cow<'a, str>>,
427}
428
429#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
430#[builder(setter(strip_option))]
431pub struct SecurityGroups<'a> {
432    /// Key pair name.
433    ///
434    /// Note
435    ///
436    /// The `null` value was allowed in the Nova legacy v2 API, but due to
437    /// strict input validation, it is not allowed in the Nova v2.1 API.
438    #[serde(skip_serializing_if = "Option::is_none")]
439    #[builder(default, setter(into))]
440    pub(crate) name: Option<Cow<'a, str>>,
441}
442
443/// A `server` object.
444#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
445#[builder(setter(strip_option))]
446pub struct Server<'a> {
447    /// IPv4 address that should be used to access this server.
448    #[serde(rename = "accessIPv4", skip_serializing_if = "Option::is_none")]
449    #[builder(default, setter(into))]
450    pub(crate) access_ipv4: Option<Cow<'a, str>>,
451
452    /// IPv6 address that should be used to access this server.
453    #[serde(rename = "accessIPv6", skip_serializing_if = "Option::is_none")]
454    #[builder(default, setter(into))]
455    pub(crate) access_ipv6: Option<Cow<'a, str>>,
456
457    /// The administrative password of the server. If you omit this parameter,
458    /// the operation generates a new password.
459    #[serde(rename = "adminPass", skip_serializing_if = "Option::is_none")]
460    #[builder(default, setter(into))]
461    pub(crate) admin_pass: Option<Cow<'a, str>>,
462
463    /// Key pair name.
464    ///
465    /// Note
466    ///
467    /// The `null` value was allowed in the Nova legacy v2 API, but due to
468    /// strict input validation, it is not allowed in the Nova v2.1 API.
469    #[serde(skip_serializing_if = "Option::is_none")]
470    #[builder(default, setter(into))]
471    pub(crate) availability_zone: Option<Cow<'a, str>>,
472
473    #[serde(skip_serializing_if = "Option::is_none")]
474    #[builder(default, setter(into))]
475    pub(crate) block_device_mapping: Option<Vec<BlockDeviceMapping<'a>>>,
476
477    /// Enables fine grained control of the block device mapping for an
478    /// instance. This is typically used for booting servers from volumes. An
479    /// example format would look as follows:
480    ///
481    /// > ```text
482    /// > "block_device_mapping_v2": [{
483    /// >     "boot_index": "0",
484    /// >     "uuid": "ac408821-c95a-448f-9292-73986c790911",
485    /// >     "source_type": "image",
486    /// >     "volume_size": "25",
487    /// >     "destination_type": "volume",
488    /// >     "delete_on_termination": true,
489    /// >     "tag": "disk1",
490    /// >     "disk_bus": "scsi"}]
491    /// > ```
492    ///
493    /// In microversion 2.32, `tag` is an optional string attribute that can be
494    /// used to assign a tag to the block device. This tag is then exposed to
495    /// the guest in the metadata API and the config drive and is associated to
496    /// hardware metadata for that block device, such as bus (ex: SCSI), bus
497    /// address (ex: 1:0:2:0), and serial.
498    ///
499    /// A bug has caused the `tag` attribute to no longer be accepted starting
500    /// with version 2.33. It has been restored in version 2.42.
501    #[serde(skip_serializing_if = "Option::is_none")]
502    #[builder(default, setter(into))]
503    pub(crate) block_device_mapping_v2: Option<Vec<BlockDeviceMappingV2<'a>>>,
504
505    /// Indicates whether a config drive enables metadata injection. The
506    /// config_drive setting provides information about a drive that the
507    /// instance can mount at boot time. The instance reads files from the
508    /// drive to get information that is normally available through the
509    /// metadata service. This metadata is different from the user data. Not
510    /// all cloud providers enable the `config_drive`. Read more in the
511    /// [OpenStack End User Guide](https://docs.openstack.org/nova/latest/user/config-drive.html).
512    #[serde(skip_serializing_if = "Option::is_none")]
513    #[builder(default, setter(into))]
514    pub(crate) config_drive: Option<bool>,
515
516    /// The flavor reference, as an ID (including a UUID) or full URL, for the
517    /// flavor for your server instance.
518    #[serde(rename = "flavorRef")]
519    #[builder(setter(into))]
520    pub(crate) flavor_ref: Cow<'a, str>,
521
522    /// The UUID of the image to use for your server instance. This is not
523    /// required in case of boot from volume. In all other cases it is required
524    /// and must be a valid UUID otherwise API will return 400.
525    #[serde(rename = "imageRef", skip_serializing_if = "Option::is_none")]
526    #[builder(default, setter(into))]
527    pub(crate) image_ref: Option<Cow<'a, str>>,
528
529    /// Key pair name.
530    ///
531    /// Note
532    ///
533    /// The `null` value was allowed in the Nova legacy v2 API, but due to
534    /// strict input validation, it is not allowed in the Nova v2.1 API.
535    #[serde(skip_serializing_if = "Option::is_none")]
536    #[builder(default, setter(into))]
537    pub(crate) key_name: Option<Cow<'a, str>>,
538
539    #[serde(skip_serializing_if = "Option::is_none")]
540    #[builder(default, setter(into))]
541    pub(crate) max_count: Option<i32>,
542
543    /// Metadata key and value pairs. The maximum size of the metadata key and
544    /// value is 255 bytes each.
545    #[serde(skip_serializing_if = "Option::is_none")]
546    #[builder(default, private, setter(into, name = "_metadata"))]
547    pub(crate) metadata: Option<BTreeMap<Cow<'a, str>, Cow<'a, str>>>,
548
549    #[serde(skip_serializing_if = "Option::is_none")]
550    #[builder(default, setter(into))]
551    pub(crate) min_count: Option<i32>,
552
553    /// Key pair name.
554    ///
555    /// Note
556    ///
557    /// The `null` value was allowed in the Nova legacy v2 API, but due to
558    /// strict input validation, it is not allowed in the Nova v2.1 API.
559    #[serde()]
560    #[builder(setter(into))]
561    pub(crate) name: Cow<'a, str>,
562
563    /// A list of `network` object. Required parameter when there are multiple
564    /// networks defined for the tenant. When you do not specify the networks
565    /// parameter, the server attaches to the only network created for the
566    /// current tenant. Optionally, you can create one or more NICs on the
567    /// server. To provision the server instance with a NIC for a network,
568    /// specify the UUID of the network in the `uuid` attribute in a `networks`
569    /// object. To provision the server instance with a NIC for an already
570    /// existing port, specify the port-id in the `port` attribute in a
571    /// `networks` object.
572    ///
573    /// If multiple networks are defined, the order in which they appear in the
574    /// guest operating system will not necessarily reflect the order in which
575    /// they are given in the server boot request. Guests should therefore not
576    /// depend on device order to deduce any information about their network
577    /// devices. Instead, device role tags should be used: introduced in 2.32,
578    /// broken in 2.37, and re-introduced and fixed in 2.42, the `tag` is an
579    /// optional, string attribute that can be used to assign a tag to a
580    /// virtual network interface. This tag is then exposed to the guest in the
581    /// metadata API and the config drive and is associated to hardware
582    /// metadata for that network interface, such as bus (ex: PCI), bus address
583    /// (ex: 0000:00:02.0), and MAC address.
584    ///
585    /// A bug has caused the `tag` attribute to no longer be accepted starting
586    /// with version 2.37. Therefore, network interfaces could only be tagged
587    /// in versions 2.32 to 2.36 inclusively. Version 2.42 has restored the
588    /// `tag` attribute.
589    ///
590    /// Starting with microversion 2.37, this field is required and the special
591    /// string values *auto* and *none* can be specified for networks. *auto*
592    /// tells the Compute service to use a network that is available to the
593    /// project, if one exists. If one does not exist, the Compute service will
594    /// attempt to automatically allocate a network for the project (if
595    /// possible). *none* tells the Compute service to not allocate a network
596    /// for the instance. The *auto* and *none* values cannot be used with any
597    /// other network values, including other network uuids, ports, fixed IPs
598    /// or device tags. These are requested as strings for the networks value,
599    /// not in a list. See the associated example.
600    #[serde(skip_serializing_if = "Option::is_none")]
601    #[builder(default, setter(into))]
602    pub(crate) networks: Option<Vec<Networks<'a>>>,
603
604    /// Controls how the API partitions the disk when you create, rebuild, or
605    /// resize servers. A server inherits the `OS-DCF:diskConfig` value from
606    /// the image from which it was created, and an image inherits the
607    /// `OS-DCF:diskConfig` value from the server from which it was created. To
608    /// override the inherited setting, you can include this attribute in the
609    /// request body of a server create, rebuild, or resize request. If the
610    /// `OS-DCF:diskConfig` value for an image is `MANUAL`, you cannot create a
611    /// server from that image and set its `OS-DCF:diskConfig` value to `AUTO`.
612    /// A valid value is:
613    ///
614    /// - `AUTO`. The API builds the server with a single partition the size of
615    ///   the target flavor disk. The API automatically adjusts the file system
616    ///   to fit the entire partition.
617    /// - `MANUAL`. The API builds the server by using whatever partition
618    ///   scheme and file system is in the source image. If the target flavor
619    ///   disk is larger, the API does not partition the remaining disk space.
620    #[serde(rename = "OS-DCF:diskConfig", skip_serializing_if = "Option::is_none")]
621    #[builder(default)]
622    pub(crate) os_dcf_disk_config: Option<OsDcfDiskConfig>,
623
624    /// The file path and contents, text only, to inject into the server at
625    /// launch. The maximum size of the file path data is 255 bytes. The
626    /// maximum limit is the number of allowed bytes in the decoded, rather
627    /// than encoded, data.
628    ///
629    /// **Available until version 2.56**
630    #[serde(skip_serializing_if = "Option::is_none")]
631    #[builder(default, setter(into))]
632    pub(crate) personality: Option<Vec<Personality<'a>>>,
633
634    /// Indicates whether a config drive enables metadata injection. The
635    /// config_drive setting provides information about a drive that the
636    /// instance can mount at boot time. The instance reads files from the
637    /// drive to get information that is normally available through the
638    /// metadata service. This metadata is different from the user data. Not
639    /// all cloud providers enable the `config_drive`. Read more in the
640    /// [OpenStack End User Guide](https://docs.openstack.org/nova/latest/user/config-drive.html).
641    #[serde(skip_serializing_if = "Option::is_none")]
642    #[builder(default, setter(into))]
643    pub(crate) return_reservation_id: Option<bool>,
644
645    /// One or more security groups. Specify the name of the security group in
646    /// the `name` attribute. If you omit this attribute, the API creates the
647    /// server in the `default` security group. Requested security groups are
648    /// not applied to pre-existing ports.
649    #[serde(skip_serializing_if = "Option::is_none")]
650    #[builder(default, setter(into))]
651    pub(crate) security_groups: Option<Vec<SecurityGroups<'a>>>,
652
653    /// Configuration information or scripts to use upon launch. Must be Base64
654    /// encoded. Restricted to 65535 bytes.
655    ///
656    /// Note
657    ///
658    /// The `null` value allowed in Nova legacy v2 API, but due to the strict
659    /// input validation, it isn’t allowed in Nova v2.1 API.
660    #[serde(skip_serializing_if = "Option::is_none")]
661    #[builder(default, setter(into))]
662    pub(crate) user_data: Option<Option<Cow<'a, str>>>,
663}
664
665impl<'a> ServerBuilder<'a> {
666    /// Metadata key and value pairs. The maximum size of the metadata key and
667    /// value is 255 bytes each.
668    pub fn metadata<I, K, V>(&mut self, iter: I) -> &mut Self
669    where
670        I: Iterator<Item = (K, V)>,
671        K: Into<Cow<'a, str>>,
672        V: Into<Cow<'a, str>>,
673    {
674        self.metadata
675            .get_or_insert(None)
676            .get_or_insert_with(BTreeMap::new)
677            .extend(iter.map(|(k, v)| (k.into(), v.into())));
678        self
679    }
680}
681
682#[derive(Builder, Debug, Clone)]
683#[builder(setter(strip_option))]
684pub struct Request<'a> {
685    #[builder(default, setter(into))]
686    pub(crate) os_sch_hnt_scheduler_hints: Option<OsSchHntSchedulerHints<'a>>,
687
688    /// The dictionary of data to send to the scheduler. Alternatively, you can
689    /// specify `OS-SCH-HNT:scheduler_hints` as the key in the request body.
690    ///
691    /// Note
692    ///
693    /// This is a top-level key in the request body, not part of the server
694    /// portion of the request body.
695    ///
696    /// There are a few caveats with scheduler hints:
697    ///
698    /// - The request validation schema is per hint. For example, some require
699    ///   a single string value, and some accept a list of values.
700    /// - Hints are only used based on the cloud scheduler configuration, which
701    ///   varies per deployment.
702    /// - Hints are pluggable per deployment, meaning that a cloud can have
703    ///   custom hints which may not be available in another cloud.
704    ///
705    /// For these reasons, it is important to consult each cloud’s user
706    /// documentation to know what is available for scheduler hints.
707    #[builder(default, setter(into))]
708    pub(crate) os_scheduler_hints: Option<OsSchedulerHints<'a>>,
709
710    /// A `server` object.
711    #[builder(setter(into))]
712    pub(crate) server: Server<'a>,
713
714    #[builder(setter(name = "_headers"), default, private)]
715    _headers: Option<HeaderMap>,
716}
717impl<'a> Request<'a> {
718    /// Create a builder for the endpoint.
719    pub fn builder() -> RequestBuilder<'a> {
720        RequestBuilder::default()
721    }
722}
723
724impl<'a> RequestBuilder<'a> {
725    /// Add a single header to the Server.
726    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
727    where
728        K: Into<HeaderName>,
729        V: Into<HeaderValue>,
730    {
731        self._headers
732            .get_or_insert(None)
733            .get_or_insert_with(HeaderMap::new)
734            .insert(header_name.into(), header_value.into());
735        self
736    }
737
738    /// Add multiple headers.
739    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
740    where
741        I: Iterator<Item = T>,
742        T: Into<(Option<HeaderName>, HeaderValue)>,
743    {
744        self._headers
745            .get_or_insert(None)
746            .get_or_insert_with(HeaderMap::new)
747            .extend(iter.map(Into::into));
748        self
749    }
750}
751
752impl RestEndpoint for Request<'_> {
753    fn method(&self) -> http::Method {
754        http::Method::POST
755    }
756
757    fn endpoint(&self) -> Cow<'static, str> {
758        "servers".to_string().into()
759    }
760
761    fn parameters(&self) -> QueryParams<'_> {
762        QueryParams::default()
763    }
764
765    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
766        let mut params = JsonBodyParams::default();
767
768        if let Some(val) = &self.os_sch_hnt_scheduler_hints {
769            params.push("OS-SCH-HNT:scheduler_hints", serde_json::to_value(val)?);
770        }
771        if let Some(val) = &self.os_scheduler_hints {
772            params.push("os:scheduler_hints", serde_json::to_value(val)?);
773        }
774        params.push("server", serde_json::to_value(&self.server)?);
775
776        params.into_body()
777    }
778
779    fn service_type(&self) -> ServiceType {
780        ServiceType::Compute
781    }
782
783    fn response_key(&self) -> Option<Cow<'static, str>> {
784        Some("server".into())
785    }
786
787    /// Returns headers to be set into the request
788    fn request_headers(&self) -> Option<&HeaderMap> {
789        self._headers.as_ref()
790    }
791
792    /// Returns required API version
793    fn api_version(&self) -> Option<ApiVersion> {
794        Some(ApiVersion::new(2, 0))
795    }
796}
797
798#[cfg(test)]
799mod tests {
800    use super::*;
801    #[cfg(feature = "sync")]
802    use crate::api::Query;
803    use crate::test::client::FakeOpenStackClient;
804    use crate::types::ServiceType;
805    use http::{HeaderName, HeaderValue};
806    use httpmock::MockServer;
807    use serde_json::json;
808
809    #[test]
810    fn test_service_type() {
811        assert_eq!(
812            Request::builder()
813                .server(
814                    ServerBuilder::default()
815                        .flavor_ref("foo")
816                        .name("foo")
817                        .build()
818                        .unwrap()
819                )
820                .build()
821                .unwrap()
822                .service_type(),
823            ServiceType::Compute
824        );
825    }
826
827    #[test]
828    fn test_response_key() {
829        assert_eq!(
830            Request::builder()
831                .server(
832                    ServerBuilder::default()
833                        .flavor_ref("foo")
834                        .name("foo")
835                        .build()
836                        .unwrap()
837                )
838                .build()
839                .unwrap()
840                .response_key()
841                .unwrap(),
842            "server"
843        );
844    }
845
846    #[cfg(feature = "sync")]
847    #[test]
848    fn endpoint() {
849        let server = MockServer::start();
850        let client = FakeOpenStackClient::new(server.base_url());
851        let mock = server.mock(|when, then| {
852            when.method(httpmock::Method::POST)
853                .path("/servers".to_string());
854
855            then.status(200)
856                .header("content-type", "application/json")
857                .json_body(json!({ "server": {} }));
858        });
859
860        let endpoint = Request::builder()
861            .server(
862                ServerBuilder::default()
863                    .flavor_ref("foo")
864                    .name("foo")
865                    .build()
866                    .unwrap(),
867            )
868            .build()
869            .unwrap();
870        let _: serde_json::Value = endpoint.query(&client).unwrap();
871        mock.assert();
872    }
873
874    #[cfg(feature = "sync")]
875    #[test]
876    fn endpoint_headers() {
877        let server = MockServer::start();
878        let client = FakeOpenStackClient::new(server.base_url());
879        let mock = server.mock(|when, then| {
880            when.method(httpmock::Method::POST)
881                .path("/servers".to_string())
882                .header("foo", "bar")
883                .header("not_foo", "not_bar");
884            then.status(200)
885                .header("content-type", "application/json")
886                .json_body(json!({ "server": {} }));
887        });
888
889        let endpoint = Request::builder()
890            .server(
891                ServerBuilder::default()
892                    .flavor_ref("foo")
893                    .name("foo")
894                    .build()
895                    .unwrap(),
896            )
897            .headers(
898                [(
899                    Some(HeaderName::from_static("foo")),
900                    HeaderValue::from_static("bar"),
901                )]
902                .into_iter(),
903            )
904            .header(
905                HeaderName::from_static("not_foo"),
906                HeaderValue::from_static("not_bar"),
907            )
908            .build()
909            .unwrap();
910        let _: serde_json::Value = endpoint.query(&client).unwrap();
911        mock.assert();
912    }
913}