openstack_cli 0.13.5

OpenStack client rewritten in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
// WARNING: This file is automatically generated from OpenAPI schema using
// `openstack-codegenerator`.

//! Create Port command
//!
//! Wraps invoking of the `v2.0/ports` with `POST` method

use clap::Args;
use eyre::{OptionExt, WrapErr};
use tracing::info;

use openstack_sdk::AsyncOpenStack;

use crate::Cli;
use crate::OpenStackCliError;
use crate::output::OutputProcessor;

use crate::common::parse_key_val;
use clap::ValueEnum;
use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::network::v2::port::create;
use openstack_types::network::v2::port::response::create::PortResponse;
use serde_json::Value;

/// Creates a port on a network.
///
/// To define the network in which to create the port, specify the `network_id`
/// attribute in the request body.
///
/// Normal response codes: 201
///
/// Error response codes: 400, 401, 403, 404
#[derive(Args)]
#[command(about = "Create port")]
pub struct PortCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

    /// Path parameters
    #[command(flatten)]
    path: PathParameters,

    /// A `port` object.
    #[command(flatten)]
    port: Port,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {}

/// Path parameters
#[derive(Args)]
struct PathParameters {}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum BindingVnicType {
    AcceleratorDirect,
    AcceleratorDirectPhysical,
    Baremetal,
    Direct,
    DirectPhysical,
    Macvtap,
    Normal,
    RemoteManaged,
    SmartNic,
    Vdpa,
    VirtioForwarder,
}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum NumaAffinityPolicy {
    Legacy,
    Preferred,
    Required,
    Socket,
}

/// Port Body data
#[derive(Args, Clone)]
struct Port {
    /// The administrative state of the resource, which is up (`true`) or down
    /// (`false`). Default is `true`.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    admin_state_up: Option<bool>,

    /// A set of zero or more allowed address pair objects each where address
    /// pair object contains an `ip_address` and `mac_address`. While the
    /// `ip_address` is required, the `mac_address` will be taken from the port
    /// if not specified. The value of `ip_address` can be an IP Address or a
    /// CIDR (if supported by the underlying extension plugin). A server
    /// connected to the port can send a packet with source address which
    /// matches one of the specified allowed address pairs.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    allowed_address_pairs: Option<Vec<Value>>,

    /// The ID of the host where the port resides. The default is an empty
    /// string.
    #[arg(help_heading = "Body parameters", long)]
    binding_host_id: Option<String>,

    /// A dictionary that enables the application running on the specific host
    /// to pass and receive vif port information specific to the networking
    /// back-end. This field is only meant for machine-machine communication
    /// for compute services like Nova, Ironic or Zun to pass information to a
    /// Neutron back-end. It should not be used by multiple services
    /// concurrently or by cloud end users. The existing counterexamples
    /// (`capabilities: [switchdev]` for Open vSwitch hardware offload and
    /// `trusted=true` for Trusted Virtual Functions) are due to be cleaned up.
    /// The networking API does not define a specific format of this field. The
    /// default is an empty dictionary. If you update it with null then it is
    /// treated like {} in the response. Since the port-mac-address-override
    /// extension the `device_mac_address` field of the binding:profile can be
    /// used to provide the MAC address of the physical device a
    /// direct-physical port is being bound to. If provided, then the
    /// `mac_address` field of the port resource will be updated to the MAC
    /// from the active binding.
    #[arg(help_heading = "Body parameters", long, value_name="key=value", value_parser=parse_key_val::<String, Value>)]
    binding_profile: Option<Vec<(String, Value)>>,

    /// The type of vNIC which this port should be attached to. This is used to
    /// determine which mechanism driver(s) to be used to bind the port. The
    /// valid values are `normal`, `macvtap`, `direct`, `baremetal`,
    /// `direct-physical`, `virtio-forwarder`, `smart-nic` and
    /// `remote-managed`. What type of vNIC is actually available depends on
    /// deployments. The default is `normal`.
    #[arg(help_heading = "Body parameters", long)]
    binding_vnic_type: Option<BindingVnicType>,

    /// A human-readable description for the resource. Default is an empty
    /// string.
    #[arg(help_heading = "Body parameters", long)]
    description: Option<String>,

    /// The ID of the device that uses this port. For example, a server
    /// instance or a logical router.
    #[arg(help_heading = "Body parameters", long)]
    device_id: Option<String>,

    /// The entity type that uses this port. For example, `compute:nova`
    /// (server instance), `network:dhcp` (DHCP agent) or
    /// `network:router_interface` (router interface).
    #[arg(help_heading = "Body parameters", long)]
    device_owner: Option<String>,

    #[arg(help_heading = "Body parameters", long)]
    device_profile: Option<String>,

    /// Set explicit NULL for the device_profile
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "device_profile")]
    no_device_profile: bool,

    /// A valid DNS domain.
    #[arg(help_heading = "Body parameters", long)]
    dns_domain: Option<String>,

    /// A valid DNS name.
    #[arg(help_heading = "Body parameters", long)]
    dns_name: Option<String>,

    /// A set of zero or more extra DHCP option pairs. An option pair consists
    /// of an option value and name.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    extra_dhcp_opts: Option<Vec<Value>>,

    /// The IP addresses for the port. If you would like to assign multiple IP
    /// addresses for the port, specify multiple entries in this field. Each
    /// entry consists of IP address (`ip_address`) and the subnet ID from
    /// which the IP address is assigned (`subnet_id`).
    ///
    /// - If you specify both a subnet ID and an IP address, OpenStack
    ///   Networking tries to allocate the IP address on that subnet to the
    ///   port.
    /// - If you specify only a subnet ID, OpenStack Networking allocates an
    ///   available IP from that subnet to the port.
    /// - If you specify only an IP address, OpenStack Networking tries to
    ///   allocate the IP address if the address is a valid IP for any of the
    ///   subnets on the specified network.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    fixed_ips: Option<Vec<Value>>,

    /// Admin-only. A dict, at the top level keyed by mechanism driver aliases
    /// (as defined in setup.cfg). To following values can be used to control
    /// Open vSwitch’s Userspace Tx packet steering feature:
    ///
    /// - `{"openvswitch": {"other_config": {"tx-steering": "hash"}}}`
    /// - `{"openvswitch": {"other_config": {"tx-steering": "thread"}}}`
    ///
    /// If omitted the default is defined by Open vSwitch. The field cannot be
    /// longer than 4095 characters.
    #[arg(help_heading = "Body parameters", long, value_name="key=value", value_parser=parse_key_val::<String, Value>)]
    hints: Option<Vec<(String, Value)>>,

    /// The MAC address of the port. If unspecified, a MAC address is
    /// automatically generated.
    #[arg(help_heading = "Body parameters", long)]
    mac_address: Option<String>,

    /// Human-readable name of the resource. Default is an empty string.
    #[arg(help_heading = "Body parameters", long)]
    name: Option<String>,

    /// The ID of the attached network.
    #[arg(help_heading = "Body parameters", long)]
    network_id: Option<String>,

    /// The port NUMA affinity policy requested during the virtual machine
    /// scheduling. Values: `None`, `required`, `preferred` or `legacy`.
    #[arg(help_heading = "Body parameters", long)]
    numa_affinity_policy: Option<NumaAffinityPolicy>,

    /// The port security status. A valid value is enabled (`true`) or disabled
    /// (`false`). If port security is enabled for the port, security group
    /// rules and anti-spoofing rules are applied to the traffic on the port.
    /// If disabled, no such rules are applied.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    port_security_enabled: Option<bool>,

    /// The uplink status propagation of the port. Valid values are enabled
    /// (`true`) and disabled (`false`).
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    propagate_uplink_status: Option<bool>,

    /// QoS policy associated with the port.
    #[arg(help_heading = "Body parameters", long)]
    qos_policy_id: Option<String>,

    /// Set explicit NULL for the qos_policy_id
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "qos_policy_id")]
    no_qos_policy_id: bool,

    /// The IDs of security groups applied to the port.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    security_groups: Option<Vec<String>>,

    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    tags: Option<Vec<String>>,

    /// The ID of the project that owns the resource. Only administrative and
    /// users with advsvc role can specify a project ID other than their own.
    /// You cannot change this value through authorization policies.
    #[arg(help_heading = "Body parameters", long)]
    tenant_id: Option<String>,
}

impl PortCommand {
    /// Perform command action
    pub async fn take_action(
        &self,
        parsed_args: &Cli,
        client: &mut AsyncOpenStack,
    ) -> Result<(), OpenStackCliError> {
        info!("Create Port");

        let op = OutputProcessor::from_args(parsed_args, Some("network.port"), Some("create"));
        op.validate_args(parsed_args)?;

        let mut ep_builder = create::Request::builder();

        // Set body parameters
        // Set Request.port data
        let args = &self.port;
        let mut port_builder = create::PortBuilder::default();
        if let Some(val) = &args.admin_state_up {
            port_builder.admin_state_up(*val);
        }

        if let Some(val) = &args.allowed_address_pairs {
            let allowed_address_pairs_builder: Vec<create::AllowedAddressPairs> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<create::AllowedAddressPairs>(v.to_owned()))
                .collect::<Vec<create::AllowedAddressPairs>>();
            port_builder.allowed_address_pairs(allowed_address_pairs_builder);
        }

        if let Some(val) = &args.binding_host_id {
            port_builder.binding_host_id(val);
        }

        if let Some(val) = &args.binding_profile {
            port_builder.binding_profile(val.iter().cloned());
        }

        if let Some(val) = &args.binding_vnic_type {
            let tmp = match val {
                BindingVnicType::AcceleratorDirect => create::BindingVnicType::AcceleratorDirect,
                BindingVnicType::AcceleratorDirectPhysical => {
                    create::BindingVnicType::AcceleratorDirectPhysical
                }
                BindingVnicType::Baremetal => create::BindingVnicType::Baremetal,
                BindingVnicType::Direct => create::BindingVnicType::Direct,
                BindingVnicType::DirectPhysical => create::BindingVnicType::DirectPhysical,
                BindingVnicType::Macvtap => create::BindingVnicType::Macvtap,
                BindingVnicType::Normal => create::BindingVnicType::Normal,
                BindingVnicType::RemoteManaged => create::BindingVnicType::RemoteManaged,
                BindingVnicType::SmartNic => create::BindingVnicType::SmartNic,
                BindingVnicType::Vdpa => create::BindingVnicType::Vdpa,
                BindingVnicType::VirtioForwarder => create::BindingVnicType::VirtioForwarder,
            };
            port_builder.binding_vnic_type(tmp);
        }

        if let Some(val) = &args.description {
            port_builder.description(val);
        }

        if let Some(val) = &args.device_id {
            port_builder.device_id(val);
        }

        if let Some(val) = &args.device_owner {
            port_builder.device_owner(val);
        }

        if let Some(val) = &args.device_profile {
            port_builder.device_profile(Some(val.into()));
        } else if args.no_device_profile {
            port_builder.device_profile(None);
        }

        if let Some(val) = &args.dns_domain {
            port_builder.dns_domain(val);
        }

        if let Some(val) = &args.dns_name {
            port_builder.dns_name(val);
        }

        if let Some(val) = &args.extra_dhcp_opts {
            use std::collections::BTreeMap;
            port_builder.extra_dhcp_opts(
                val.iter()
                    .map(|v| {
                        v.as_object()
                            .ok_or_eyre("extra_dhcp_opts must be a valid json object")
                            .map(|obj| {
                                obj.into_iter()
                                    .map(|(k, v)| (k.into(), v.clone()))
                                    .collect::<BTreeMap<_, Value>>()
                            })
                    })
                    .collect::<Result<Vec<_>, _>>()?,
            );
        }

        if let Some(val) = &args.fixed_ips {
            let fixed_ips_builder: Vec<create::FixedIps> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<create::FixedIps>(v.to_owned()))
                .collect::<Vec<create::FixedIps>>();
            port_builder.fixed_ips(fixed_ips_builder);
        }

        if let Some(val) = &args.hints {
            port_builder.hints(val.iter().cloned());
        }

        if let Some(val) = &args.mac_address {
            port_builder.mac_address(val);
        }

        if let Some(val) = &args.name {
            port_builder.name(val);
        }

        if let Some(val) = &args.network_id {
            port_builder.network_id(val);
        }

        if let Some(val) = &args.numa_affinity_policy {
            let tmp = match val {
                NumaAffinityPolicy::Legacy => create::NumaAffinityPolicy::Legacy,
                NumaAffinityPolicy::Preferred => create::NumaAffinityPolicy::Preferred,
                NumaAffinityPolicy::Required => create::NumaAffinityPolicy::Required,
                NumaAffinityPolicy::Socket => create::NumaAffinityPolicy::Socket,
            };
            port_builder.numa_affinity_policy(tmp);
        }

        if let Some(val) = &args.port_security_enabled {
            port_builder.port_security_enabled(*val);
        }

        if let Some(val) = &args.propagate_uplink_status {
            port_builder.propagate_uplink_status(*val);
        }

        if let Some(val) = &args.qos_policy_id {
            port_builder.qos_policy_id(Some(val.into()));
        } else if args.no_qos_policy_id {
            port_builder.qos_policy_id(None);
        }

        if let Some(val) = &args.security_groups {
            port_builder.security_groups(val.iter().map(Into::into).collect::<Vec<_>>());
        }

        if let Some(val) = &args.tags {
            port_builder.tags(val.iter().map(Into::into).collect::<Vec<_>>());
        }

        if let Some(val) = &args.tenant_id {
            port_builder.tenant_id(val);
        }

        ep_builder.port(
            port_builder
                .build()
                .wrap_err("error preparing the request data")?,
        );

        let ep = ep_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;

        let data = ep.query_async(client).await?;
        op.output_single::<PortResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}