Beispiel #1
0
 def add_known_arguments(self, parser):
     parser.add_argument(
         '--name',
         help=_('Name of this router.'))
     utils.add_boolean_argument(
         parser, '--admin-state-up', dest='admin_state',
         help=_('Specify the administrative state of the router'
                ' (True meaning "Up")'))
     utils.add_boolean_argument(
         parser, '--admin_state_up', dest='admin_state',
         help=argparse.SUPPRESS)
     utils.add_boolean_argument(
         parser, '--distributed', dest='distributed',
         help=_('True means this router should operate in'
                ' distributed mode.'))
     routes_group = parser.add_mutually_exclusive_group()
     routes_group.add_argument(
         '--route', metavar='destination=CIDR,nexthop=IP_ADDR',
         action='append', dest='routes',
         type=utils.str2dict_type(required_keys=['destination', 'nexthop']),
         help=_('Route to associate with the router.'
                ' You can repeat this option.'))
     routes_group.add_argument(
         '--no-routes',
         action='store_true',
         help=_('Remove routes associated with the router.'))
def updatable_args2body(parsed_args, body, for_create=True, ip_version=None):
    if parsed_args.disable_dhcp and parsed_args.enable_dhcp:
        raise exceptions.CommandError(_(
            "You cannot enable and disable DHCP at the same time."))

    neutronV20.update_dict(parsed_args, body,
                           ['name', 'allocation_pools',
                            'host_routes', 'dns_nameservers',
                            'description'])
    if parsed_args.no_gateway:
        body['gateway_ip'] = None
    elif parsed_args.gateway:
        body['gateway_ip'] = parsed_args.gateway
    if parsed_args.disable_dhcp:
        body['enable_dhcp'] = False
    if parsed_args.enable_dhcp:
        body['enable_dhcp'] = True
    if for_create and parsed_args.ipv6_ra_mode:
        if ip_version == 4:
            raise exceptions.CommandError(_("--ipv6-ra-mode is invalid "
                                            "when --ip-version is 4"))
        body['ipv6_ra_mode'] = parsed_args.ipv6_ra_mode
    if for_create and parsed_args.ipv6_address_mode:
        if ip_version == 4:
            raise exceptions.CommandError(_("--ipv6-address-mode is "
                                            "invalid when --ip-version "
                                            "is 4"))
        body['ipv6_address_mode'] = parsed_args.ipv6_address_mode
 def _bulk_delete(self, obj_deleter, neutron_client, parsed_args_ids):
     successful_delete = []
     non_existent = []
     multiple_ids = []
     for item_id in parsed_args_ids:
         try:
             self.delete_item(obj_deleter, neutron_client, item_id)
             successful_delete.append(item_id)
         except exceptions.NotFound:
             non_existent.append(item_id)
         except exceptions.NeutronClientNoUniqueMatch:
             multiple_ids.append(item_id)
     if successful_delete:
         print((_('Deleted %(resource)s(s): %(id)s'))
               % {'id': ", ".join(successful_delete),
                  'resource': self.cmd_resource},
               file=self.app.stdout)
     if non_existent or multiple_ids:
         err_msgs = []
         if non_existent:
             err_msgs.append((_("Unable to find %(resource)s(s) with id(s) "
                                "'%(id)s'.") %
                              {'resource': self.cmd_resource,
                               'id': ", ".join(non_existent)}))
         if multiple_ids:
             err_msgs.append((_("Multiple %(resource)s(s) matches found "
                                "for name(s) '%(id)s'. Please use an ID "
                                "to be more specific.") %
                              {'resource': self.cmd_resource,
                               'id': ", ".join(multiple_ids)}))
         raise exceptions.NeutronCLIError(message='\n'.join(err_msgs))
def add_common_args(parser):
    parser.add_argument('dragent_id',
                        metavar='<agent-id>',
                        help=_("ID of the dynamic routing agent"))
    parser.add_argument('bgp_speaker',
                        metavar='<bgp-speaker>',
                        help=_("ID or name of the BGP speaker"))
    def _get_common_parser(self, parser):
        """Adds to parser arguments common to create, set and unset commands.

        :params ArgumentParser parser: argparse object contains all command's
                                       arguments
        """
        ADVERTISE_ROUTES = _("Routes will be advertised to the "
                             "BGP VPN%s") % (
                                 _(' (default)') if self._action == 'create'
                                 else "")
        NOT_ADVERTISE_ROUTES = _("Routes from the router will not be "
                                 "advertised to the BGP VPN")

        group_advertise_extra_routes = parser.add_mutually_exclusive_group()
        group_advertise_extra_routes.add_argument(
            '--advertise_extra_routes',
            action='store_true',
            help=NOT_ADVERTISE_ROUTES if self._action == 'unset'
            else ADVERTISE_ROUTES,
        )
        group_advertise_extra_routes.add_argument(
            '--no-advertise_extra_routes',
            action='store_true',
            help=ADVERTISE_ROUTES if self._action == 'unset'
            else NOT_ADVERTISE_ROUTES,
        )
def _common_args2body(client, parsed_args, is_create=True):
    if parsed_args.redirect_url:
        if parsed_args.action != 'REDIRECT_TO_URL':
            raise exceptions.CommandError(_('Action must be REDIRECT_TO_URL'))
    if parsed_args.redirect_pool:
        if parsed_args.action != 'REDIRECT_TO_POOL':
            raise exceptions.CommandError(_('Action must be REDIRECT_TO_POOL'))
        parsed_args.redirect_pool_id = _get_pool_id(
            client, parsed_args.redirect_pool)
    if (parsed_args.action == 'REDIRECT_TO_URL' and
            not parsed_args.redirect_url):
        raise exceptions.CommandError(_('Redirect URL must be specified'))
    if (parsed_args.action == 'REDIRECT_TO_POOL' and
            not parsed_args.redirect_pool):
        raise exceptions.CommandError(_('Redirect pool must be specified'))

    attributes = ['name', 'description',
                  'action', 'redirect_pool_id', 'redirect_url',
                  'position', 'admin_state_up']
    if is_create:
        parsed_args.listener_id = _get_listener_id(
            client, parsed_args.listener)
        attributes.extend(['listener_id', 'tenant_id'])
    body = {}
    neutronV20.update_dict(parsed_args, body, attributes)
    return {'l7policy': body}
def _get_attrs(client_manager, parsed_args):
    attrs = {}

    # Validate password
    if 'auth_type' in parsed_args:
        if parsed_args.auth_type != 'none':
            if 'password' not in parsed_args or parsed_args.password is None:
                raise exceptions.CommandError(_('Must provide password if '
                                                'auth-type is specified.'))
        if (
            parsed_args.auth_type == 'none' and
            parsed_args.password is not None
        ):
            raise exceptions.CommandError(_('Must provide auth-type if '
                                            'password is specified.'))
        attrs['auth_type'] = parsed_args.auth_type

    if parsed_args.name is not None:
        attrs['name'] = parsed_args.name
    if 'remote_as' in parsed_args:
        attrs['remote_as'] = parsed_args.remote_as
    if 'peer_ip' in parsed_args:
        attrs['peer_ip'] = parsed_args.peer_ip
    if 'password' in parsed_args:
        attrs['password'] = parsed_args.password

    if 'project' in parsed_args and parsed_args.project is not None:
        identity_client = client_manager.identity
        project_id = nc_osc_utils.find_project(
            identity_client,
            parsed_args.project,
            parsed_args.project_domain,
        ).id
        attrs['tenant_id'] = project_id
    return attrs
 def get_parser(self, prog_name):
     parser = super(DisassociateHealthMonitor, self).get_parser(prog_name)
     parser.add_argument("health_monitor_id", metavar="HEALTH_MONITOR_ID", help=_("Health monitor to associate."))
     parser.add_argument(
         "pool_id", metavar="POOL", help=_("ID of the pool to be associated with the health monitor.")
     )
     return parser
def _add_common_args(parser):
    parser.add_argument(
        '--description',
        help=_('Description of the load balancer.'))
    parser.add_argument(
        '--name', metavar='NAME',
        help=_('Name of the load balancer.'))
 def get_parser(self, prog_name):
     parser = super(SetSfcPortPairGroup, self).get_parser(prog_name)
     parser.add_argument(
         'port_pair_group',
         metavar='<port-pair-group>',
         help=_("Port pair group to modify (name or ID)"))
     parser.add_argument(
         '--name',
         metavar='<name>',
         help=_('Name of the port pair group'))
     parser.add_argument(
         '--description',
         metavar='<description>',
         help=_('Description for the port pair group'))
     parser.add_argument(
         '--port-pair',
         metavar='<port-pair>',
         dest='port_pairs',
         default=[],
         action='append',
         help=_('Port pair (name or ID). '
                'This option can be repeated.'))
     parser.add_argument(
         '--no-port-pair',
         action='store_true',
         help=_('Remove all port pair from port pair group'))
     return parser
Beispiel #11
0
 def get_parser(self, prog_name):
     parser = super(UnsetFirewallPolicy, self).get_parser(prog_name)
     parser.add_argument(
         const.FWP,
         metavar='<firewall-policy>',
         help=_('Firewall policy to unset (name or ID)'))
     firewall_rule_group = parser.add_mutually_exclusive_group()
     firewall_rule_group.add_argument(
         '--firewall-rule',
         action='append',
         metavar='<firewall-rule>',
         help=_('Remove firewall rule(s) from the firewall policy '
                '(name or ID)'))
     firewall_rule_group.add_argument(
         '--all-firewall-rule',
         action='store_true',
         help=_('Remove all firewall rules from the firewall policy'))
     parser.add_argument(
         '--audited',
         action='store_true',
         help=_('Disable auditing for the policy'))
     parser.add_argument(
         '--public',
         action='store_true',
         help=_('Restrict use of the firewall policy to the '
                'current project'))
     return parser
Beispiel #12
0
def _get_common_parser(parser):
    parser.add_argument(
        '--description',
        help=_('Description of the firewall policy'))
    audited_group = parser.add_mutually_exclusive_group()
    audited_group.add_argument(
        '--audited',
        action='store_true',
        help=_('Enable auditing for the policy'))
    audited_group.add_argument(
        '--no-audited',
        action='store_true',
        help=_('Disable auditing for the policy'))
    public_group = parser.add_mutually_exclusive_group()
    public_group.add_argument(
        '--public',
        action='store_true',
        help=_('Make the firewall policy public, which allows it to be '
               'used in all projects (as opposed to the default, '
               'which is to restrict its use to the current project)'))
    public_group.add_argument(
        '--private',
        action='store_true',
        help=_('Restrict use of the firewall policy to the '
               'current project'))
    return parser
Beispiel #13
0
 def get_parser(self, prog_name):
     parser = super(SetGatewayRouter, self).get_parser(prog_name)
     parser.add_argument(
         'router', metavar='ROUTER',
         help=_('ID or name of the router.'))
     parser.add_argument(
         'external_network', metavar='EXTERNAL-NETWORK',
         help=_('ID or name of the external network for the gateway.'))
     parser.add_argument(
         '--enable-snat', action='store_true',
         help=_('Enable source NAT on the router gateway.'))
     parser.add_argument(
         '--disable-snat', action='store_true',
         help=_('Disable source NAT on the router gateway.'))
     parser.add_argument(
         '--fixed-ip', metavar='subnet_id=SUBNET,ip_address=IP_ADDR',
         action='append',
         type=utils.str2dict_type(optional_keys=['subnet_id',
                                                 'ip_address']),
         help=_('Desired IP and/or subnet on external network: '
                'subnet_id=<name_or_id>,ip_address=<ip>. '
                'You can specify both of subnet_id and ip_address or '
                'specify one of them as well. '
                'You can repeat this option.'))
     return parser
def _add_common_args(parser, is_create=True):
        parser.add_argument(
            '--type',
            required=is_create,
            type=utils.convert_to_uppercase,
            choices=['HOST_NAME', 'PATH', 'FILE_TYPE', 'HEADER', 'COOKIE'],
            help=_('Rule type.'))
        parser.add_argument(
            '--compare-type',
            required=is_create,
            type=utils.convert_to_uppercase,
            choices=['REGEX', 'STARTS_WITH', 'ENDS_WITH',
                     'CONTAINS', 'EQUAL_TO'],
            help=_('Rule compare type.'))
        parser.add_argument(
            '--invert-compare',
            dest='invert',
            action='store_true',
            help=_('Invert the compare type.'))
        parser.add_argument(
            '--key',
            help=_('Key to compare.'
                   ' Relevant for HEADER and COOKIE types only.'))
        parser.add_argument(
            '--value',
            required=is_create,
            help=_('Value to compare.'))
 def add_known_arguments(self, parser):
     parser.add_argument('--name',
                         help=_('Updated name of the address scope.'))
     utils.add_boolean_argument(
         parser, '--shared',
         help=_('Set sharing of address scope. '
                '(True means shared)'))
Beispiel #16
0
def _add_updatable_args(parser):
    parser.add_argument(
        '--name',
        help=_('Name of this port.'))
    parser.add_argument(
        '--description',
        help=_('Description of this port.'))
    parser.add_argument(
        '--fixed-ip', metavar='subnet_id=SUBNET,ip_address=IP_ADDR',
        action='append',
        type=utils.str2dict_type(optional_keys=['subnet_id', 'ip_address']),
        help=_('Desired IP and/or subnet for this port: '
               'subnet_id=<name_or_id>,ip_address=<ip>. '
               'You can repeat this option.'))
    parser.add_argument(
        '--fixed_ip',
        action='append',
        help=argparse.SUPPRESS)
    parser.add_argument(
        '--device-id',
        help=_('Device ID of this port.'))
    parser.add_argument(
        '--device_id',
        help=argparse.SUPPRESS)
    parser.add_argument(
        '--device-owner',
        help=_('Device owner of this port.'))
    parser.add_argument(
        '--device_owner',
        help=argparse.SUPPRESS)
def add_common_args(parser):
    parser.add_argument(
        '--name',
        help=_('Name for the VPN service.'))
    parser.add_argument(
        '--description',
        help=_('Description for the VPN service.'))
 def run(self, parsed_args):
     self.log.debug('run(%s)', parsed_args)
     self.set_extra_attrs(parsed_args)
     neutron_client = self.get_client()
     _extra_values = parse_args_to_dict(self.values_specs)
     _merge_args(self, parsed_args, _extra_values,
                 self.values_specs)
     body = self.args2body(parsed_args)
     if self.resource in body:
         body[self.resource].update(_extra_values)
     else:
         body[self.resource] = _extra_values
     if not body[self.resource]:
         raise exceptions.CommandError(
             _("Must specify new values to update %s") %
             self.cmd_resource)
     if self.allow_names:
         _id = find_resourceid_by_name_or_id(
             neutron_client, self.resource, parsed_args.id,
             cmd_resource=self.cmd_resource, parent_id=self.parent_id)
     else:
         _id = find_resourceid_by_id(
             neutron_client, self.resource, parsed_args.id,
             self.cmd_resource, self.parent_id)
     obj_updater = getattr(neutron_client,
                           "update_%s" % self.cmd_resource)
     if self.parent_id:
         obj_updater(_id, self.parent_id, body)
     else:
         obj_updater(_id, body)
     print((_('Updated %(resource)s: %(id)s') %
            {'id': parsed_args.id, 'resource': self.resource}),
           file=self.app.stdout)
     return
 def get_parser(self, prog_name):
     parser = super(SetNetworkTrunk, self).get_parser(prog_name)
     parser.add_argument(
         'trunk',
         metavar="<trunk>",
         help=_("Trunk to modify (name or ID)")
     )
     parser.add_argument(
         '--name',
         metavar="<name>",
         help=_("Set trunk name")
     )
     parser.add_argument(
         '--subport',
         metavar='<port=,segmentation-type=,segmentation-id=>',
         action=parseractions.MultiKeyValueAction, dest='set_subports',
         help=_("Subport to add. Subport is of form "
                "\'port=<name or ID>,segmentation-type=,segmentation-ID=\'"
                "(--subport) option can be repeated)")
     )
     admin_group = parser.add_mutually_exclusive_group()
     admin_group.add_argument(
         '--enable',
         action='store_true',
         help=_("Enable trunk")
     )
     admin_group.add_argument(
         '--disable',
         action='store_true',
         help=_("Disable trunk")
     )
     return parser
def add_bandwidth_limit_arguments(parser):
    parser.add_argument(
        '--max-kbps',
        help=_('max bandwidth in kbps.'))
    parser.add_argument(
        '--max-burst-kbps',
        help=_('max burst bandwidth in kbps.'))
 def add_known_arguments(self, parser):
     parser.add_argument(
         'name',
         metavar='NAME',
         help=_('Name of the BGP peer to create.'))
     parser.add_argument(
         '--peer-ip',
         metavar='PEER_IP_ADDRESS',
         required=True,
         help=_('Peer IP address.'))
     parser.add_argument(
         '--remote-as',
         required=True,
         metavar='PEER_REMOTE_AS',
         help=_('Peer AS number. (Integer in [%(min_val)s, %(max_val)s] '
                'is allowed.)') %
         {'min_val': neutronv20.bgp.speaker.MIN_AS_NUM,
          'max_val': neutronv20.bgp.speaker.MAX_AS_NUM})
     parser.add_argument(
         '--auth-type',
         metavar='PEER_AUTH_TYPE',
         choices=['none', 'md5'],
         default='none',
         type=utils.convert_to_lowercase,
         help=_('Authentication algorithm. Supported algorithms: '
                'none(default), md5'))
     parser.add_argument(
         '--password',
         metavar='AUTH_PASSWORD',
         help=_('Authentication password.'))
Beispiel #22
0
def validate_lifetime_dict(lifetime_dict):

    for key, value in lifetime_dict.items():
        if key not in lifetime_keys:
            message = _(
                "Lifetime Dictionary KeyError: "
                "Reason-Invalid unit key : "
                "'%(key)s' not in %(supported_key)s") % {
                    'key': key, 'supported_key': lifetime_keys}
            raise exceptions.CommandError(message)
        if key == 'units' and value not in lifetime_units:
            message = _(
                "Lifetime Dictionary ValueError: "
                "Reason-Invalid units : "
                "'%(key_value)s' not in %(supported_units)s") % {
                    'key_value': key, 'supported_units': lifetime_units}
            raise exceptions.CommandError(message)
        if key == 'value':
            try:
                if int(value) < 60:
                    raise ValueError()
            except ValueError:
                message = _(
                    "Lifetime Dictionary ValueError: "
                    "Reason-Invalid value should be at least 60:"
                    "'%(key_value)s' = %(value)s") % {
                        'key_value': key, 'value': value}
                raise exceptions.CommandError(message)
            else:
                lifetime_dict['value'] = int(value)
    return
Beispiel #23
0
def validate_dpd_dict(dpd_dict):
    for key, value in dpd_dict.items():
        if key not in DPD_SUPPORTED_KEYS:
            message = _(
                "DPD Dictionary KeyError: "
                "Reason-Invalid DPD key : "
                "'%(key)s' not in %(supported_key)s") % {
                    'key': key, 'supported_key': DPD_SUPPORTED_KEYS}
            raise exceptions.CommandError(message)
        if key == 'action' and value not in DPD_SUPPORTED_ACTIONS:
            message = _(
                "DPD Dictionary ValueError: "
                "Reason-Invalid DPD action : "
                "'%(key_value)s' not in %(supported_action)s") % {
                    'key_value': value,
                    'supported_action': DPD_SUPPORTED_ACTIONS}
            raise exceptions.CommandError(message)
        if key in ('interval', 'timeout'):
            try:
                if int(value) <= 0:
                    raise ValueError()
            except ValueError:
                message = _(
                    "DPD Dictionary ValueError: "
                    "Reason-Invalid positive integer value: "
                    "'%(key)s' = %(value)s") % {
                        'key': key, 'value': value}
                raise exceptions.CommandError(message)
            else:
                dpd_dict[key] = int(value)
    return
 def add_known_arguments(self, parser):
     parser.add_argument(
         'name', metavar='NAME',
         help=_('Name of the security group to be created.'))
     parser.add_argument(
         '--description',
         help=_('Description of the security group to be created.'))
def _get_common_parser(parser):
    parser.add_argument(
        '--description',
        metavar='<description>',
        help=_('Description for the VPN service'))
    parser.add_argument(
        '--subnet',
        metavar='<subnet>',
        help=_('Local private subnet (name or ID)'))
    parser.add_argument(
        '--flavor',
        metavar='<flavor>',
        help=_('Flavor for the VPN service (name or ID)'))
    admin_group = parser.add_mutually_exclusive_group()
    admin_group.add_argument(
        '--enable',
        action='store_true',
        help=_("Enable VPN service")
    )
    admin_group.add_argument(
        '--disable',
        action='store_true',
        help=_("Disable VPN service")
    )
    return parser
 def add_known_arguments(self, parser):
     parser.add_argument(
         '--name',
         help=_('Updated name of the security group.'))
     parser.add_argument(
         '--description',
         help=_('Updated description of the security group.'))
Beispiel #27
0
 def add_known_arguments(self, parser):
     _add_common_args(parser)
     parser.add_argument(
         '--admin-state-down',
         dest='admin_state', action='store_false',
         help=_('Set admin state up to false.'))
     parser.add_argument(
         '--listener',
         help=_('Listener whose default-pool should be set to this pool. '
                'At least one of --listener or --loadbalancer must be '
                'specified.'))
     parser.add_argument(
         '--loadbalancer',
         help=_('Loadbalancer with which this pool should be associated. '
                'At least one of --listener or --loadbalancer must be '
                'specified.'))
     parser.add_argument(
         '--protocol',
         type=utils.convert_to_uppercase,
         required=True,
         choices=['HTTP', 'HTTPS', 'TCP'],
         help=_('Protocol for balancing.'))
     parser.add_argument(
         '--session-persistence',
         metavar='type=TYPE[,cookie_name=COOKIE_NAME]',
         type=utils.str2dict_type(required_keys=['type'],
                                  optional_keys=['cookie_name']),
         help=_('The type of session persistence to use and associated '
                'cookie name.'))
def _add_common_args(parser):
        parser.add_argument(
            '--name',
            help=_('Name of the member.'))
        parser.add_argument(
            '--weight',
            help=_('Weight of member in the pool (default:1, [0..256]).'))
 def get_parser(self, prog_name):
     parser = super(CreateBgpPeer, self).get_parser(prog_name)
     parser.add_argument(
         'name',
         metavar='<name>',
         help=_("Name of the BGP peer to create"))
     parser.add_argument(
         '--peer-ip',
         metavar='<peer-ip-address>',
         required=True,
         help=_("Peer IP address"))
     parser.add_argument(
         '--remote-as',
         required=True,
         metavar='<peer-remote-as>',
         help=_("Peer AS number. (Integer in [%(min_val)s, %(max_val)s] "
                "is allowed)") % {'min_val': constants.MIN_AS_NUM,
                                  'max_val': constants.MAX_AS_NUM})
     parser.add_argument(
         '--auth-type',
         metavar='<peer-auth-type>',
         choices=['none', 'md5'],
         type=nc_utils.convert_to_lowercase,
         default='none',
         help=_("Authentication algorithm. Supported algorithms: "
                "none (default), md5"))
     parser.add_argument(
         '--password',
         metavar='<auth-password>',
         help=_("Authentication password"))
     nc_osc_utils.add_project_owner_option_to_parser(parser)
     return parser
 def add_known_arguments(self, parser):
     parser.add_argument(
         '--name',
         help=_('Name of security group.'))
     parser.add_argument(
         '--description',
         help=_('Description of security group.'))
Beispiel #31
0
    def run(self, parsed_args):
        self.log.debug('run(%s)' % parsed_args)
        neutron_client = self.get_client()

        if '=' in parsed_args.interface:
            resource, value = parsed_args.interface.split('=', 1)
            if resource not in ['subnet', 'port']:
                exceptions.CommandError(
                    _('You must specify either subnet or '
                      'port for INTERFACE parameter.'))
        else:
            resource = 'subnet'
            value = parsed_args.interface

        _router_id = neutronV20.find_resourceid_by_name_or_id(
            neutron_client, self.resource, parsed_args.router)

        _interface_id = neutronV20.find_resourceid_by_name_or_id(
            neutron_client, resource, value)
        body = {'%s_id' % resource: _interface_id}

        portinfo = self.call_api(neutron_client, _router_id, body)
        print(self.success_message(parsed_args.router, portinfo),
              file=self.app.stdout)
Beispiel #32
0
    def args2body(self, parsed_args):
        resource = {
            'protocol': parsed_args.protocol,
            'protocol_port': parsed_args.protocol_port,
            'admin_state_up': parsed_args.admin_state
        }
        if not parsed_args.loadbalancer and not parsed_args.default_pool:
            message = _('Either --default-pool or --loadbalancer must be '
                        'specified.')
            raise exceptions.CommandError(message)
        if parsed_args.loadbalancer:
            loadbalancer_id = _get_loadbalancer_id(self.get_client(),
                                                   parsed_args.loadbalancer)
            resource['loadbalancer_id'] = loadbalancer_id
        if parsed_args.default_pool:
            default_pool_id = _get_pool_id(self.get_client(),
                                           parsed_args.default_pool)
            resource['default_pool_id'] = default_pool_id

        neutronV20.update_dict(parsed_args, resource, [
            'connection_limit', 'description', 'name',
            'default_tls_container_ref', 'sni_container_refs', 'tenant_id'
        ])
        return {self.resource: resource}
Beispiel #33
0
 def run(self, parsed_args):
     self.log.debug('run(%s)' % parsed_args)
     neutron_client = self.get_client()
     _router_id = neutronV20.find_resourceid_by_name_or_id(
         neutron_client, self.resource, parsed_args.router)
     _ext_net_id = neutronV20.find_resourceid_by_name_or_id(
         neutron_client, 'network', parsed_args.external_network)
     router_dict = {'network_id': _ext_net_id}
     if parsed_args.disable_snat:
         router_dict['enable_snat'] = False
     if parsed_args.fixed_ip:
         ips = []
         for ip_spec in parsed_args.fixed_ip:
             ip_dict = utils.str2dict(ip_spec)
             subnet_name_id = ip_dict.get('subnet_id')
             if subnet_name_id:
                 subnet_id = neutronV20.find_resourceid_by_name_or_id(
                     neutron_client, 'subnet', subnet_name_id)
                 ip_dict['subnet_id'] = subnet_id
             ips.append(ip_dict)
         router_dict['external_fixed_ips'] = ips
     neutron_client.add_gateway_router(_router_id, router_dict)
     print(_('Set gateway for router %s') % parsed_args.router,
           file=self.app.stdout)
Beispiel #34
0
    def args2body_extradhcpopt(self, parsed_args, port):
        ops = []
        if parsed_args.extra_dhcp_opts:
            # the extra_dhcp_opt params (opt_name & opt_value)
            # must come in pairs, if there is a parm error
            # both must be thrown out.
            opt_ele = {}
            edo_err_msg = _("Invalid --extra-dhcp-opt option, can only be: "
                            "opt_name=<dhcp_option_name>,opt_value=<value>,"
                            "ip_version={4,6}. "
                            "You can repeat this option.")
            for opt in parsed_args.extra_dhcp_opts:
                opt_ele.update(utils.str2dict(opt))
                if ('opt_name' in opt_ele and
                    ('opt_value' in opt_ele or 'ip_version' in opt_ele)):
                    if opt_ele.get('opt_value') == 'null':
                        opt_ele['opt_value'] = None
                    ops.append(opt_ele)
                    opt_ele = {}
                else:
                    raise exceptions.CommandError(edo_err_msg)

        if ops:
            port['extra_dhcp_opts'] = ops
Beispiel #35
0
class DeleteIPsecPolicy(command.Command):
    _description = _("Delete IPsec policy(policies)")

    def get_parser(self, prog_name):
        parser = super(DeleteIPsecPolicy, self).get_parser(prog_name)
        parser.add_argument('ipsecpolicy',
                            metavar='<ipsec-policy>',
                            nargs='+',
                            help=_('ipsec policy to delete (name or ID)'))
        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.neutronclient
        result = 0
        for ipsec in parsed_args.ipsecpolicy:
            try:
                ipsec_id = client.find_resource(
                    'ipsecpolicy', ipsec, cmd_resource='ipsecpolicy')['id']
                client.delete_ipsecpolicy(ipsec_id)
            except Exception as e:
                result += 1
                LOG.error(
                    _("Failed to delete IPsec policy with "
                      "name or ID '%(ipsecpolicy)s': %(e)s"), {
                          'ipsecpolicy': ipsec,
                          'e': e
                      })

        if result > 0:
            total = len(parsed_args.ipsecpolicy)
            msg = (_("%(result)s of %(total)s IPsec policy failed "
                     "to delete.") % {
                         'result': result,
                         'total': total
                     })
            raise exceptions.CommandError(msg)
Beispiel #36
0
 def get_parser(self, prog_name):
     parser = super(SetSfcPortChain, self).get_parser(prog_name)
     parser.add_argument('--name',
                         metavar='<name>',
                         help=_('Name of the port chain'))
     parser.add_argument('--description',
                         metavar='<description>',
                         help=_('Description for the port chain'))
     parser.add_argument('--flow-classifier',
                         metavar='<flow-classifier>',
                         dest='flow_classifiers',
                         action='append',
                         help=_('Add flow classifier (name or ID). '
                                'This option can be repeated.'))
     parser.add_argument(
         '--no-flow-classifier',
         action='store_true',
         help=_('Remove associated flow classifiers from the port chain'))
     parser.add_argument(
         '--port-pair-group',
         metavar='<port-pair-group>',
         dest='port_pair_groups',
         action='append',
         help=_('Add port pair group (name or ID). '
                'Current port pair groups order is kept, the added port '
                'pair group will be placed at the end of the port chain. '
                'This option can be repeated.'))
     parser.add_argument(
         '--no-port-pair-group',
         action='store_true',
         help=_('Remove associated port pair groups from the port chain. '
                'At least one --port-pair-group must be specified '
                'together.'))
     parser.add_argument('port_chain',
                         metavar='<port-chain>',
                         help=_("Port chain to modify (name or ID)"))
     return parser
 def add_known_arguments(self, parser):
     parser.add_argument(
         'name',
         help=_('Name for the Service Chain Instance.'))
     parser.add_argument(
         '--description',
         help=_('Description of the Service Chain Instance.'))
     parser.add_argument(
         '--service-chain-spec', dest='servicechain_spec',
         help=_('Service Chain Spec ID or the Service Chain Spec name'))
     parser.add_argument(
         '--provider-ptg', dest='provider_ptg',
         help=_('Destination Policy Target Group ID of the Provider.'))
     parser.add_argument(
         '--consumer-ptg', dest='consumer_ptg',
         help=_('Source Policy Target Group ID of the Consumer.'))
     parser.add_argument(
         '--param-values', dest='param_values',
         help=_('Name,Value pairs of Service Configuration Parameters for '
                'Service Chain Node.'))
Beispiel #38
0
 def get_parser(self, prog_name):
     parser = super(CreateIPsecSiteConnection, self).get_parser(prog_name)
     _get_common_parser(parser)
     parser.add_argument(
         '--peer-id',
         required=True,
         help=_('Peer router identity for authentication. Can be '
                'IPv4/IPv6 address, e-mail address, key id, or FQDN'))
     parser.add_argument(
         '--peer-address',
         required=True,
         help=_('Peer gateway public IPv4/IPv6 address or FQDN'))
     parser.add_argument('--psk',
                         required=True,
                         help=_('Pre-shared key string.'))
     parser.add_argument('--vpnservice',
                         metavar='VPNSERVICE',
                         required=True,
                         help=_('VPN service instance associated with this '
                                'connection (name or ID)'))
     parser.add_argument(
         '--ikepolicy',
         metavar='IKEPOLICY',
         required=True,
         help=_('IKE policy associated with this connection (name or ID)'))
     parser.add_argument('--ipsecpolicy',
                         metavar='IPSECPOLICY',
                         required=True,
                         help=_(
                             'IPsec policy associated with this connection '
                             '(name or ID)'))
     parser.add_argument('name',
                         metavar='<name>',
                         help=_('Set friendly name for the connection'))
     osc_utils.add_project_owner_option_to_parser(parser)
     return parser
Beispiel #39
0
def add_updatable_arguments(parser):
    parser.add_argument('--description', help=_('Description of subnetpool.'))
    parser.add_argument('--min-prefixlen',
                        type=int,
                        help=_('Subnetpool minimum prefix length.'))
    parser.add_argument('--max-prefixlen',
                        type=int,
                        help=_('Subnetpool maximum prefix length.'))
    parser.add_argument('--default-prefixlen',
                        type=int,
                        help=_('Subnetpool default prefix length.'))
    parser.add_argument(
        '--pool-prefix',
        action='append',
        dest='prefixes',
        help=_('Subnetpool prefixes (This option can be repeated).'))
    utils.add_boolean_argument(
        parser,
        '--is-default',
        help=_('Specify whether this should be the default subnetpool '
               '(True meaning default).'))
Beispiel #40
0
 def get_parser(self, prog_name):
     parser = super(CreateSfcPortPairGroup, self).get_parser(prog_name)
     parser.add_argument(
         'name',
         metavar='<name>',
         help=_('Name of the port pair group'))
     parser.add_argument(
         '--description',
         metavar='<description>',
         help=_('Description for the port pair group'))
     parser.add_argument(
         '--port-pair',
         metavar='<port-pair>',
         dest='port_pairs',
         default=[],
         action='append',
         help=_('Port pair (name or ID). '
                'This option can be repeated.'))
     tap_enable = parser.add_mutually_exclusive_group()
     tap_enable.add_argument(
         '--enable-tap',
         action='store_true',
         help=_('Port pairs of this port pair group are deployed as '
                'passive tap service function')
     )
     tap_enable.add_argument(
         '--disable-tap',
         action='store_true',
         help=_('Port pairs of this port pair group are deployed as l3 '
                'service function (default)')
     )
     parser.add_argument(
         '--port-pair-group-parameters',
         metavar='lb-fields=<lb-fields>',
         action=parseractions.KeyValueAction,
         help=_('Dictionary of port pair group parameters. '
                'Currently only one parameter lb-fields is supported. '
                '<lb-fields> is a & separated list of load-balancing '
                'fields.'))
     return parser
 def get_parser(self, prog_name):
     parser = super(SetNetworkTrunk, self).get_parser(prog_name)
     parser.add_argument(
         'trunk',
         metavar="<trunk>",
         help=_("Trunk to modify (name or ID)")
     )
     parser.add_argument(
         '--name',
         metavar="<name>",
         help=_("Set trunk name")
     )
     parser.add_argument(
         '--description',
         metavar='<description>',
         help=_("A description of the trunk")
     )
     parser.add_argument(
         '--subport',
         metavar='<port=,segmentation-type=,segmentation-id=>',
         action=parseractions.MultiKeyValueAction, dest='set_subports',
         help=_("Subport to add. Subport is of form "
                "\'port=<name or ID>,segmentation-type=,segmentation-ID=\'"
                "(--subport) option can be repeated")
     )
     admin_group = parser.add_mutually_exclusive_group()
     admin_group.add_argument(
         '--enable',
         action='store_true',
         help=_("Enable trunk")
     )
     admin_group.add_argument(
         '--disable',
         action='store_true',
         help=_("Disable trunk")
     )
     return parser
 def add_known_arguments(self, parser):
     parser.add_argument('floating_network_id',
                         metavar='FLOATING_NETWORK',
                         help=_('ID or name of the network from which '
                                'the floating IP is allocated.'))
     parser.add_argument('--description',
                         help=_('Description of the floating IP.'))
     parser.add_argument(
         '--port-id',
         help=_('ID of the port to be associated with the floating IP.'))
     parser.add_argument('--port_id', help=argparse.SUPPRESS)
     parser.add_argument(
         '--fixed-ip-address',
         help=_('IP address on the port (only required if port has '
                'multiple IPs).'))
     parser.add_argument('--fixed_ip_address', help=argparse.SUPPRESS)
     parser.add_argument('--floating-ip-address',
                         help=_('IP address of the floating IP'))
     parser.add_argument(
         '--subnet',
         dest='subnet_id',
         help=_('Subnet ID on which you want to create the floating IP.'))
     dns.add_dns_argument_create(parser, self.resource, 'domain')
     dns.add_dns_argument_create(parser, self.resource, 'name')
Beispiel #43
0
    def add_known_arguments(self, parser):
        parser.add_argument('--admin-state-down',
                            dest='admin_state',
                            action='store_false',
                            help=_('Set admin state up to false.'))
        parser.add_argument('--admin_state_down',
                            dest='admin_state',
                            action='store_false',
                            help=argparse.SUPPRESS)
        parser.add_argument('name',
                            metavar='NAME',
                            help=_('Name of the router to be created.'))
        parser.add_argument('--description', help=_('Description of router.'))
        parser.add_argument('--flavor', help=_('ID or name of flavor.'))
        utils.add_boolean_argument(parser,
                                   '--distributed',
                                   dest='distributed',
                                   help=_('Create a distributed router.'))
        utils.add_boolean_argument(parser,
                                   '--ha',
                                   dest='ha',
                                   help=_('Create a highly available router.'))

        availability_zone.add_az_hint_argument(parser, self.resource)
Beispiel #44
0
def add_common_args(parser, is_create=True):
    parser.add_argument(
        '--auth-algorithm',
        default='sha1' if is_create else argparse.SUPPRESS,
        type=utils.convert_to_lowercase,
        choices=['sha1', 'sha256', 'sha384', 'sha512'],
        help=_('Authentication algorithm for IPsec policy, default:sha1.'))
    parser.add_argument('--description',
                        help=_('Description of the IPsec policy.'))
    parser.add_argument(
        '--encapsulation-mode',
        default='tunnel' if is_create else argparse.SUPPRESS,
        choices=['tunnel', 'transport'],
        type=utils.convert_to_lowercase,
        help=_('Encapsulation mode for IPsec policy, default:tunnel.'))
    parser.add_argument(
        '--encryption-algorithm',
        default='aes-128' if is_create else argparse.SUPPRESS,
        type=utils.convert_to_lowercase,
        help=_('Encryption algorithm for IPsec policy, default:aes-128.'))
    parser.add_argument(
        '--lifetime',
        metavar="units=UNITS,value=VALUE",
        type=utils.str2dict_type(optional_keys=['units', 'value']),
        help=vpn_utils.lifetime_help("IPsec"))
    parser.add_argument(
        '--pfs',
        default='group5' if is_create else argparse.SUPPRESS,
        type=utils.convert_to_lowercase,
        help=_('Perfect Forward Secrecy for IPsec policy, default:group5.'))
    parser.add_argument(
        '--transform-protocol',
        default='esp' if is_create else argparse.SUPPRESS,
        type=utils.convert_to_lowercase,
        choices=['esp', 'ah', 'ah-esp'],
        help=_('Transform protocol for IPsec policy, default:esp.'))
Beispiel #45
0
 def get_parser(self, prog_name):
     parser = super(ListIKEPolicy, self).get_parser(prog_name)
     parser.add_argument('--long',
                         action='store_true',
                         help=_("List additional fields in output"))
     return parser
Beispiel #46
0
 def get_parser(self, prog_name):
     parser = super(RemoveGatewayRouter, self).get_parser(prog_name)
     parser.add_argument('router',
                         metavar='ROUTER',
                         help=_('ID or name of the router.'))
     return parser
Beispiel #47
0
 def success_message(self, router_id, portinfo):
     # portinfo is not used since it is None for router-interface-delete.
     return _('Removed interface from router %s.') % router_id
Beispiel #48
0
 def success_message(self, router_id, portinfo):
     return (_('Added interface %(port)s to router %(router)s.') % {
         'router': router_id,
         'port': portinfo['port_id']
     })
 class TestException(exceptions.NeutronException):
     message = _('Exception with %(reason)s')
Beispiel #50
0
 def get_parser(self, prog_name):
     parser = super(ShowNetworkTrunk, self).get_parser(prog_name)
     parser.add_argument('trunk',
                         metavar="<trunk>",
                         help=_("Trunk to display (name or ID)"))
     return parser
Beispiel #51
0
 def get_parser(self, prog_name):
     parser = super(ShowFirewallPolicy, self).get_parser(prog_name)
     parser.add_argument(const.FWP,
                         metavar='<firewall-policy>',
                         help=_('Firewall policy to show (name or ID)'))
     return parser
Beispiel #52
0
 def add_known_arguments(self, parser):
     parser.add_argument(
         '--target-tenant',
         help=_('ID of the tenant to which the RBAC '
                'policy will be enforced.'))
Beispiel #53
0
def _get_common_parser(parser):
    parser.add_argument(
        '--description',
        metavar='<description>',
        help=_('Description for the endpoint group'))
    return parser
def parse_args_to_dict(values_specs):
    """It is used to analyze the extra command options to command.

    Besides known options and arguments, our commands also support user to
    put more options to the end of command line. For example,
    list_nets -- --tag x y --key1 value1, where '-- --tag x y --key1 value1'
    is extra options to our list_nets. This feature can support V2.0 API's
    fields selection and filters. For example, to list networks which has name
    'test4', we can have list_nets -- --name=test4.

    value spec is: --key type=int|bool|... value. Type is one of Python
    built-in types. By default, type is string. The key without value is
    a bool option. Key with two values will be a list option.
    """

    # values_specs for example: '-- --tag x y --key1 type=int value1'
    # -- is a pseudo argument
    values_specs_copy = values_specs[:]
    if values_specs_copy and values_specs_copy[0] == '--':
        del values_specs_copy[0]
    # converted ArgumentParser arguments for each of the options
    _options = {}
    # the argument part for current option in _options
    current_arg = None
    # the string after remove meta info in values_specs
    # for example, '--tag x y --key1 value1'
    _values_specs = []
    # record the count of values for an option
    # for example: for '--tag x y', it is 2, while for '--key1 value1', it is 1
    _value_number = 0
    # list=true
    _list_flag = False
    # action=clear
    _clear_flag = False
    # the current item in values_specs
    current_item = None
    # the str after 'type='
    current_type_str = None
    for _item in values_specs_copy:
        if _item.startswith('--'):
            # Deal with previous argument if any
            _process_previous_argument(current_arg, _value_number,
                                       current_type_str, _list_flag,
                                       _values_specs, _clear_flag,
                                       values_specs)

            # Init variables for current argument
            current_item = _item
            _list_flag = False
            _clear_flag = False
            current_type_str = None
            if "=" in _item:
                _value_number = 1
                _item = _item.split('=')[0]
            else:
                _value_number = 0
            if _item in _options:
                raise exceptions.CommandError(
                    _("Duplicated options %s") % ' '.join(values_specs))
            else:
                _options.update({_item: {}})
            current_arg = _options[_item]
            _item = current_item
        elif _item.startswith('type='):
            if current_arg is None:
                raise exceptions.CommandError(
                    _("Invalid values_specs %s") % ' '.join(values_specs))
            if 'type' not in current_arg:
                current_type_str = _item.split('=', 2)[1]
                current_arg.update({'type': eval(current_type_str)})
                if current_type_str == 'bool':
                    current_arg.update({'type': utils.str2bool})
                elif current_type_str == 'dict':
                    current_arg.update({'type': utils.str2dict})
                continue
        elif _item == 'list=true':
            _list_flag = True
            continue
        elif _item == 'action=clear':
            _clear_flag = True
            continue

        if not _item.startswith('--'):
            # All others are value items
            # Make sure '--' occurs first and allow minus value
            if (not current_item or '=' in current_item
                    or _item.startswith('-') and not is_number(_item)):
                raise exceptions.CommandError(
                    _("Invalid values_specs %s") % ' '.join(values_specs))
            _value_number += 1

        if _item.startswith('---'):
            raise exceptions.CommandError(
                _("Invalid values_specs %s") % ' '.join(values_specs))

        _values_specs.append(_item)

    # Deal with last one argument
    _process_previous_argument(current_arg, _value_number, current_type_str,
                               _list_flag, _values_specs, _clear_flag,
                               values_specs)

    # Populate the parser with arguments
    _parser = argparse.ArgumentParser(add_help=False)
    for opt, optspec in six.iteritems(_options):
        _parser.add_argument(opt, **optspec)
    _args = _parser.parse_args(_values_specs)

    result_dict = {}
    for opt in six.iterkeys(_options):
        _opt = opt.split('--', 2)[1]
        _opt = _opt.replace('-', '_')
        _value = getattr(_args, _opt)
        result_dict.update({_opt: _value})
    return result_dict
class ListCommand(NeutronCommand, lister.Lister):
    """List resources that belong to a given tenant."""

    log = None
    _formatters = {}
    list_columns = []
    unknown_parts_flag = True
    pagination_support = False
    sorting_support = False
    resource_plural = None

    # A list to define arguments for filtering by attribute value
    # CLI arguments are shown in the order of this list.
    # Each element must be either of a string of an attribute name
    # or a dict of a full attribute definitions whose format is:
    # {'name': attribute name, (mandatory)
    #  'help': help message for CLI (mandatory)
    #  'boolean': boolean parameter or not. (Default: False) (optional)
    #  'argparse_kwargs': a dict of parameters passed to
    #                     argparse add_argument()
    #                     (Default: {}) (optional)
    # }
    # For more details, see ListNetworks.filter_attrs.
    filter_attrs = []

    default_attr_defs = {
        'name': {
            'help': _("Filter %s according to their name."),
            'boolean': False,
        },
        'tenant_id': {
            'help': _('Filter %s belonging to the given tenant.'),
            'boolean': False,
        },
        'admin_state_up': {
            'help':
            _('Filter and list the %s whose administrative '
              'state is active'),
            'boolean':
            True,
        },
    }

    def get_parser(self, prog_name):
        parser = super(ListCommand, self).get_parser(prog_name)
        add_show_list_common_argument(parser)
        if self.pagination_support:
            add_pagination_argument(parser)
        if self.sorting_support:
            add_sorting_argument(parser)
        self.add_known_arguments(parser)
        self.add_filtering_arguments(parser)
        return parser

    def add_filtering_arguments(self, parser):
        if not self.filter_attrs:
            return

        group_parser = parser.add_argument_group('filtering arguments')
        collection = self.resource_plural or '%ss' % self.resource
        for attr in self.filter_attrs:
            if isinstance(attr, str):
                # Use detail defined in default_attr_defs
                attr_name = attr
                attr_defs = self.default_attr_defs[attr]
            else:
                attr_name = attr['name']
                attr_defs = attr
            option_name = '--%s' % attr_name.replace('_', '-')
            params = attr_defs.get('argparse_kwargs', {})
            try:
                help_msg = attr_defs['help'] % collection
            except TypeError:
                help_msg = attr_defs['help']
            if attr_defs.get('boolean', False):
                add_arg_func = functools.partial(utils.add_boolean_argument,
                                                 group_parser)
            else:
                add_arg_func = group_parser.add_argument
            add_arg_func(option_name, help=help_msg, **params)

    def args2search_opts(self, parsed_args):
        search_opts = {}
        fields = parsed_args.fields
        if parsed_args.fields:
            search_opts.update({'fields': fields})
        if parsed_args.show_details:
            search_opts.update({'verbose': 'True'})
        filter_attrs = [
            field if isinstance(field, str) else field['name']
            for field in self.filter_attrs
        ]
        for attr in filter_attrs:
            val = getattr(parsed_args, attr, None)
            if attr in HYPHEN_OPTS:
                attr = attr.replace('_', '-')
            if val:
                search_opts[attr] = val
        return search_opts

    def call_server(self, neutron_client, search_opts, parsed_args):
        resource_plural = neutron_client.get_resource_plural(self.cmd_resource)
        obj_lister = getattr(neutron_client, "list_%s" % resource_plural)
        if self.parent_id:
            data = obj_lister(self.parent_id, **search_opts)
        else:
            data = obj_lister(**search_opts)
        return data

    def retrieve_list(self, parsed_args):
        """Retrieve a list of resources from Neutron server."""
        neutron_client = self.get_client()
        _extra_values = parse_args_to_dict(self.values_specs)
        _merge_args(self, parsed_args, _extra_values, self.values_specs)
        search_opts = self.args2search_opts(parsed_args)
        search_opts.update(_extra_values)
        if self.pagination_support:
            page_size = parsed_args.page_size
            if page_size:
                search_opts.update({'limit': page_size})
        if self.sorting_support:
            keys = parsed_args.sort_key
            if keys:
                search_opts.update({'sort_key': keys})
            dirs = parsed_args.sort_dir
            len_diff = len(keys) - len(dirs)
            if len_diff > 0:
                dirs += ['asc'] * len_diff
            elif len_diff < 0:
                dirs = dirs[:len(keys)]
            if dirs:
                search_opts.update({'sort_dir': dirs})
        data = self.call_server(neutron_client, search_opts, parsed_args)
        collection = neutron_client.get_resource_plural(self.resource)
        return data.get(collection, [])

    def extend_list(self, data, parsed_args):
        """Update a retrieved list.

        This method provides a way to modify an original list returned from
        the neutron server. For example, you can add subnet cidr information
        to a network list.
        """
        pass

    def setup_columns(self, info, parsed_args):
        _columns = len(info) > 0 and sorted(info[0].keys()) or []
        if not _columns:
            # clean the parsed_args.columns so that cliff will not break
            parsed_args.columns = []
        elif parsed_args.columns:
            _columns = [x for x in parsed_args.columns if x in _columns]
        elif self.list_columns:
            # if no -c(s) by user and list_columns, we use columns in
            # both list_columns and returned resource.
            # Also Keep their order the same as in list_columns
            _columns = [x for x in self.list_columns if x in _columns]

        formatters = self._formatters
        if hasattr(self, '_formatters_csv') and parsed_args.formatter == 'csv':
            formatters = self._formatters_csv

        return (
            _columns,
            (utils.get_item_properties(
                s,
                _columns,
                formatters=formatters,
            ) for s in info),
        )

    def take_action(self, parsed_args):
        self.set_extra_attrs(parsed_args)
        data = self.retrieve_list(parsed_args)
        self.extend_list(data, parsed_args)
        return self.setup_columns(data, parsed_args)
Beispiel #56
0
class UnsetFirewallPolicy(command.Command):
    _description = _("Unset firewall policy properties")

    def get_parser(self, prog_name):
        parser = super(UnsetFirewallPolicy, self).get_parser(prog_name)
        parser.add_argument(const.FWP,
                            metavar='<firewall-policy>',
                            help=_('Firewall policy to unset (name or ID)'))
        firewall_rule_group = parser.add_mutually_exclusive_group()
        firewall_rule_group.add_argument(
            '--firewall-rule',
            action='append',
            metavar='<firewall-rule>',
            help=_('Remove firewall rule(s) from the firewall policy '
                   '(name or ID)'))
        firewall_rule_group.add_argument(
            '--all-firewall-rule',
            action='store_true',
            help=_('Remove all firewall rules from the firewall policy'))
        parser.add_argument('--audited',
                            action='store_true',
                            help=_('Disable auditing for the policy'))
        parser.add_argument('--public',
                            action='store_true',
                            help=_(
                                'Restrict use of the firewall policy to the '
                                'current project'))
        return parser

    def _get_attrs(self, client_manager, parsed_args):
        attrs = {}
        client = client_manager.neutronclient

        if parsed_args.firewall_rule:
            current = client.find_resource(
                const.FWP,
                parsed_args.firewall_policy,
                cmd_resource=const.CMD_FWP)[const.FWRS]
            removed = []
            for f in set(parsed_args.firewall_rule):
                removed.append(
                    client.find_resource(const.FWR,
                                         f,
                                         cmd_resource=const.CMD_FWR)['id'])
            attrs[const.FWRS] = [r for r in current if r not in removed]
        if parsed_args.all_firewall_rule:
            attrs[const.FWRS] = []
        if parsed_args.audited:
            attrs['audited'] = False
        if parsed_args.public:
            attrs['public'] = False
        return attrs

    def take_action(self, parsed_args):
        client = self.app.client_manager.neutronclient
        fwp_id = client.find_resource(const.FWP,
                                      parsed_args.firewall_policy,
                                      cmd_resource=const.CMD_FWP)['id']
        attrs = self._get_attrs(self.app.client_manager, parsed_args)
        try:
            client.update_fwaas_firewall_policy(fwp_id, {const.FWP: attrs})
        except Exception as e:
            msg = (_("Failed to unset firewall policy '%(policy)s': %(e)s") % {
                'policy': parsed_args.firewall_policy,
                'e': e
            })
            raise exceptions.CommandError(msg)
Beispiel #57
0
 def get_parser(self, prog_name):
     parser = super(ShowIKEPolicy, self).get_parser(prog_name)
     parser.add_argument('ikepolicy',
                         metavar='<ike-policy>',
                         help=_('IKE policy to display (name or ID)'))
     return parser
 def get_parser(self, prog_name):
     parser = super(ShowBgpSpeaker, self).get_parser(prog_name)
     parser.add_argument('bgp_speaker',
                         metavar="<bgp-speaker>",
                         help=_("BGP speaker to display (name or ID)"))
     return parser
Beispiel #59
0
    def _append_global_identity_args(self, parser):
        # FIXME(bklei): these are global identity (Keystone) arguments which
        # should be consistent and shared by all service clients. Therefore,
        # they should be provided by keystoneauth1. We will need to
        # refactor this code once this functionality is available in
        # keystoneauth1.
        #
        # Note: At that time we'll need to decide if we can just abandon
        #       the deprecated args (--service-type and --endpoint-type).

        parser.add_argument(
            '--os-service-type',
            metavar='<os-service-type>',
            default=env('OS_NETWORK_SERVICE_TYPE', default='network'),
            help=_('Defaults to env[OS_NETWORK_SERVICE_TYPE] or network.'))

        parser.add_argument(
            '--os-endpoint-type',
            metavar='<os-endpoint-type>',
            default=env('OS_ENDPOINT_TYPE', default='public'),
            help=_('Defaults to env[OS_ENDPOINT_TYPE] or public.'))

        # FIXME(bklei): --service-type is deprecated but kept in for
        # backward compatibility.
        parser.add_argument('--service-type',
                            metavar='<service-type>',
                            default=env('OS_NETWORK_SERVICE_TYPE',
                                        default='network'),
                            help=_('DEPRECATED! Use --os-service-type.'))

        # FIXME(bklei): --endpoint-type is deprecated but kept in for
        # backward compatibility.
        parser.add_argument('--endpoint-type',
                            metavar='<endpoint-type>',
                            default=env('OS_ENDPOINT_TYPE', default='public'),
                            help=_('DEPRECATED! Use --os-endpoint-type.'))

        parser.add_argument('--os-auth-strategy',
                            metavar='<auth-strategy>',
                            default=env('OS_AUTH_STRATEGY',
                                        default='keystone'),
                            help=_('DEPRECATED! Only keystone is supported.'))

        parser.add_argument('--os_auth_strategy', help=argparse.SUPPRESS)

        parser.add_argument('--os-cloud',
                            metavar='<cloud>',
                            default=env('OS_CLOUD', default=None),
                            help=_('Defaults to env[OS_CLOUD].'))

        parser.add_argument(
            '--os-auth-url',
            metavar='<auth-url>',
            default=env('OS_AUTH_URL'),
            help=_('Authentication URL, defaults to env[OS_AUTH_URL].'))
        parser.add_argument('--os_auth_url', help=argparse.SUPPRESS)

        project_name_group = parser.add_mutually_exclusive_group()
        project_name_group.add_argument(
            '--os-tenant-name',
            metavar='<auth-tenant-name>',
            default=env('OS_TENANT_NAME'),
            help=_('Authentication tenant name, defaults to '
                   'env[OS_TENANT_NAME].'))
        project_name_group.add_argument(
            '--os-project-name',
            metavar='<auth-project-name>',
            default=utils.env('OS_PROJECT_NAME'),
            help='Another way to specify tenant name. '
            'This option is mutually exclusive with '
            ' --os-tenant-name. '
            'Defaults to env[OS_PROJECT_NAME].')

        parser.add_argument('--os_tenant_name', help=argparse.SUPPRESS)

        project_id_group = parser.add_mutually_exclusive_group()
        project_id_group.add_argument(
            '--os-tenant-id',
            metavar='<auth-tenant-id>',
            default=env('OS_TENANT_ID'),
            help=_('Authentication tenant ID, defaults to '
                   'env[OS_TENANT_ID].'))
        project_id_group.add_argument('--os-project-id',
                                      metavar='<auth-project-id>',
                                      default=utils.env('OS_PROJECT_ID'),
                                      help='Another way to specify tenant ID. '
                                      'This option is mutually exclusive with '
                                      ' --os-tenant-id. '
                                      'Defaults to env[OS_PROJECT_ID].')

        parser.add_argument(
            '--os-username',
            metavar='<auth-username>',
            default=utils.env('OS_USERNAME'),
            help=_('Authentication username, defaults to env[OS_USERNAME].'))
        parser.add_argument('--os_username', help=argparse.SUPPRESS)

        parser.add_argument('--os-user-id',
                            metavar='<auth-user-id>',
                            default=env('OS_USER_ID'),
                            help=_('Authentication user ID (Env: OS_USER_ID)'))

        parser.add_argument('--os_user_id', help=argparse.SUPPRESS)

        parser.add_argument('--os-user-domain-id',
                            metavar='<auth-user-domain-id>',
                            default=utils.env('OS_USER_DOMAIN_ID'),
                            help='OpenStack user domain ID. '
                            'Defaults to env[OS_USER_DOMAIN_ID].')

        parser.add_argument('--os_user_domain_id', help=argparse.SUPPRESS)

        parser.add_argument('--os-user-domain-name',
                            metavar='<auth-user-domain-name>',
                            default=utils.env('OS_USER_DOMAIN_NAME'),
                            help='OpenStack user domain name. '
                            'Defaults to env[OS_USER_DOMAIN_NAME].')

        parser.add_argument('--os_user_domain_name', help=argparse.SUPPRESS)

        parser.add_argument('--os_project_id', help=argparse.SUPPRESS)

        parser.add_argument('--os_project_name', help=argparse.SUPPRESS)

        parser.add_argument('--os-project-domain-id',
                            metavar='<auth-project-domain-id>',
                            default=utils.env('OS_PROJECT_DOMAIN_ID'),
                            help='Defaults to env[OS_PROJECT_DOMAIN_ID].')

        parser.add_argument('--os-project-domain-name',
                            metavar='<auth-project-domain-name>',
                            default=utils.env('OS_PROJECT_DOMAIN_NAME'),
                            help='Defaults to env[OS_PROJECT_DOMAIN_NAME].')

        parser.add_argument('--os-cert',
                            metavar='<certificate>',
                            default=utils.env('OS_CERT'),
                            help=_("Path of certificate file to use in SSL "
                                   "connection. This file can optionally be "
                                   "prepended with the private key. Defaults "
                                   "to env[OS_CERT]."))

        parser.add_argument('--os-cacert',
                            metavar='<ca-certificate>',
                            default=env('OS_CACERT', default=None),
                            help=_(
                                "Specify a CA bundle file to use in "
                                "verifying a TLS (https) server certificate. "
                                "Defaults to env[OS_CACERT]."))

        parser.add_argument('--os-key',
                            metavar='<key>',
                            default=utils.env('OS_KEY'),
                            help=_(
                                "Path of client key to use in SSL "
                                "connection. This option is not necessary "
                                "if your key is prepended to your certificate "
                                "file. Defaults to env[OS_KEY]."))

        parser.add_argument(
            '--os-password',
            metavar='<auth-password>',
            default=utils.env('OS_PASSWORD'),
            help=_('Authentication password, defaults to env[OS_PASSWORD].'))
        parser.add_argument('--os_password', help=argparse.SUPPRESS)

        parser.add_argument('--os-region-name',
                            metavar='<auth-region-name>',
                            default=env('OS_REGION_NAME'),
                            help=_('Authentication region name, defaults to '
                                   'env[OS_REGION_NAME].'))
        parser.add_argument('--os_region_name', help=argparse.SUPPRESS)

        parser.add_argument(
            '--os-token',
            metavar='<token>',
            default=env('OS_TOKEN'),
            help=_('Authentication token, defaults to env[OS_TOKEN].'))
        parser.add_argument('--os_token', help=argparse.SUPPRESS)

        parser.add_argument(
            '--http-timeout',
            metavar='<seconds>',
            default=env('OS_NETWORK_TIMEOUT', default=None),
            type=float,
            help=_('Timeout in seconds to wait for an HTTP response. Defaults '
                   'to env[OS_NETWORK_TIMEOUT] or None if not specified.'))

        parser.add_argument('--os-url',
                            metavar='<url>',
                            default=env('OS_URL'),
                            help=_('Defaults to env[OS_URL].'))
        parser.add_argument('--os_url', help=argparse.SUPPRESS)

        parser.add_argument(
            '--insecure',
            action='store_true',
            default=env('NEUTRONCLIENT_INSECURE', default=False),
            help=_("Explicitly allow neutronclient to perform \"insecure\" "
                   "SSL (https) requests. The server's certificate will "
                   "not be verified against any certificate authorities. "
                   "This option should be used with caution."))
Beispiel #60
0
class FirewallPolicyInsertRule(command.Command):
    _description = _("Insert a rule into a given firewall policy")

    def get_parser(self, prog_name):
        parser = super(FirewallPolicyInsertRule, self).get_parser(prog_name)
        parser.add_argument(
            const.FWP,
            metavar='<firewall-policy>',
            help=_('Firewall policy to insert rule (name or ID)'))
        parser.add_argument(
            '--insert-before',
            metavar='<firewall-rule>',
            help=_('Insert the new rule before this existing rule  '
                   '(name or ID)'))
        parser.add_argument(
            '--insert-after',
            metavar='<firewall-rule>',
            help=_('Insert the new rule after this existing rule  '
                   '(name or ID)'))
        parser.add_argument(
            const.FWR,
            metavar='<firewall-rule>',
            help=_('Firewall rule to be inserted (name or ID)'))
        return parser

    def args2body(self, parsed_args):
        client = self.app.client_manager.neutronclient
        _rule_id = _get_required_firewall_rule(client, parsed_args)
        _insert_before = ''
        if 'insert_before' in parsed_args:
            if parsed_args.insert_before:
                _insert_before = client.find_resource(
                    const.FWR,
                    parsed_args.insert_before,
                    cmd_resource=const.CMD_FWR)['id']
        _insert_after = ''
        if 'insert_after' in parsed_args:
            if parsed_args.insert_after:
                _insert_after = client.find_resource(
                    const.FWR,
                    parsed_args.insert_after,
                    cmd_resource=const.CMD_FWR)['id']
        return {
            'firewall_rule_id': _rule_id,
            'insert_before': _insert_before,
            'insert_after': _insert_after
        }

    def take_action(self, parsed_args):
        client = self.app.client_manager.neutronclient
        policy_id = client.find_resource(const.FWP,
                                         parsed_args.firewall_policy,
                                         cmd_resource=const.CMD_FWP)['id']
        body = self.args2body(parsed_args)
        client.insert_rule_fwaas_firewall_policy(policy_id, body)
        rule_id = body['firewall_rule_id']
        policy = parsed_args.firewall_policy
        print((_('Inserted firewall rule %(rule)s in firewall policy '
                 '%(policy)s') % {
                     'rule': rule_id,
                     'policy': policy
                 }),
              file=self.app.stdout)