remove unnecessary neutronclient files

Change-Id: I2684718e779fb8c85cb0dcd126d7ec4e26035a4c
This commit is contained in:
Isaku Yamahata 2014-06-27 17:51:59 +09:00
parent 2acb813816
commit 066bddc79f
36 changed files with 0 additions and 5848 deletions

View File

@ -1,61 +0,0 @@
# Copyright 2013 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from neutronclient.neutron import v2_0 as neutronV20
def _format_timestamp(component):
try:
return component['heartbeat_timestamp'].split(".", 2)[0]
except Exception:
return ''
class ListAgent(neutronV20.ListCommand):
"""List agents."""
resource = 'agent'
list_columns = ['id', 'agent_type', 'host', 'alive', 'admin_state_up',
'binary']
_formatters = {'heartbeat_timestamp': _format_timestamp}
sorting_support = True
def extend_list(self, data, parsed_args):
for agent in data:
if 'alive' in agent:
agent['alive'] = ":-)" if agent['alive'] else 'xxx'
class ShowAgent(neutronV20.ShowCommand):
"""Show information of a given agent."""
resource = 'agent'
allow_names = False
json_indent = 5
class DeleteAgent(neutronV20.DeleteCommand):
"""Delete a given agent."""
resource = 'agent'
allow_names = False
class UpdateAgent(neutronV20.UpdateCommand):
"""Update a given agent."""
resource = 'agent'
allow_names = False

View File

@ -1,277 +0,0 @@
# Copyright 2013 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from __future__ import print_function
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.neutron.v2_0 import network
from neutronclient.neutron.v2_0 import router
from neutronclient.openstack.common.gettextutils import _
PERFECT_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
class AddNetworkToDhcpAgent(neutronV20.NeutronCommand):
"""Add a network to a DHCP agent."""
def get_parser(self, prog_name):
parser = super(AddNetworkToDhcpAgent, self).get_parser(prog_name)
parser.add_argument(
'dhcp_agent',
help=_('ID of the DHCP agent'))
parser.add_argument(
'network',
help=_('Network to add'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_net_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'network', parsed_args.network)
neutron_client.add_network_to_dhcp_agent(parsed_args.dhcp_agent,
{'network_id': _net_id})
print(_('Added network %s to DHCP agent') % parsed_args.network,
file=self.app.stdout)
class RemoveNetworkFromDhcpAgent(neutronV20.NeutronCommand):
"""Remove a network from a DHCP agent."""
def get_parser(self, prog_name):
parser = super(RemoveNetworkFromDhcpAgent, self).get_parser(prog_name)
parser.add_argument(
'dhcp_agent',
help=_('ID of the DHCP agent'))
parser.add_argument(
'network',
help=_('Network to remove'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_net_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'network', parsed_args.network)
neutron_client.remove_network_from_dhcp_agent(
parsed_args.dhcp_agent, _net_id)
print(_('Removed network %s to DHCP agent') % parsed_args.network,
file=self.app.stdout)
class ListNetworksOnDhcpAgent(network.ListNetwork):
"""List the networks on a DHCP agent."""
unknown_parts_flag = False
def get_parser(self, prog_name):
parser = super(ListNetworksOnDhcpAgent,
self).get_parser(prog_name)
parser.add_argument(
'dhcp_agent',
help=_('ID of the DHCP agent'))
return parser
def call_server(self, neutron_client, search_opts, parsed_args):
data = neutron_client.list_networks_on_dhcp_agent(
parsed_args.dhcp_agent, **search_opts)
return data
class ListDhcpAgentsHostingNetwork(neutronV20.ListCommand):
"""List DHCP agents hosting a network."""
resource = 'agent'
_formatters = {}
list_columns = ['id', 'host', 'admin_state_up', 'alive']
unknown_parts_flag = False
def get_parser(self, prog_name):
parser = super(ListDhcpAgentsHostingNetwork,
self).get_parser(prog_name)
parser.add_argument(
'network',
help=_('Network to query'))
return parser
def extend_list(self, data, parsed_args):
for agent in data:
agent['alive'] = ":-)" if agent['alive'] else 'xxx'
def call_server(self, neutron_client, search_opts, parsed_args):
_id = neutronV20.find_resourceid_by_name_or_id(neutron_client,
'network',
parsed_args.network)
search_opts['network'] = _id
data = neutron_client.list_dhcp_agent_hosting_networks(**search_opts)
return data
class AddRouterToL3Agent(neutronV20.NeutronCommand):
"""Add a router to a L3 agent."""
def get_parser(self, prog_name):
parser = super(AddRouterToL3Agent, self).get_parser(prog_name)
parser.add_argument(
'l3_agent',
help=_('ID of the L3 agent'))
parser.add_argument(
'router',
help=_('Router to add'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'router', parsed_args.router)
neutron_client.add_router_to_l3_agent(parsed_args.l3_agent,
{'router_id': _id})
print(_('Added router %s to L3 agent') % parsed_args.router,
file=self.app.stdout)
class RemoveRouterFromL3Agent(neutronV20.NeutronCommand):
"""Remove a router from a L3 agent."""
def get_parser(self, prog_name):
parser = super(RemoveRouterFromL3Agent, self).get_parser(prog_name)
parser.add_argument(
'l3_agent',
help=_('ID of the L3 agent'))
parser.add_argument(
'router',
help=_('Router to remove'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'router', parsed_args.router)
neutron_client.remove_router_from_l3_agent(
parsed_args.l3_agent, _id)
print(_('Removed Router %s to L3 agent') % parsed_args.router,
file=self.app.stdout)
class ListRoutersOnL3Agent(neutronV20.ListCommand):
"""List the routers on a L3 agent."""
_formatters = {'external_gateway_info':
router._format_external_gateway_info}
list_columns = ['id', 'name', 'external_gateway_info']
resource = 'router'
unknown_parts_flag = False
def get_parser(self, prog_name):
parser = super(ListRoutersOnL3Agent,
self).get_parser(prog_name)
parser.add_argument(
'l3_agent',
help=_('ID of the L3 agent to query'))
return parser
def call_server(self, neutron_client, search_opts, parsed_args):
data = neutron_client.list_routers_on_l3_agent(
parsed_args.l3_agent, **search_opts)
return data
class ListL3AgentsHostingRouter(neutronV20.ListCommand):
"""List L3 agents hosting a router."""
resource = 'agent'
_formatters = {}
list_columns = ['id', 'host', 'admin_state_up', 'alive']
unknown_parts_flag = False
def get_parser(self, prog_name):
parser = super(ListL3AgentsHostingRouter,
self).get_parser(prog_name)
parser.add_argument('router',
help=_('Router to query'))
return parser
def extend_list(self, data, parsed_args):
for agent in data:
agent['alive'] = ":-)" if agent['alive'] else 'xxx'
def call_server(self, neutron_client, search_opts, parsed_args):
_id = neutronV20.find_resourceid_by_name_or_id(neutron_client,
'router',
parsed_args.router)
search_opts['router'] = _id
data = neutron_client.list_l3_agent_hosting_routers(**search_opts)
return data
class ListPoolsOnLbaasAgent(neutronV20.ListCommand):
"""List the pools on a loadbalancer agent."""
list_columns = ['id', 'name', 'lb_method', 'protocol',
'admin_state_up', 'status']
resource = 'pool'
unknown_parts_flag = False
def get_parser(self, prog_name):
parser = super(ListPoolsOnLbaasAgent, self).get_parser(prog_name)
parser.add_argument(
'lbaas_agent',
help=_('ID of the loadbalancer agent to query'))
return parser
def call_server(self, neutron_client, search_opts, parsed_args):
data = neutron_client.list_pools_on_lbaas_agent(
parsed_args.lbaas_agent, **search_opts)
return data
class GetLbaasAgentHostingPool(neutronV20.ListCommand):
"""Get loadbalancer agent hosting a pool.
Deriving from ListCommand though server will return only one agent
to keep common output format for all agent schedulers
"""
resource = 'agent'
list_columns = ['id', 'host', 'admin_state_up', 'alive']
unknown_parts_flag = False
def get_parser(self, prog_name):
parser = super(GetLbaasAgentHostingPool,
self).get_parser(prog_name)
parser.add_argument('pool',
help=_('Pool to query'))
return parser
def extend_list(self, data, parsed_args):
for agent in data:
agent['alive'] = ":-)" if agent['alive'] else 'xxx'
def call_server(self, neutron_client, search_opts, parsed_args):
_id = neutronV20.find_resourceid_by_name_or_id(neutron_client,
'pool',
parsed_args.pool)
search_opts['pool'] = _id
agent = neutron_client.get_lbaas_agent_hosting_pool(**search_opts)
data = {'agents': [agent['agent']]}
return data

View File

@ -1,73 +0,0 @@
# 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.
#
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListCredential(neutronV20.ListCommand):
"""List credentials that belong to a given tenant."""
resource = 'credential'
_formatters = {}
list_columns = ['credential_id', 'credential_name', 'user_name',
'password', 'type']
class ShowCredential(neutronV20.ShowCommand):
"""Show information of a given credential."""
resource = 'credential'
allow_names = False
class CreateCredential(neutronV20.CreateCommand):
"""Creates a credential."""
resource = 'credential'
def add_known_arguments(self, parser):
parser.add_argument(
'credential_name',
help=_('Name/Ip address for Credential'))
parser.add_argument(
'credential_type',
help=_('Type of the Credential'))
parser.add_argument(
'--username',
help=_('Username for the credential'))
parser.add_argument(
'--password',
help=_('Password for the credential'))
def args2body(self, parsed_args):
body = {'credential': {
'credential_name': parsed_args.credential_name}}
if parsed_args.credential_type:
body['credential'].update({'type':
parsed_args.credential_type})
if parsed_args.username:
body['credential'].update({'user_name':
parsed_args.username})
if parsed_args.password:
body['credential'].update({'password':
parsed_args.password})
return body
class DeleteCredential(neutronV20.DeleteCommand):
"""Delete a given credential."""
resource = 'credential'
allow_names = False

View File

@ -1,40 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from neutronclient.neutron import v2_0 as cmd_base
from neutronclient.openstack.common.gettextutils import _
class ListExt(cmd_base.ListCommand):
"""List all extensions."""
resource = 'extension'
list_columns = ['alias', 'name']
class ShowExt(cmd_base.ShowCommand):
"""Show information of a given resource."""
resource = "extension"
allow_names = False
def get_parser(self, prog_name):
parser = super(cmd_base.ShowCommand, self).get_parser(prog_name)
cmd_base.add_show_list_common_argument(parser)
parser.add_argument(
'id', metavar='EXT-ALIAS',
help=_('The extension alias'))
return parser

View File

@ -1,146 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from __future__ import print_function
import argparse
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListFloatingIP(neutronV20.ListCommand):
"""List floating ips that belong to a given tenant."""
resource = 'floatingip'
list_columns = ['id', 'fixed_ip_address', 'floating_ip_address',
'port_id']
pagination_support = True
sorting_support = True
class ShowFloatingIP(neutronV20.ShowCommand):
"""Show information of a given floating ip."""
resource = 'floatingip'
allow_names = False
class CreateFloatingIP(neutronV20.CreateCommand):
"""Create a floating ip for a given tenant."""
resource = 'floatingip'
def add_known_arguments(self, parser):
parser.add_argument(
'floating_network_id', metavar='FLOATING_NETWORK',
help=_('Network name or id to allocate floating IP from'))
parser.add_argument(
'--port-id',
help=_('ID of the port to be associated with the floatingip'))
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)
def args2body(self, parsed_args):
_network_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'network', parsed_args.floating_network_id)
body = {self.resource: {'floating_network_id': _network_id}}
if parsed_args.port_id:
body[self.resource].update({'port_id': parsed_args.port_id})
if parsed_args.tenant_id:
body[self.resource].update({'tenant_id': parsed_args.tenant_id})
if parsed_args.fixed_ip_address:
body[self.resource].update({'fixed_ip_address':
parsed_args.fixed_ip_address})
return body
class DeleteFloatingIP(neutronV20.DeleteCommand):
"""Delete a given floating ip."""
resource = 'floatingip'
allow_names = False
class AssociateFloatingIP(neutronV20.NeutronCommand):
"""Create a mapping between a floating ip and a fixed ip."""
api = 'network'
resource = 'floatingip'
def get_parser(self, prog_name):
parser = super(AssociateFloatingIP, self).get_parser(prog_name)
parser.add_argument(
'floatingip_id', metavar='FLOATINGIP_ID',
help=_('ID of the floating IP to associate'))
parser.add_argument(
'port_id', metavar='PORT',
help=_('ID or name of the port to be associated with the '
'floatingip'))
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)
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
update_dict = {}
if parsed_args.port_id:
update_dict['port_id'] = parsed_args.port_id
if parsed_args.fixed_ip_address:
update_dict['fixed_ip_address'] = parsed_args.fixed_ip_address
neutron_client.update_floatingip(parsed_args.floatingip_id,
{'floatingip': update_dict})
print(_('Associated floatingip %s') % parsed_args.floatingip_id,
file=self.app.stdout)
class DisassociateFloatingIP(neutronV20.NeutronCommand):
"""Remove a mapping from a floating ip to a fixed ip.
"""
api = 'network'
resource = 'floatingip'
def get_parser(self, prog_name):
parser = super(DisassociateFloatingIP, self).get_parser(prog_name)
parser.add_argument(
'floatingip_id', metavar='FLOATINGIP_ID',
help=_('ID of the floating IP to associate'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
neutron_client.update_floatingip(parsed_args.floatingip_id,
{'floatingip': {'port_id': None}})
print(_('Disassociated floatingip %s') % parsed_args.floatingip_id,
file=self.app.stdout)

View File

@ -1,90 +0,0 @@
# Copyright 2013 Big Switch Networks
# All Rights Reserved
#
# 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.
#
# @author: KC Wang, Big Switch Networks
#
import argparse
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.openstack.common.gettextutils import _
class ListFirewall(neutronv20.ListCommand):
"""List firewalls that belong to a given tenant."""
resource = 'firewall'
list_columns = ['id', 'name', 'firewall_policy_id']
_formatters = {}
pagination_support = True
sorting_support = True
class ShowFirewall(neutronv20.ShowCommand):
"""Show information of a given firewall."""
resource = 'firewall'
class CreateFirewall(neutronv20.CreateCommand):
"""Create a firewall."""
resource = 'firewall'
def add_known_arguments(self, parser):
parser.add_argument(
'firewall_policy_id', metavar='POLICY',
help=_('Firewall policy id'))
parser.add_argument(
'--name',
help=_('Name for the firewall'))
parser.add_argument(
'--description',
help=_('Description for the firewall rule'))
parser.add_argument(
'--shared',
action='store_true',
help=_('Set shared to True (default False)'),
default=argparse.SUPPRESS)
parser.add_argument(
'--admin-state-down',
dest='admin_state',
action='store_false',
help=_('Set admin state up to false'))
def args2body(self, parsed_args):
_policy_id = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'firewall_policy',
parsed_args.firewall_policy_id)
body = {
self.resource: {
'firewall_policy_id': _policy_id,
'admin_state_up': parsed_args.admin_state, }, }
neutronv20.update_dict(parsed_args, body[self.resource],
['name', 'description', 'shared',
'tenant_id'])
return body
class UpdateFirewall(neutronv20.UpdateCommand):
"""Update a given firewall."""
resource = 'firewall'
class DeleteFirewall(neutronv20.DeleteCommand):
"""Delete a given firewall."""
resource = 'firewall'

View File

@ -1,213 +0,0 @@
# Copyright 2013 Big Switch Networks
# All Rights Reserved
#
# 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.
#
# @author: KC Wang, Big Switch Networks
#
from __future__ import print_function
import argparse
import string
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.openstack.common.gettextutils import _
def _format_firewall_rules(firewall_policy):
try:
output = '[' + ',\n '.join([rule for rule in
firewall_policy['firewall_rules']]) + ']'
return output
except Exception:
return ''
class ListFirewallPolicy(neutronv20.ListCommand):
"""List firewall policies that belong to a given tenant."""
resource = 'firewall_policy'
list_columns = ['id', 'name', 'firewall_rules']
_formatters = {'firewall_rules': _format_firewall_rules,
}
pagination_support = True
sorting_support = True
class ShowFirewallPolicy(neutronv20.ShowCommand):
"""Show information of a given firewall policy."""
resource = 'firewall_policy'
class CreateFirewallPolicy(neutronv20.CreateCommand):
"""Create a firewall policy."""
resource = 'firewall_policy'
def add_known_arguments(self, parser):
parser.add_argument(
'name',
metavar='NAME',
help=_('Name for the firewall policy'))
parser.add_argument(
'--description',
help=_('Description for the firewall policy'))
parser.add_argument(
'--shared',
dest='shared',
action='store_true',
help=_('To create a shared policy'),
default=argparse.SUPPRESS)
parser.add_argument(
'--firewall-rules', type=string.split,
help=_('Ordered list of whitespace-delimited firewall rule '
'names or IDs; e.g., --firewall-rules \"rule1 rule2\"'))
parser.add_argument(
'--audited',
action='store_true',
help=_('To set audited to True'),
default=argparse.SUPPRESS)
def args2body(self, parsed_args):
if parsed_args.firewall_rules:
_firewall_rules = []
for f in parsed_args.firewall_rules:
_firewall_rules.append(
neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'firewall_rule', f))
body = {self.resource: {
'firewall_rules': _firewall_rules,
},
}
else:
body = {self.resource: {}}
neutronv20.update_dict(parsed_args, body[self.resource],
['name', 'description', 'shared',
'audited', 'tenant_id'])
return body
class UpdateFirewallPolicy(neutronv20.UpdateCommand):
"""Update a given firewall policy."""
resource = 'firewall_policy'
class DeleteFirewallPolicy(neutronv20.DeleteCommand):
"""Delete a given firewall policy."""
resource = 'firewall_policy'
class FirewallPolicyInsertRule(neutronv20.UpdateCommand):
"""Insert a rule into a given firewall policy."""
resource = 'firewall_policy'
def call_api(self, neutron_client, firewall_policy_id, body):
return neutron_client.firewall_policy_insert_rule(firewall_policy_id,
body)
def args2body(self, parsed_args):
_rule = ''
if parsed_args.firewall_rule_id:
_rule = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'firewall_rule',
parsed_args.firewall_rule_id)
_insert_before = ''
if 'insert_before' in parsed_args:
if parsed_args.insert_before:
_insert_before = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'firewall_rule',
parsed_args.insert_before)
_insert_after = ''
if 'insert_after' in parsed_args:
if parsed_args.insert_after:
_insert_after = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'firewall_rule',
parsed_args.insert_after)
body = {'firewall_rule_id': _rule,
'insert_before': _insert_before,
'insert_after': _insert_after}
neutronv20.update_dict(parsed_args, body, [])
return body
def get_parser(self, prog_name):
parser = super(FirewallPolicyInsertRule, self).get_parser(prog_name)
parser.add_argument(
'--insert-before',
metavar='FIREWALL_RULE',
help=_('Insert before this rule'))
parser.add_argument(
'--insert-after',
metavar='FIREWALL_RULE',
help=_('Insert after this rule'))
parser.add_argument(
'firewall_rule_id',
metavar='FIREWALL_RULE',
help=_('New rule to insert'))
self.add_known_arguments(parser)
return parser
def run(self, parsed_args):
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
body = self.args2body(parsed_args)
_id = neutronv20.find_resourceid_by_name_or_id(neutron_client,
self.resource,
parsed_args.id)
self.call_api(neutron_client, _id, body)
print((_('Inserted firewall rule in firewall policy %(id)s') %
{'id': parsed_args.id}), file=self.app.stdout)
class FirewallPolicyRemoveRule(neutronv20.UpdateCommand):
"""Remove a rule from a given firewall policy."""
resource = 'firewall_policy'
def call_api(self, neutron_client, firewall_policy_id, body):
return neutron_client.firewall_policy_remove_rule(firewall_policy_id,
body)
def args2body(self, parsed_args):
_rule = ''
if parsed_args.firewall_rule_id:
_rule = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'firewall_rule',
parsed_args.firewall_rule_id)
body = {'firewall_rule_id': _rule}
neutronv20.update_dict(parsed_args, body, [])
return body
def get_parser(self, prog_name):
parser = super(FirewallPolicyRemoveRule, self).get_parser(prog_name)
parser.add_argument(
'firewall_rule_id',
metavar='FIREWALL_RULE',
help=_('Firewall rule to remove from policy'))
self.add_known_arguments(parser)
return parser
def run(self, parsed_args):
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
body = self.args2body(parsed_args)
_id = neutronv20.find_resourceid_by_name_or_id(neutron_client,
self.resource,
parsed_args.id)
self.call_api(neutron_client, _id, body)
print((_('Removed firewall rule from firewall policy %(id)s') %
{'id': parsed_args.id}), file=self.app.stdout)

View File

@ -1,155 +0,0 @@
# Copyright 2013 Big Switch Networks
# All Rights Reserved
#
# 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.
#
# @author: KC Wang, Big Switch Networks
#
import argparse
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.openstack.common.gettextutils import _
class ListFirewallRule(neutronv20.ListCommand):
"""List firewall rules that belong to a given tenant."""
resource = 'firewall_rule'
list_columns = ['id', 'name', 'firewall_policy_id', 'summary', 'enabled']
pagination_support = True
sorting_support = True
def extend_list(self, data, parsed_args):
for d in data:
val = []
if d.get('protocol'):
protocol = d['protocol'].upper()
else:
protocol = 'no-protocol'
val.append(protocol)
if 'source_ip_address' in d and 'source_port' in d:
src = 'source: ' + str(d['source_ip_address']).lower()
src = src + '(' + str(d['source_port']).lower() + ')'
else:
src = 'source: none specified'
val.append(src)
if 'destination_ip_address' in d and 'destination_port' in d:
dst = 'dest: ' + str(d['destination_ip_address']).lower()
dst = dst + '(' + str(d['destination_port']).lower() + ')'
else:
dst = 'dest: none specified'
val.append(dst)
if 'action' in d:
action = d['action']
else:
action = 'no-action'
val.append(action)
d['summary'] = ',\n '.join(val)
class ShowFirewallRule(neutronv20.ShowCommand):
"""Show information of a given firewall rule."""
resource = 'firewall_rule'
class CreateFirewallRule(neutronv20.CreateCommand):
"""Create a firewall rule."""
resource = 'firewall_rule'
def add_known_arguments(self, parser):
parser.add_argument(
'--name',
help=_('Name for the firewall rule'))
parser.add_argument(
'--description',
help=_('Description for the firewall rule'))
parser.add_argument(
'--shared',
dest='shared',
action='store_true',
help=_('Set shared to True (default False)'),
default=argparse.SUPPRESS)
parser.add_argument(
'--source-ip-address',
help=_('Source ip address or subnet'))
parser.add_argument(
'--destination-ip-address',
help=_('Destination ip address or subnet'))
parser.add_argument(
'--source-port',
help=_('Source port (integer in [1, 65535] or range in a:b)'))
parser.add_argument(
'--destination-port',
help=_('Destination port (integer in [1, 65535] or range in a:b)'))
parser.add_argument(
'--disabled',
dest='enabled',
action='store_false',
help=_('To disable this rule'),
default=argparse.SUPPRESS)
parser.add_argument(
'--protocol', choices=['tcp', 'udp', 'icmp', 'any'],
required=True,
help=_('Protocol for the firewall rule'))
parser.add_argument(
'--action',
required=True,
choices=['allow', 'deny'],
help=_('Action for the firewall rule'))
def args2body(self, parsed_args):
body = {
self.resource: {},
}
neutronv20.update_dict(parsed_args, body[self.resource],
['name', 'description', 'shared', 'protocol',
'source_ip_address', 'destination_ip_address',
'source_port', 'destination_port',
'action', 'enabled', 'tenant_id'])
protocol = parsed_args.protocol
if protocol == 'any':
protocol = None
body[self.resource]['protocol'] = protocol
return body
class UpdateFirewallRule(neutronv20.UpdateCommand):
"""Update a given firewall rule."""
resource = 'firewall_rule'
def add_known_arguments(self, parser):
parser.add_argument(
'--protocol', choices=['tcp', 'udp', 'icmp', 'any'],
required=False,
help=_('Protocol for the firewall rule'))
def args2body(self, parsed_args):
body = {
self.resource: {},
}
protocol = parsed_args.protocol
if protocol:
if protocol == 'any':
protocol = None
body[self.resource]['protocol'] = protocol
return body
class DeleteFirewallRule(neutronv20.DeleteCommand):
"""Delete a given firewall rule."""
resource = 'firewall_rule'

View File

@ -1,168 +0,0 @@
# Copyright 2013 Mirantis Inc.
# All Rights Reserved
#
# 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.
#
# @author: Ilya Shakhat, Mirantis Inc.
#
from __future__ import print_function
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListHealthMonitor(neutronV20.ListCommand):
"""List healthmonitors that belong to a given tenant."""
resource = 'health_monitor'
list_columns = ['id', 'type', 'admin_state_up']
pagination_support = True
sorting_support = True
class ShowHealthMonitor(neutronV20.ShowCommand):
"""Show information of a given healthmonitor."""
resource = 'health_monitor'
class CreateHealthMonitor(neutronV20.CreateCommand):
"""Create a healthmonitor."""
resource = 'health_monitor'
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(
'--expected-codes',
help=_('The list of HTTP status codes expected in '
'response from the member to declare it healthy. This '
'attribute can contain one value, '
'or a list of values separated by comma, '
'or a range of values (e.g. "200-299"). If this attribute '
'is not specified, it defaults to "200". '))
parser.add_argument(
'--http-method',
help=_('The HTTP method used for requests by the monitor of type '
'HTTP.'))
parser.add_argument(
'--url-path',
help=_('The HTTP path used in the HTTP request used by the monitor'
' to test a member health. This must be a string '
'beginning with a / (forward slash)'))
parser.add_argument(
'--delay',
required=True,
help=_('The time in seconds between sending probes to members.'))
parser.add_argument(
'--max-retries',
required=True,
help=_('Number of permissible connection failures before changing '
'the member status to INACTIVE. [1..10]'))
parser.add_argument(
'--timeout',
required=True,
help=_('Maximum number of seconds for a monitor to wait for a '
'connection to be established before it times out. The '
'value must be less than the delay value.'))
parser.add_argument(
'--type',
required=True, choices=['PING', 'TCP', 'HTTP', 'HTTPS'],
help=_('One of predefined health monitor types'))
def args2body(self, parsed_args):
body = {
self.resource: {
'admin_state_up': parsed_args.admin_state,
'delay': parsed_args.delay,
'max_retries': parsed_args.max_retries,
'timeout': parsed_args.timeout,
'type': parsed_args.type,
},
}
neutronV20.update_dict(parsed_args, body[self.resource],
['expected_codes', 'http_method', 'url_path',
'tenant_id'])
return body
class UpdateHealthMonitor(neutronV20.UpdateCommand):
"""Update a given healthmonitor."""
resource = 'health_monitor'
allow_names = False
class DeleteHealthMonitor(neutronV20.DeleteCommand):
"""Delete a given healthmonitor."""
resource = 'health_monitor'
class AssociateHealthMonitor(neutronV20.NeutronCommand):
"""Create a mapping between a health monitor and a pool."""
resource = 'health_monitor'
def get_parser(self, prog_name):
parser = super(AssociateHealthMonitor, 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 run(self, parsed_args):
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
body = {'health_monitor': {'id': parsed_args.health_monitor_id}}
pool_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'pool', parsed_args.pool_id)
neutron_client.associate_health_monitor(pool_id, body)
print((_('Associated health monitor '
'%s') % parsed_args.health_monitor_id),
file=self.app.stdout)
class DisassociateHealthMonitor(neutronV20.NeutronCommand):
"""Remove a mapping from a health monitor to a pool."""
resource = 'health_monitor'
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 run(self, parsed_args):
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
pool_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'pool', parsed_args.pool_id)
neutron_client.disassociate_health_monitor(pool_id,
parsed_args
.health_monitor_id)
print((_('Disassociated health monitor '
'%s') % parsed_args.health_monitor_id),
file=self.app.stdout)

View File

@ -1,92 +0,0 @@
# Copyright 2013 Mirantis Inc.
# All Rights Reserved
#
# 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.
#
# @author: Ilya Shakhat, Mirantis Inc.
#
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListMember(neutronV20.ListCommand):
"""List members that belong to a given tenant."""
resource = 'member'
list_columns = [
'id', 'address', 'protocol_port', 'weight', 'admin_state_up', 'status'
]
pagination_support = True
sorting_support = True
class ShowMember(neutronV20.ShowCommand):
"""Show information of a given member."""
resource = 'member'
class CreateMember(neutronV20.CreateCommand):
"""Create a member."""
resource = 'member'
def add_known_arguments(self, parser):
parser.add_argument(
'pool_id', metavar='POOL',
help=_('Pool id or name this vip belongs to'))
parser.add_argument(
'--admin-state-down',
dest='admin_state', action='store_false',
help=_('Set admin state up to false'))
parser.add_argument(
'--weight',
help=_('Weight of pool member in the pool (default:1, [0..256])'))
parser.add_argument(
'--address',
required=True,
help=_('IP address of the pool member on the pool network. '))
parser.add_argument(
'--protocol-port',
required=True,
help=_('Port on which the pool member listens for requests or '
'connections. '))
def args2body(self, parsed_args):
_pool_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'pool', parsed_args.pool_id)
body = {
self.resource: {
'pool_id': _pool_id,
'admin_state_up': parsed_args.admin_state,
},
}
neutronV20.update_dict(
parsed_args,
body[self.resource],
['address', 'protocol_port', 'weight', 'tenant_id']
)
return body
class UpdateMember(neutronV20.UpdateCommand):
"""Update a given member."""
resource = 'member'
class DeleteMember(neutronV20.DeleteCommand):
"""Delete a given member."""
resource = 'member'

View File

@ -1,129 +0,0 @@
# Copyright 2013 Mirantis Inc.
# All Rights Reserved
#
# 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.
#
# @author: Ilya Shakhat, Mirantis Inc.
#
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
def _format_provider(pool):
return pool.get('provider') or 'N/A'
class ListPool(neutronV20.ListCommand):
"""List pools that belong to a given tenant."""
resource = 'pool'
list_columns = ['id', 'name', 'provider', 'lb_method', 'protocol',
'admin_state_up', 'status']
_formatters = {'provider': _format_provider}
pagination_support = True
sorting_support = True
class ShowPool(neutronV20.ShowCommand):
"""Show information of a given pool."""
resource = 'pool'
class CreatePool(neutronV20.CreateCommand):
"""Create a pool."""
resource = 'pool'
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(
'--description',
help=_('Description of the pool'))
parser.add_argument(
'--lb-method',
required=True,
choices=['ROUND_ROBIN', 'LEAST_CONNECTIONS', 'SOURCE_IP'],
help=_('The algorithm used to distribute load between the members '
'of the pool'))
parser.add_argument(
'--name',
required=True,
help=_('The name of the pool'))
parser.add_argument(
'--protocol',
required=True,
choices=['HTTP', 'HTTPS', 'TCP'],
help=_('Protocol for balancing'))
parser.add_argument(
'--subnet-id', metavar='SUBNET',
required=True,
help=_('The subnet on which the members of the pool will be '
'located'))
parser.add_argument(
'--provider',
help=_('Provider name of loadbalancer service'))
def args2body(self, parsed_args):
_subnet_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'subnet', parsed_args.subnet_id)
body = {
self.resource: {
'admin_state_up': parsed_args.admin_state,
'subnet_id': _subnet_id,
},
}
neutronV20.update_dict(parsed_args, body[self.resource],
['description', 'lb_method', 'name',
'protocol', 'tenant_id', 'provider'])
return body
class UpdatePool(neutronV20.UpdateCommand):
"""Update a given pool."""
resource = 'pool'
class DeletePool(neutronV20.DeleteCommand):
"""Delete a given pool."""
resource = 'pool'
class RetrievePoolStats(neutronV20.ShowCommand):
"""Retrieve stats for a given pool."""
resource = 'pool'
def get_data(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
pool_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'pool', parsed_args.id)
params = {}
if parsed_args.fields:
params = {'fields': parsed_args.fields}
data = neutron_client.retrieve_pool_stats(pool_id, **params)
self.format_output_data(data)
stats = data['stats']
if 'stats' in data:
return zip(*sorted(stats.iteritems()))
else:
return None

View File

@ -1,109 +0,0 @@
# Copyright 2013 Mirantis Inc.
# All Rights Reserved
#
# 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.
#
# @author: Ilya Shakhat, Mirantis Inc.
#
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListVip(neutronV20.ListCommand):
"""List vips that belong to a given tenant."""
resource = 'vip'
list_columns = ['id', 'name', 'algorithm', 'address', 'protocol',
'admin_state_up', 'status']
pagination_support = True
sorting_support = True
class ShowVip(neutronV20.ShowCommand):
"""Show information of a given vip."""
resource = 'vip'
class CreateVip(neutronV20.CreateCommand):
"""Create a vip."""
resource = 'vip'
def add_known_arguments(self, parser):
parser.add_argument(
'pool_id', metavar='POOL',
help=_('Pool id or name this vip belongs to'))
parser.add_argument(
'--address',
help=_('IP address of the vip'))
parser.add_argument(
'--admin-state-down',
dest='admin_state', action='store_false',
help=_('Set admin state up to false'))
parser.add_argument(
'--connection-limit',
help=_('The maximum number of connections per second allowed for '
'the vip. Positive integer or -1 for unlimited (default)'))
parser.add_argument(
'--description',
help=_('Description of the vip'))
parser.add_argument(
'--name',
required=True,
help=_('Name of the vip'))
parser.add_argument(
'--protocol-port',
required=True,
help=_('TCP port on which to listen for client traffic that is '
'associated with the vip address'))
parser.add_argument(
'--protocol',
required=True, choices=['TCP', 'HTTP', 'HTTPS'],
help=_('Protocol for balancing'))
parser.add_argument(
'--subnet-id', metavar='SUBNET',
required=True,
help=_('The subnet on which to allocate the vip address'))
def args2body(self, parsed_args):
_pool_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'pool', parsed_args.pool_id)
_subnet_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'subnet', parsed_args.subnet_id)
body = {
self.resource: {
'pool_id': _pool_id,
'admin_state_up': parsed_args.admin_state,
'subnet_id': _subnet_id,
},
}
neutronV20.update_dict(parsed_args, body[self.resource],
['address', 'connection_limit', 'description',
'name', 'protocol_port', 'protocol',
'tenant_id'])
return body
class UpdateVip(neutronV20.UpdateCommand):
"""Update a given vip."""
resource = 'vip'
class DeleteVip(neutronV20.DeleteCommand):
"""Delete a given vip."""
resource = 'vip'

View File

@ -1,135 +0,0 @@
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Sylvain Afchain <sylvain.afchain@enovance.com>
#
# 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.
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.openstack.common.gettextutils import _
class ListMeteringLabel(neutronv20.ListCommand):
"""List metering labels that belong to a given tenant."""
resource = 'metering_label'
list_columns = ['id', 'name', 'description', 'shared']
pagination_support = True
sorting_support = True
class ShowMeteringLabel(neutronv20.ShowCommand):
"""Show information of a given metering label."""
resource = 'metering_label'
allow_names = True
class CreateMeteringLabel(neutronv20.CreateCommand):
"""Create a metering label for a given tenant."""
resource = 'metering_label'
def add_known_arguments(self, parser):
parser.add_argument(
'name', metavar='NAME',
help=_('Name of metering label to create'))
parser.add_argument(
'--description',
help=_('Description of metering label to create'))
parser.add_argument(
'--shared',
action='store_true',
help=_('Set the label as shared'))
def args2body(self, parsed_args):
body = {'metering_label': {
'name': parsed_args.name}, }
if parsed_args.tenant_id:
body['metering_label'].update({'tenant_id': parsed_args.tenant_id})
if parsed_args.description:
body['metering_label'].update(
{'description': parsed_args.description})
if parsed_args.shared:
body['metering_label'].update(
{'shared': True})
return body
class DeleteMeteringLabel(neutronv20.DeleteCommand):
"""Delete a given metering label."""
resource = 'metering_label'
allow_names = True
class ListMeteringLabelRule(neutronv20.ListCommand):
"""List metering labels that belong to a given label."""
resource = 'metering_label_rule'
list_columns = ['id', 'excluded', 'direction', 'remote_ip_prefix']
pagination_support = True
sorting_support = True
class ShowMeteringLabelRule(neutronv20.ShowCommand):
"""Show information of a given metering label rule."""
resource = 'metering_label_rule'
class CreateMeteringLabelRule(neutronv20.CreateCommand):
"""Create a metering label rule for a given label."""
resource = 'metering_label_rule'
def add_known_arguments(self, parser):
parser.add_argument(
'label_id', metavar='LABEL',
help=_('Id or Name of the label'))
parser.add_argument(
'remote_ip_prefix', metavar='REMOTE_IP_PREFIX',
help=_('CIDR to match on'))
parser.add_argument(
'--direction',
default='ingress', choices=['ingress', 'egress'],
help=_('Direction of traffic, default:ingress'))
parser.add_argument(
'--excluded',
action='store_true',
help=_('Exclude this cidr from the label, default:not excluded'))
def args2body(self, parsed_args):
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
label_id = neutronv20.find_resourceid_by_name_or_id(
neutron_client, 'metering_label', parsed_args.label_id)
body = {'metering_label_rule': {
'metering_label_id': label_id,
'remote_ip_prefix': parsed_args.remote_ip_prefix
}}
if parsed_args.direction:
body['metering_label_rule'].update(
{'direction': parsed_args.direction})
if parsed_args.excluded:
body['metering_label_rule'].update(
{'excluded': True})
return body
class DeleteMeteringLabelRule(neutronv20.DeleteCommand):
"""Delete a given metering label."""
resource = 'metering_label_rule'

View File

@ -1,243 +0,0 @@
# Copyright 2014 NEC Corporation
# All Rights Reserved
#
# 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.
import logging
from neutronclient.common import exceptions
from neutronclient.common import validators
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListPacketFilter(neutronV20.ListCommand):
"""List packet filters that belong to a given tenant."""
resource = 'packet_filter'
log = logging.getLogger(__name__ + '.ListPacketFilter')
list_columns = ['id', 'name', 'action', 'priority', 'summary']
pagination_support = True
sorting_support = True
def extend_list(self, data, parsed_args):
for d in data:
val = []
proto_eth_type = []
if d.get('protocol'):
proto_eth_type.append('protocol: %s' % d['protocol'].upper())
if d.get('eth_type'):
proto_eth_type.append('eth_type: %s' % d['eth_type'])
if proto_eth_type:
val.append(', '.join(proto_eth_type))
val.append('network: ' + d['network_id'])
if d.get('in_port'):
val.append('in_port: ' + d['in_port'])
source = [str(d.get(field)) for field
in ['src_mac', 'src_cidr', 'src_port'] if d.get(field)]
if source:
val.append('source: ' + ' '.join(source))
dest = [str(d.get(field)) for field
in ['dst_mac', 'dst_cidr', 'dst_port'] if d.get(field)]
if dest:
val.append('destination: ' + ' '.join(dest))
d['summary'] = '\n'.join(val)
class ShowPacketFilter(neutronV20.ShowCommand):
"""Show information of a given packet filter."""
resource = 'packet_filter'
log = logging.getLogger(__name__ + '.ShowPacketFilter')
class PacketFilterOptionMixin(object):
def add_known_arguments(self, parser):
mode = self._get_mode()
if not mode:
return
mode_create = mode == 'create'
if mode_create:
parser.add_argument(
'--admin-state-down',
dest='admin_state', action='store_false',
help=_('Set Admin State Up to false'))
else:
parser.add_argument(
'--admin-state', choices=['True', 'False'],
help=_('Set a value of Admin State Up'))
parser.add_argument(
'--name',
help=_('Name of this packet filter'))
if mode_create:
parser.add_argument(
'--in-port', metavar='PORT',
help=_('Name or ID of the input port'))
parser.add_argument(
'--src-mac',
help=_('Source MAC address'))
parser.add_argument(
'--dst-mac',
help=_('Destination MAC address'))
parser.add_argument(
'--eth-type',
help=_('Ether Type. Integer [0:65535] (hex or decimal).'
' E.g., 0x0800 (IPv4), 0x0806 (ARP), 0x86DD (IPv6)'))
parser.add_argument(
'--protocol',
help=_('IP Protocol.'
' Protocol name or integer.'
' Recognized names are icmp, tcp, udp, arp'
' (case insensitive).'
' Integer should be [0:255] (decimal or hex).'))
parser.add_argument(
'--src-cidr',
help=_('Source IP address CIDR'))
parser.add_argument(
'--dst-cidr',
help=_('Destination IP address CIDR'))
parser.add_argument(
'--src-port',
help=_('Source port address'))
parser.add_argument(
'--dst-port',
help=_('Destination port address'))
default_priority = '30000' if mode_create else None
parser.add_argument(
'--priority', metavar='PRIORITY',
default=default_priority,
help=(_('Priority of the filter. Integer of [0:65535].%s')
% (' Default: 30000.' if mode_create else '')))
default_action = 'allow' if mode_create else None
parser.add_argument(
'--action',
choices=['allow', 'drop'],
default=default_action,
help=(_('Action of the filter.%s')
% (' Default: allow' if mode_create else '')))
if mode_create:
parser.add_argument(
'network', metavar='NETWORK',
help=_('network to which this packet filter is applied'))
def _get_mode(self):
klass = self.__class__.__name__.lower()
if klass.startswith('create'):
mode = 'create'
elif klass.startswith('update'):
mode = 'update'
else:
mode = None
return mode
def validate_fields(self, parsed_args):
self._validate_protocol(parsed_args.protocol)
validators.validate_int_range(parsed_args, 'priority', 0, 0xffff)
validators.validate_int_range(parsed_args, 'src_port', 0, 0xffff)
validators.validate_int_range(parsed_args, 'dst_port', 0, 0xffff)
validators.validate_ip_subnet(parsed_args, 'src_cidr')
validators.validate_ip_subnet(parsed_args, 'dst_cidr')
def _validate_protocol(self, protocol):
if not protocol or protocol == 'action=clear':
return
try:
protocol = int(protocol, 0)
if 0 <= protocol <= 255:
return
except ValueError:
# Use string as a protocol name
# Exact check will be done in the server side.
return
msg = (_('protocol %s should be either of name '
'(tcp, udp, icmp, arp; '
'case insensitive) or integer [0:255] (decimal or hex).') %
protocol)
raise exceptions.CommandError(msg)
class CreatePacketFilter(PacketFilterOptionMixin,
neutronV20.CreateCommand):
"""Create a packet filter for a given tenant."""
resource = 'packet_filter'
log = logging.getLogger(__name__ + '.CreatePacketFilter')
def args2body(self, parsed_args):
self.validate_fields(parsed_args)
_network_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'network', parsed_args.network)
body = {'network_id': _network_id,
'admin_state_up': parsed_args.admin_state}
if parsed_args.in_port:
_port_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'port', parsed_args.in_port)
body['in_port'] = _port_id
neutronV20.update_dict(
parsed_args, body,
['action', 'priority', 'name',
'eth_type', 'protocol', 'src_mac', 'dst_mac',
'src_cidr', 'dst_cidr', 'src_port', 'dst_port'])
return {self.resource: body}
class UpdatePacketFilter(PacketFilterOptionMixin,
neutronV20.UpdateCommand):
"""Update packet filter's information."""
resource = 'packet_filter'
log = logging.getLogger(__name__ + '.UpdatePacketFilter')
def args2body(self, parsed_args):
self.validate_fields(parsed_args)
body = {}
if parsed_args.admin_state:
body['admin_state_up'] = (parsed_args.admin_state == 'True')
# fields which allows None
for attr in ['eth_type', 'protocol', 'src_mac', 'dst_mac',
'src_cidr', 'dst_cidr', 'src_port', 'dst_port']:
if not hasattr(parsed_args, attr):
continue
val = getattr(parsed_args, attr)
if val is None:
continue
if val == '' or val == 'action=clear':
body[attr] = None
else:
body[attr] = val
for attr in ['action', 'priority', 'name']:
if (hasattr(parsed_args, attr) and
getattr(parsed_args, attr) is not None):
body[attr] = getattr(parsed_args, attr)
return {self.resource: body}
class DeletePacketFilter(neutronV20.DeleteCommand):
"""Delete a given packet filter."""
resource = 'packet_filter'
log = logging.getLogger(__name__ + '.DeletePacketFilter')

View File

@ -1,53 +0,0 @@
# Copyright 2014 Alcatel-Lucent USA Inc.
#
# 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.
#
# @author: Ronak Shah, Nuage Networks, Alcatel-Lucent USA Inc.
from neutronclient.neutron.v2_0 import CreateCommand
from neutronclient.neutron.v2_0 import DeleteCommand
from neutronclient.neutron.v2_0 import ListCommand
from neutronclient.neutron.v2_0 import ShowCommand
class ListNetPartition(ListCommand):
"""List netpartitions that belong to a given tenant."""
resource = 'net_partition'
list_columns = ['id', 'name']
class ShowNetPartition(ShowCommand):
"""Show information of a given netpartition."""
resource = 'net_partition'
class CreateNetPartition(CreateCommand):
"""Create a netpartition for a given tenant."""
resource = 'net_partition'
def add_known_arguments(self, parser):
parser.add_argument(
'name', metavar='name',
help='Name of NetPartition to create')
def args2body(self, parsed_args):
body = {'net_partition': {'name': parsed_args.name}, }
return body
class DeleteNetPartition(DeleteCommand):
"""Delete a given netpartition."""
resource = 'net_partition'

View File

@ -1,144 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
import argparse
from neutronclient.common import exceptions
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
def _format_subnets(network):
try:
return '\n'.join([' '.join([s['id'], s.get('cidr', '')])
for s in network['subnets']])
except Exception:
return ''
class ListNetwork(neutronV20.ListCommand):
"""List networks that belong to a given tenant."""
# Length of a query filter on subnet id
# id=<uuid>& (with len(uuid)=36)
subnet_id_filter_len = 40
resource = 'network'
_formatters = {'subnets': _format_subnets, }
list_columns = ['id', 'name', 'subnets']
pagination_support = True
sorting_support = True
def extend_list(self, data, parsed_args):
"""Add subnet information to a network list."""
neutron_client = self.get_client()
search_opts = {'fields': ['id', 'cidr']}
if self.pagination_support:
page_size = parsed_args.page_size
if page_size:
search_opts.update({'limit': page_size})
subnet_ids = []
for n in data:
if 'subnets' in n:
subnet_ids.extend(n['subnets'])
def _get_subnet_list(sub_ids):
search_opts['id'] = sub_ids
return neutron_client.list_subnets(
**search_opts).get('subnets', [])
try:
subnets = _get_subnet_list(subnet_ids)
except exceptions.RequestURITooLong as uri_len_exc:
# The URI is too long because of too many subnet_id filters
# Use the excess attribute of the exception to know how many
# subnet_id filters can be inserted into a single request
subnet_count = len(subnet_ids)
max_size = ((self.subnet_id_filter_len * subnet_count) -
uri_len_exc.excess)
chunk_size = max_size / self.subnet_id_filter_len
subnets = []
for i in range(0, subnet_count, chunk_size):
subnets.extend(
_get_subnet_list(subnet_ids[i: i + chunk_size]))
subnet_dict = dict([(s['id'], s) for s in subnets])
for n in data:
if 'subnets' in n:
n['subnets'] = [(subnet_dict.get(s) or {"id": s})
for s in n['subnets']]
class ListExternalNetwork(ListNetwork):
"""List external networks that belong to a given tenant."""
pagination_support = True
sorting_support = True
def retrieve_list(self, parsed_args):
external = '--router:external=True'
if external not in self.values_specs:
self.values_specs.append('--router:external=True')
return super(ListExternalNetwork, self).retrieve_list(parsed_args)
class ShowNetwork(neutronV20.ShowCommand):
"""Show information of a given network."""
resource = 'network'
class CreateNetwork(neutronV20.CreateCommand):
"""Create a network for a given tenant."""
resource = 'network'
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(
'--shared',
action='store_true',
help=_('Set the network as shared'),
default=argparse.SUPPRESS)
parser.add_argument(
'name', metavar='NAME',
help=_('Name of network to create'))
def args2body(self, parsed_args):
body = {'network': {
'name': parsed_args.name,
'admin_state_up': parsed_args.admin_state}, }
neutronV20.update_dict(parsed_args, body['network'],
['shared', 'tenant_id'])
return body
class DeleteNetwork(neutronV20.DeleteCommand):
"""Delete a given network."""
resource = 'network'
class UpdateNetwork(neutronV20.UpdateCommand):
"""Update network's information."""
resource = 'network'

View File

@ -1,128 +0,0 @@
# 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.
#
#@author Abhishek Raut, Cisco Systems
#@author Sergey Sudakovich, Cisco Systems
#@author Rudrajit Tapadar, Cisco Systems
from __future__ import print_function
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.neutron.v2_0 import parse_args_to_dict
from neutronclient.openstack.common.gettextutils import _
RESOURCE = 'network_profile'
SEGMENT_TYPE_CHOICES = ['vlan', 'overlay', 'multi-segment', 'trunk']
class ListNetworkProfile(neutronV20.ListCommand):
"""List network profiles that belong to a given tenant."""
resource = RESOURCE
_formatters = {}
list_columns = ['id', 'name', 'segment_type', 'sub_type', 'segment_range',
'physical_network', 'multicast_ip_index',
'multicast_ip_range']
class ShowNetworkProfile(neutronV20.ShowCommand):
"""Show information of a given network profile."""
resource = RESOURCE
allow_names = True
class CreateNetworkProfile(neutronV20.CreateCommand):
"""Creates a network profile."""
resource = RESOURCE
def add_known_arguments(self, parser):
parser.add_argument('name',
help=_('Name for Network Profile'))
parser.add_argument('segment_type',
choices=SEGMENT_TYPE_CHOICES,
help='Segment type')
# TODO(Abhishek): Check on sub-type choices depending on segment_type
parser.add_argument('--sub_type',
help=_('Sub-type for the segment. Available sub-'
'types for overlay segments: native, enhanced; '
'For trunk segments: vlan, overlay.'))
parser.add_argument('--segment_range',
help=_('Range for the Segment'))
parser.add_argument('--physical_network',
help=_('Name for the Physical Network'))
parser.add_argument('--multicast_ip_range',
help=_('Multicast IPv4 Range'))
parser.add_argument("--add-tenant",
help=_("Add tenant to the network profile"))
def args2body(self, parsed_args):
body = {'network_profile': {'name': parsed_args.name}}
if parsed_args.segment_type:
body['network_profile'].update({'segment_type':
parsed_args.segment_type})
if parsed_args.sub_type:
body['network_profile'].update({'sub_type':
parsed_args.sub_type})
if parsed_args.segment_range:
body['network_profile'].update({'segment_range':
parsed_args.segment_range})
if parsed_args.physical_network:
body['network_profile'].update({'physical_network':
parsed_args.physical_network})
if parsed_args.multicast_ip_range:
body['network_profile'].update({'multicast_ip_range':
parsed_args.multicast_ip_range})
if parsed_args.add_tenant:
body['network_profile'].update({'add_tenant':
parsed_args.add_tenant})
return body
class DeleteNetworkProfile(neutronV20.DeleteCommand):
"""Delete a given network profile."""
resource = RESOURCE
allow_names = True
class UpdateNetworkProfile(neutronV20.UpdateCommand):
"""Update network profile's information."""
resource = RESOURCE
class UpdateNetworkProfileV2(neutronV20.NeutronCommand):
api = 'network'
resource = RESOURCE
def get_parser(self, prog_name):
parser = super(UpdateNetworkProfileV2, self).get_parser(prog_name)
parser.add_argument("--remove-tenant",
help="Remove tenant from the network profile")
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
data = {self.resource: parse_args_to_dict(parsed_args)}
if parsed_args.remove_tenant:
data[self.resource]['remove_tenant'] = parsed_args.remove_tenant
neutron_client.update_network_profile(parsed_args.id,
{self.resource: data})
print((_('Updated %(resource)s: %(id)s') %
{'id': parsed_args.id, 'resource': self.resource}),
file=self.app.stdout)
return

View File

@ -1,267 +0,0 @@
# Copyright 2013 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from __future__ import print_function
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
GW_RESOURCE = 'network_gateway'
DEV_RESOURCE = 'gateway_device'
CONNECTOR_TYPE_HELP = _("Type of the transport zone connector to use for this "
"device. Valid values are gre, stt, ipsecgre, "
"ipsecstt, and bridge. Defaults to stt")
CONNECTOR_IP_HELP = _("IP address for this device's transport connector. "
"It must correspond to the IP address of the interface "
"used for tenant traffic on the NSX gateway node")
CLIENT_CERT_HELP = _("PEM certificate used by the NSX gateway transport node "
"to authenticate with the NSX controller")
CLIENT_CERT_FILE_HELP = _("File containing the PEM certificate used by the "
"NSX gateway transport node to authenticate with "
"the NSX controller")
class ListGatewayDevice(neutronV20.ListCommand):
"""List network gateway devices for a given tenant."""
resource = DEV_RESOURCE
list_columns = ['id', 'name']
class ShowGatewayDevice(neutronV20.ShowCommand):
"""Show information for a given network gateway device."""
resource = DEV_RESOURCE
def read_cert_file(cert_file):
return open(cert_file, 'rb').read()
def gateway_device_args2body(parsed_args):
body = {}
if parsed_args.name:
body['name'] = parsed_args.name
if parsed_args.connector_type:
body['connector_type'] = parsed_args.connector_type
if parsed_args.connector_ip:
body['connector_ip'] = parsed_args.connector_ip
cert_data = None
if parsed_args.cert_file:
cert_data = read_cert_file(parsed_args.cert_file)
elif parsed_args.cert_data:
cert_data = parsed_args.cert_data
if cert_data:
body['client_certificate'] = cert_data
if getattr(parsed_args, 'tenant_id', None):
body['tenant_id'] = parsed_args.tenant_id
return {DEV_RESOURCE: body}
class CreateGatewayDevice(neutronV20.CreateCommand):
"""Create a network gateway device."""
resource = DEV_RESOURCE
def add_known_arguments(self, parser):
parser.add_argument(
'name', metavar='NAME',
help='Name of network gateway device to create')
parser.add_argument(
'--connector-type',
default='stt',
choices=['stt', 'gre', 'ipsecgre', 'ipsecstt', 'bridge'],
help=CONNECTOR_TYPE_HELP)
parser.add_argument(
'--connector-ip',
required=True,
help=CONNECTOR_IP_HELP)
client_cert_group = parser.add_mutually_exclusive_group(
required=True)
client_cert_group.add_argument(
'--client-certificate',
dest='cert_data',
help=CLIENT_CERT_HELP)
client_cert_group.add_argument(
'--client-certificate-file',
dest='cert_file',
help=CLIENT_CERT_FILE_HELP)
def args2body(self, parsed_args):
return gateway_device_args2body(parsed_args)
class UpdateGatewayDevice(neutronV20.UpdateCommand):
"""Update a network gateway device."""
resource = DEV_RESOURCE
def add_known_arguments(self, parser):
parser.add_argument(
'--name', metavar='NAME',
help='New name for network gateway device')
parser.add_argument(
'--connector-type',
required=False,
choices=['stt', 'gre', 'ipsecgre', 'ipsecstt', 'bridge'],
help=CONNECTOR_TYPE_HELP)
parser.add_argument(
'--connector-ip',
required=False,
help=CONNECTOR_IP_HELP)
client_cert_group = parser.add_mutually_exclusive_group()
client_cert_group.add_argument(
'--client-certificate',
dest='cert_data',
help=CLIENT_CERT_HELP)
client_cert_group.add_argument(
'--client-certificate-file',
dest='cert_file',
help=CLIENT_CERT_FILE_HELP)
def args2body(self, parsed_args):
return gateway_device_args2body(parsed_args)
class DeleteGatewayDevice(neutronV20.DeleteCommand):
"""Delete a given network gateway device."""
resource = DEV_RESOURCE
class ListNetworkGateway(neutronV20.ListCommand):
"""List network gateways for a given tenant."""
resource = GW_RESOURCE
list_columns = ['id', 'name']
class ShowNetworkGateway(neutronV20.ShowCommand):
"""Show information of a given network gateway."""
resource = GW_RESOURCE
class CreateNetworkGateway(neutronV20.CreateCommand):
"""Create a network gateway."""
resource = GW_RESOURCE
def add_known_arguments(self, parser):
parser.add_argument(
'name', metavar='NAME',
help=_('Name of network gateway to create'))
parser.add_argument(
'--device', metavar='id=ID,interface_name=NAME_OR_ID',
action='append',
help=_('Device info for this gateway. You can repeat this '
'option for multiple devices for HA gateways'))
def args2body(self, parsed_args):
body = {self.resource: {
'name': parsed_args.name}}
devices = []
if parsed_args.device:
for device in parsed_args.device:
devices.append(utils.str2dict(device))
if devices:
body[self.resource].update({'devices': devices})
if parsed_args.tenant_id:
body[self.resource].update({'tenant_id': parsed_args.tenant_id})
return body
class DeleteNetworkGateway(neutronV20.DeleteCommand):
"""Delete a given network gateway."""
resource = GW_RESOURCE
class UpdateNetworkGateway(neutronV20.UpdateCommand):
"""Update the name for a network gateway."""
resource = GW_RESOURCE
class NetworkGatewayInterfaceCommand(neutronV20.NeutronCommand):
"""Base class for connecting/disconnecting networks to/from a gateway."""
resource = GW_RESOURCE
def get_parser(self, prog_name):
parser = super(NetworkGatewayInterfaceCommand,
self).get_parser(prog_name)
parser.add_argument(
'net_gateway_id', metavar='NET-GATEWAY-ID',
help=_('ID of the network gateway'))
parser.add_argument(
'network_id', metavar='NETWORK-ID',
help=_('ID of the internal network to connect on the gateway'))
parser.add_argument(
'--segmentation-type',
help=_('L2 segmentation strategy on the external side of '
'the gateway (e.g.: VLAN, FLAT)'))
parser.add_argument(
'--segmentation-id',
help=_('Identifier for the L2 segment on the external side '
'of the gateway'))
return parser
def retrieve_ids(self, client, args):
gateway_id = neutronV20.find_resourceid_by_name_or_id(
client, self.resource, args.net_gateway_id)
network_id = neutronV20.find_resourceid_by_name_or_id(
client, 'network', args.network_id)
return (gateway_id, network_id)
class ConnectNetworkGateway(NetworkGatewayInterfaceCommand):
"""Add an internal network interface to a router."""
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
(gateway_id, network_id) = self.retrieve_ids(neutron_client,
parsed_args)
neutron_client.connect_network_gateway(
gateway_id, {'network_id': network_id,
'segmentation_type': parsed_args.segmentation_type,
'segmentation_id': parsed_args.segmentation_id})
# TODO(Salvatore-Orlando): Do output formatting as
# any other command
print(_('Connected network to gateway %s') % gateway_id,
file=self.app.stdout)
class DisconnectNetworkGateway(NetworkGatewayInterfaceCommand):
"""Remove a network from a network gateway."""
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
(gateway_id, network_id) = self.retrieve_ids(neutron_client,
parsed_args)
neutron_client.disconnect_network_gateway(
gateway_id, {'network_id': network_id,
'segmentation_type': parsed_args.segmentation_type,
'segmentation_id': parsed_args.segmentation_id})
# TODO(Salvatore-Orlando): Do output formatting as
# any other command
print(_('Disconnected network from gateway %s') % gateway_id,
file=self.app.stdout)

View File

@ -1,82 +0,0 @@
# Copyright 2013 VMware Inc.
# All Rights Reserved
#
# 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.
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListQoSQueue(neutronV20.ListCommand):
"""List queues that belong to a given tenant."""
resource = 'qos_queue'
list_columns = ['id', 'name', 'min', 'max',
'qos_marking', 'dscp', 'default']
class ShowQoSQueue(neutronV20.ShowCommand):
"""Show information of a given queue."""
resource = 'qos_queue'
allow_names = True
class CreateQoSQueue(neutronV20.CreateCommand):
"""Create a queue."""
resource = 'qos_queue'
def add_known_arguments(self, parser):
parser.add_argument(
'name', metavar='NAME',
help=_('Name of queue'))
parser.add_argument(
'--min',
help=_('min-rate')),
parser.add_argument(
'--max',
help=_('max-rate')),
parser.add_argument(
'--qos-marking',
help=_('QOS marking untrusted/trusted')),
parser.add_argument(
'--default',
default=False,
help=_('If true all ports created with be the size of this queue'
' if queue is not specified')),
parser.add_argument(
'--dscp',
help=_('Differentiated Services Code Point')),
def args2body(self, parsed_args):
params = {'name': parsed_args.name,
'default': parsed_args.default}
if parsed_args.min:
params['min'] = parsed_args.min
if parsed_args.max:
params['max'] = parsed_args.max
if parsed_args.qos_marking:
params['qos_marking'] = parsed_args.qos_marking
if parsed_args.dscp:
params['dscp'] = parsed_args.dscp
if parsed_args.tenant_id:
params['tenant_id'] = parsed_args.tenant_id
return {'qos_queue': params}
class DeleteQoSQueue(neutronV20.DeleteCommand):
"""Delete a given queue."""
resource = 'qos_queue'
allow_names = True

View File

@ -1,74 +0,0 @@
# 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.
#
#@author Abhishek Raut, Cisco Systems
#@author Sergey Sudakovich, Cisco Systems
from __future__ import print_function
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.neutron.v2_0 import parse_args_to_dict
from neutronclient.openstack.common.gettextutils import _
RESOURCE = 'policy_profile'
class ListPolicyProfile(neutronV20.ListCommand):
"""List policy profiles that belong to a given tenant."""
resource = RESOURCE
_formatters = {}
list_columns = ['id', 'name']
class ShowPolicyProfile(neutronV20.ShowCommand):
"""Show information of a given policy profile."""
resource = RESOURCE
allow_names = True
class UpdatePolicyProfile(neutronV20.UpdateCommand):
"""Update policy profile's information."""
resource = RESOURCE
class UpdatePolicyProfileV2(neutronV20.UpdateCommand):
"""Update policy profile's information."""
api = 'network'
resource = RESOURCE
def get_parser(self, prog_name):
parser = super(UpdatePolicyProfileV2, self).get_parser(prog_name)
parser.add_argument("--add-tenant",
help=_("Add tenant to the policy profile"))
parser.add_argument("--remove-tenant",
help=_("Remove tenant from the policy profile"))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
data = {self.resource: parse_args_to_dict(parsed_args)}
if parsed_args.add_tenant:
data[self.resource]['add_tenant'] = parsed_args.add_tenant
if parsed_args.remove_tenant:
data[self.resource]['remove_tenant'] = parsed_args.remove_tenant
neutron_client.update_policy_profile(parsed_args.id,
{self.resource: data})
print((_('Updated %(resource)s: %(id)s') %
{'id': parsed_args.id, 'resource': self.resource}),
file=self.app.stdout)
return

View File

@ -1,238 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
import argparse
from neutronclient.common import exceptions
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
def _format_fixed_ips(port):
try:
return '\n'.join([utils.dumps(ip) for ip in port['fixed_ips']])
except Exception:
return ''
class ListPort(neutronV20.ListCommand):
"""List ports that belong to a given tenant."""
resource = 'port'
_formatters = {'fixed_ips': _format_fixed_ips, }
list_columns = ['id', 'name', 'mac_address', 'fixed_ips']
pagination_support = True
sorting_support = True
class ListRouterPort(neutronV20.ListCommand):
"""List ports that belong to a given tenant, with specified router."""
resource = 'port'
_formatters = {'fixed_ips': _format_fixed_ips, }
list_columns = ['id', 'name', 'mac_address', 'fixed_ips']
pagination_support = True
sorting_support = True
def get_parser(self, prog_name):
parser = super(ListRouterPort, self).get_parser(prog_name)
parser.add_argument(
'id', metavar='router',
help=_('ID or name of router to look up'))
return parser
def get_data(self, parsed_args):
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'router', parsed_args.id)
self.values_specs.append('--device_id=%s' % _id)
return super(ListRouterPort, self).get_data(parsed_args)
class ShowPort(neutronV20.ShowCommand):
"""Show information of a given port."""
resource = 'port'
class UpdatePortSecGroupMixin(object):
def add_arguments_secgroup(self, parser):
group_sg = parser.add_mutually_exclusive_group()
group_sg.add_argument(
'--security-group', metavar='SECURITY_GROUP',
default=[], action='append', dest='security_groups',
help=_('Security group associated with the port. You can '
'repeat this option.'))
group_sg.add_argument(
'--no-security-groups',
action='store_true',
help=_('Associate no security groups with the port'))
def _resolv_sgid(self, secgroup):
return neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'security_group', secgroup)
def args2body_secgroup(self, parsed_args, port):
if parsed_args.security_groups:
port['security_groups'] = [self._resolv_sgid(sg) for sg
in parsed_args.security_groups]
elif parsed_args.no_security_groups:
port['security_groups'] = []
class UpdateExtraDhcpOptMixin(object):
def add_arguments_extradhcpopt(self, parser):
group_sg = parser.add_mutually_exclusive_group()
group_sg.add_argument(
'--extra-dhcp-opt',
default=[],
action='append',
dest='extra_dhcp_opts',
help=_('Extra dhcp options to be assigned to this port: '
'opt_name=<dhcp_option_name>,opt_value=<value>. You can '
'repeat this option.'))
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>. "
"You can repeat this option.")
for opt in parsed_args.extra_dhcp_opts:
if opt.split('=')[0] in ['opt_value', 'opt_name']:
opt_ele.update(utils.str2dict(opt))
if (('opt_name' in opt_ele) and
('opt_value' in opt_ele)):
if opt_ele['opt_value'] == 'null':
opt_ele['opt_value'] = None
ops.append(opt_ele)
opt_ele = {}
else:
raise exceptions.CommandError(edo_err_msg)
else:
raise exceptions.CommandError(edo_err_msg)
if ops:
port.update({'extra_dhcp_opts': ops})
class CreatePort(neutronV20.CreateCommand, UpdatePortSecGroupMixin,
UpdateExtraDhcpOptMixin):
"""Create a port for a given tenant."""
resource = 'port'
def add_known_arguments(self, parser):
parser.add_argument(
'--name',
help=_('Name of this port'))
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(
'--mac-address',
help=_('MAC address of this port'))
parser.add_argument(
'--mac_address',
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(
'--fixed-ip', metavar='subnet_id=SUBNET,ip_address=IP_ADDR',
action='append',
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)
self.add_arguments_secgroup(parser)
self.add_arguments_extradhcpopt(parser)
parser.add_argument(
'network_id', metavar='NETWORK',
help=_('Network id or name this port belongs to'))
def args2body(self, parsed_args):
_network_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'network', parsed_args.network_id)
body = {'port': {'admin_state_up': parsed_args.admin_state,
'network_id': _network_id, }, }
if parsed_args.mac_address:
body['port'].update({'mac_address': parsed_args.mac_address})
if parsed_args.device_id:
body['port'].update({'device_id': parsed_args.device_id})
if parsed_args.tenant_id:
body['port'].update({'tenant_id': parsed_args.tenant_id})
if parsed_args.name:
body['port'].update({'name': parsed_args.name})
ips = []
if parsed_args.fixed_ip:
for ip_spec in parsed_args.fixed_ip:
ip_dict = utils.str2dict(ip_spec)
if 'subnet_id' in ip_dict:
subnet_name_id = ip_dict['subnet_id']
_subnet_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'subnet', subnet_name_id)
ip_dict['subnet_id'] = _subnet_id
ips.append(ip_dict)
if ips:
body['port'].update({'fixed_ips': ips})
self.args2body_secgroup(parsed_args, body['port'])
self.args2body_extradhcpopt(parsed_args, body['port'])
return body
class DeletePort(neutronV20.DeleteCommand):
"""Delete a given port."""
resource = 'port'
class UpdatePort(neutronV20.UpdateCommand, UpdatePortSecGroupMixin,
UpdateExtraDhcpOptMixin):
"""Update port's information."""
resource = 'port'
def add_known_arguments(self, parser):
self.add_arguments_secgroup(parser)
self.add_arguments_extradhcpopt(parser)
def args2body(self, parsed_args):
body = {'port': {}}
self.args2body_secgroup(parsed_args, body['port'])
self.args2body_extradhcpopt(parsed_args, body['port'])
return body

View File

@ -1,243 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from __future__ import print_function
import argparse
from cliff import lister
from cliff import show
from neutronclient.common import exceptions
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
def get_tenant_id(tenant_id, client):
return (tenant_id if tenant_id else
client.get_quotas_tenant()['tenant']['tenant_id'])
class DeleteQuota(neutronV20.NeutronCommand):
"""Delete defined quotas of a given tenant."""
api = 'network'
resource = 'quota'
def get_parser(self, prog_name):
parser = super(DeleteQuota, self).get_parser(prog_name)
parser.add_argument(
'--tenant-id', metavar='tenant-id',
help=_('The owner tenant ID'))
parser.add_argument(
'--tenant_id',
help=argparse.SUPPRESS)
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
tenant_id = get_tenant_id(parsed_args.tenant_id,
neutron_client)
obj_deleter = getattr(neutron_client,
"delete_%s" % self.resource)
obj_deleter(tenant_id)
print((_('Deleted %(resource)s: %(tenant_id)s')
% {'tenant_id': tenant_id,
'resource': self.resource}),
file=self.app.stdout)
return
class ListQuota(neutronV20.NeutronCommand, lister.Lister):
"""List quotas of all tenants who have non-default quota values."""
api = 'network'
resource = 'quota'
def get_parser(self, prog_name):
parser = super(ListQuota, self).get_parser(prog_name)
return parser
def get_data(self, parsed_args):
self.log.debug('get_data(%s)', parsed_args)
neutron_client = self.get_client()
search_opts = {}
self.log.debug('search options: %s', search_opts)
neutron_client.format = parsed_args.request_format
obj_lister = getattr(neutron_client,
"list_%ss" % self.resource)
data = obj_lister(**search_opts)
info = []
collection = self.resource + "s"
if collection in data:
info = data[collection]
_columns = len(info) > 0 and sorted(info[0].keys()) or []
return (_columns, (utils.get_item_properties(s, _columns)
for s in info))
class ShowQuota(neutronV20.NeutronCommand, show.ShowOne):
"""Show quotas of a given tenant
"""
api = 'network'
resource = "quota"
def get_parser(self, prog_name):
parser = super(ShowQuota, self).get_parser(prog_name)
parser.add_argument(
'--tenant-id', metavar='tenant-id',
help=_('The owner tenant ID'))
parser.add_argument(
'--tenant_id',
help=argparse.SUPPRESS)
return parser
def get_data(self, parsed_args):
self.log.debug('get_data(%s)', parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
tenant_id = get_tenant_id(parsed_args.tenant_id,
neutron_client)
params = {}
obj_shower = getattr(neutron_client,
"show_%s" % self.resource)
data = obj_shower(tenant_id, **params)
if self.resource in data:
for k, v in data[self.resource].iteritems():
if isinstance(v, list):
value = ""
for _item in v:
if value:
value += "\n"
if isinstance(_item, dict):
value += utils.dumps(_item)
else:
value += str(_item)
data[self.resource][k] = value
elif v is None:
data[self.resource][k] = ''
return zip(*sorted(data[self.resource].iteritems()))
else:
return None
class UpdateQuota(neutronV20.NeutronCommand, show.ShowOne):
"""Define tenant's quotas not to use defaults."""
resource = 'quota'
def get_parser(self, prog_name):
parser = super(UpdateQuota, self).get_parser(prog_name)
parser.add_argument(
'--tenant-id', metavar='tenant-id',
help=_('The owner tenant ID'))
parser.add_argument(
'--tenant_id',
help=argparse.SUPPRESS)
parser.add_argument(
'--network', metavar='networks',
help=_('The limit of networks'))
parser.add_argument(
'--subnet', metavar='subnets',
help=_('The limit of subnets'))
parser.add_argument(
'--port', metavar='ports',
help=_('The limit of ports'))
parser.add_argument(
'--router', metavar='routers',
help=_('The limit of routers'))
parser.add_argument(
'--floatingip', metavar='floatingips',
help=_('The limit of floating IPs'))
parser.add_argument(
'--security-group', metavar='security_groups',
help=_('The limit of security groups'))
parser.add_argument(
'--security-group-rule', metavar='security_group_rules',
help=_('The limit of security groups rules'))
parser.add_argument(
'--vip', metavar='vips',
help=_('the limit of vips'))
parser.add_argument(
'--pool', metavar='pools',
help=_('the limit of pools'))
parser.add_argument(
'--member', metavar='members',
help=_('the limit of pool members'))
parser.add_argument(
'--health-monitor', metavar='health_monitors',
help=_('the limit of health monitors'))
return parser
def _validate_int(self, name, value):
try:
return_value = int(value)
except Exception:
message = (_('Quota limit for %(name)s must be an integer') %
{'name': name})
raise exceptions.NeutronClientException(message=message)
return return_value
def args2body(self, parsed_args):
quota = {}
for resource in ('network', 'subnet', 'port', 'router', 'floatingip',
'security_group', 'security_group_rule',
'vip', 'pool', 'member', 'health_monitor'):
if getattr(parsed_args, resource):
quota[resource] = self._validate_int(
resource,
getattr(parsed_args, resource))
return {self.resource: quota}
def get_data(self, parsed_args):
self.log.debug('run(%s)', parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_extra_values = neutronV20.parse_args_to_dict(self.values_specs)
neutronV20._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
obj_updator = getattr(neutron_client,
"update_%s" % self.resource)
tenant_id = get_tenant_id(parsed_args.tenant_id,
neutron_client)
data = obj_updator(tenant_id, body)
if self.resource in data:
for k, v in data[self.resource].iteritems():
if isinstance(v, list):
value = ""
for _item in v:
if value:
value += "\n"
if isinstance(_item, dict):
value += utils.dumps(_item)
else:
value += str(_item)
data[self.resource][k] = value
elif v is None:
data[self.resource][k] = ''
return zip(*sorted(data[self.resource].iteritems()))
else:
return None

View File

@ -1,222 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from __future__ import print_function
import argparse
from neutronclient.common import exceptions
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
def _format_external_gateway_info(router):
try:
return utils.dumps(router['external_gateway_info'])
except Exception:
return ''
class ListRouter(neutronV20.ListCommand):
"""List routers that belong to a given tenant."""
resource = 'router'
_formatters = {'external_gateway_info': _format_external_gateway_info, }
list_columns = ['id', 'name', 'external_gateway_info']
pagination_support = True
sorting_support = True
class ShowRouter(neutronV20.ShowCommand):
"""Show information of a given router."""
resource = 'router'
class CreateRouter(neutronV20.CreateCommand):
"""Create a router for a given tenant."""
resource = 'router'
_formatters = {'external_gateway_info': _format_external_gateway_info, }
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 router to create'))
parser.add_argument(
'distributed', action='store_true',
help=_('Create a distributed router (VMware NSX plugin only)'))
def args2body(self, parsed_args):
body = {'router': {
'name': parsed_args.name,
'admin_state_up': parsed_args.admin_state, }, }
if parsed_args.tenant_id:
body['router'].update({'tenant_id': parsed_args.tenant_id})
return body
class DeleteRouter(neutronV20.DeleteCommand):
"""Delete a given router."""
resource = 'router'
class UpdateRouter(neutronV20.UpdateCommand):
"""Update router's information."""
resource = 'router'
class RouterInterfaceCommand(neutronV20.NeutronCommand):
"""Based class to Add/Remove router interface."""
api = 'network'
resource = 'router'
def call_api(self, neutron_client, router_id, body):
raise NotImplementedError()
def success_message(self, router_id, portinfo):
raise NotImplementedError()
def get_parser(self, prog_name):
parser = super(RouterInterfaceCommand, self).get_parser(prog_name)
parser.add_argument(
'router_id', metavar='router-id',
help=_('ID of the router'))
parser.add_argument(
'interface', metavar='INTERFACE',
help=_('The format is "SUBNET|subnet=SUBNET|port=PORT". '
'Either a subnet or port must be specified. '
'Both ID and name are accepted as SUBNET or PORT. '
'Note that "subnet=" can be omitted when specifying subnet.'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
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_id)
_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_id, portinfo),
file=self.app.stdout)
class AddInterfaceRouter(RouterInterfaceCommand):
"""Add an internal network interface to a router."""
def call_api(self, neutron_client, router_id, body):
return neutron_client.add_interface_router(router_id, body)
def success_message(self, router_id, portinfo):
return (_('Added interface %(port)s to router %(router)s.') %
{'router': router_id, 'port': portinfo['port_id']})
class RemoveInterfaceRouter(RouterInterfaceCommand):
"""Remove an internal network interface from a router."""
def call_api(self, neutron_client, router_id, body):
return neutron_client.remove_interface_router(router_id, body)
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
class SetGatewayRouter(neutronV20.NeutronCommand):
"""Set the external network gateway for a router."""
api = 'network'
resource = 'router'
def get_parser(self, prog_name):
parser = super(SetGatewayRouter, self).get_parser(prog_name)
parser.add_argument(
'router_id', metavar='router-id',
help=_('ID of the router'))
parser.add_argument(
'external_network_id', metavar='external-network-id',
help=_('ID of the external network for the gateway'))
parser.add_argument(
'--disable-snat', action='store_true',
help=_('Disable Source NAT on the router gateway'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_router_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, self.resource, parsed_args.router_id)
_ext_net_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, 'network', parsed_args.external_network_id)
router_dict = {'network_id': _ext_net_id}
if parsed_args.disable_snat:
router_dict['enable_snat'] = False
neutron_client.add_gateway_router(_router_id, router_dict)
print(_('Set gateway for router %s') % parsed_args.router_id,
file=self.app.stdout)
class RemoveGatewayRouter(neutronV20.NeutronCommand):
"""Remove an external network gateway from a router."""
api = 'network'
resource = 'router'
def get_parser(self, prog_name):
parser = super(RemoveGatewayRouter, self).get_parser(prog_name)
parser.add_argument(
'router_id', metavar='router-id',
help=_('ID of the router'))
return parser
def run(self, parsed_args):
self.log.debug('run(%s)' % parsed_args)
neutron_client = self.get_client()
neutron_client.format = parsed_args.request_format
_router_id = neutronV20.find_resourceid_by_name_or_id(
neutron_client, self.resource, parsed_args.router_id)
neutron_client.remove_gateway_router(_router_id)
print(_('Removed gateway from router %s') % parsed_args.router_id,
file=self.app.stdout)

View File

@ -1,249 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
import argparse
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
class ListSecurityGroup(neutronV20.ListCommand):
"""List security groups that belong to a given tenant."""
resource = 'security_group'
list_columns = ['id', 'name', 'description']
pagination_support = True
sorting_support = True
class ShowSecurityGroup(neutronV20.ShowCommand):
"""Show information of a given security group."""
resource = 'security_group'
allow_names = True
class CreateSecurityGroup(neutronV20.CreateCommand):
"""Create a security group."""
resource = 'security_group'
def add_known_arguments(self, parser):
parser.add_argument(
'name', metavar='NAME',
help=_('Name of security group'))
parser.add_argument(
'--description',
help=_('Description of security group'))
def args2body(self, parsed_args):
body = {'security_group': {
'name': parsed_args.name}}
if parsed_args.description:
body['security_group'].update(
{'description': parsed_args.description})
if parsed_args.tenant_id:
body['security_group'].update({'tenant_id': parsed_args.tenant_id})
return body
class DeleteSecurityGroup(neutronV20.DeleteCommand):
"""Delete a given security group."""
resource = 'security_group'
allow_names = True
class UpdateSecurityGroup(neutronV20.UpdateCommand):
"""Update a given security group."""
resource = 'security_group'
def add_known_arguments(self, parser):
parser.add_argument(
'--name',
help=_('Name of security group'))
parser.add_argument(
'--description',
help=_('Description of security group'))
def args2body(self, parsed_args):
body = {'security_group': {}}
if parsed_args.name:
body['security_group'].update(
{'name': parsed_args.name})
if parsed_args.description:
body['security_group'].update(
{'description': parsed_args.description})
return body
class ListSecurityGroupRule(neutronV20.ListCommand):
"""List security group rules that belong to a given tenant."""
resource = 'security_group_rule'
list_columns = ['id', 'security_group_id', 'direction', 'protocol',
'remote_ip_prefix', 'remote_group_id']
replace_rules = {'security_group_id': 'security_group',
'remote_group_id': 'remote_group'}
pagination_support = True
sorting_support = True
def get_parser(self, prog_name):
parser = super(ListSecurityGroupRule, self).get_parser(prog_name)
parser.add_argument(
'--no-nameconv', action='store_true',
help=_('Do not convert security group ID to its name'))
return parser
@staticmethod
def replace_columns(cols, rules, reverse=False):
if reverse:
rules = dict((rules[k], k) for k in rules.keys())
return [rules.get(col, col) for col in cols]
def retrieve_list(self, parsed_args):
parsed_args.fields = self.replace_columns(parsed_args.fields,
self.replace_rules,
reverse=True)
return super(ListSecurityGroupRule, self).retrieve_list(parsed_args)
def extend_list(self, data, parsed_args):
if parsed_args.no_nameconv:
return
neutron_client = self.get_client()
search_opts = {'fields': ['id', 'name']}
if self.pagination_support:
page_size = parsed_args.page_size
if page_size:
search_opts.update({'limit': page_size})
sec_group_ids = set()
for rule in data:
for key in self.replace_rules:
sec_group_ids.add(rule[key])
search_opts.update({"id": sec_group_ids})
secgroups = neutron_client.list_security_groups(**search_opts)
secgroups = secgroups.get('security_groups', [])
sg_dict = dict([(sg['id'], sg['name'])
for sg in secgroups if sg['name']])
for rule in data:
for key in self.replace_rules:
rule[key] = sg_dict.get(rule[key], rule[key])
def setup_columns(self, info, parsed_args):
parsed_args.columns = self.replace_columns(parsed_args.columns,
self.replace_rules,
reverse=True)
# NOTE(amotoki): 2nd element of the tuple returned by setup_columns()
# is a generator, so if you need to create a look using the generator
# object, you need to recreate a generator to show a list expectedly.
info = super(ListSecurityGroupRule, self).setup_columns(info,
parsed_args)
cols = info[0]
if not parsed_args.no_nameconv:
cols = self.replace_columns(info[0], self.replace_rules)
parsed_args.columns = cols
return (cols, info[1])
class ShowSecurityGroupRule(neutronV20.ShowCommand):
"""Show information of a given security group rule."""
resource = 'security_group_rule'
allow_names = False
class CreateSecurityGroupRule(neutronV20.CreateCommand):
"""Create a security group rule."""
resource = 'security_group_rule'
def add_known_arguments(self, parser):
parser.add_argument(
'security_group_id', metavar='SECURITY_GROUP',
help=_('Security group name or id to add rule.'))
parser.add_argument(
'--direction',
default='ingress', choices=['ingress', 'egress'],
help=_('Direction of traffic: ingress/egress'))
parser.add_argument(
'--ethertype',
default='IPv4',
help=_('IPv4/IPv6'))
parser.add_argument(
'--protocol',
help=_('Protocol of packet'))
parser.add_argument(
'--port-range-min',
help=_('Starting port range'))
parser.add_argument(
'--port_range_min',
help=argparse.SUPPRESS)
parser.add_argument(
'--port-range-max',
help=_('Ending port range'))
parser.add_argument(
'--port_range_max',
help=argparse.SUPPRESS)
parser.add_argument(
'--remote-ip-prefix',
help=_('CIDR to match on'))
parser.add_argument(
'--remote_ip_prefix',
help=argparse.SUPPRESS)
parser.add_argument(
'--remote-group-id', metavar='REMOTE_GROUP',
help=_('Remote security group name or id to apply rule'))
parser.add_argument(
'--remote_group_id',
help=argparse.SUPPRESS)
def args2body(self, parsed_args):
_security_group_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'security_group', parsed_args.security_group_id)
body = {'security_group_rule': {
'security_group_id': _security_group_id,
'direction': parsed_args.direction,
'ethertype': parsed_args.ethertype}}
if parsed_args.protocol:
body['security_group_rule'].update(
{'protocol': parsed_args.protocol})
if parsed_args.port_range_min:
body['security_group_rule'].update(
{'port_range_min': parsed_args.port_range_min})
if parsed_args.port_range_max:
body['security_group_rule'].update(
{'port_range_max': parsed_args.port_range_max})
if parsed_args.remote_ip_prefix:
body['security_group_rule'].update(
{'remote_ip_prefix': parsed_args.remote_ip_prefix})
if parsed_args.remote_group_id:
_remote_group_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'security_group',
parsed_args.remote_group_id)
body['security_group_rule'].update(
{'remote_group_id': _remote_group_id})
if parsed_args.tenant_id:
body['security_group_rule'].update(
{'tenant_id': parsed_args.tenant_id})
return body
class DeleteSecurityGroupRule(neutronV20.DeleteCommand):
"""Delete a given security group rule."""
resource = 'security_group_rule'
allow_names = False

View File

@ -1,27 +0,0 @@
# Copyright 2013 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
from neutronclient.neutron import v2_0 as neutronV20
class ListServiceProvider(neutronV20.ListCommand):
"""List service providers."""
resource = 'service_provider'
list_columns = ['service_type', 'name', 'default']
_formatters = {}
pagination_support = True
sorting_support = True

View File

@ -1,188 +0,0 @@
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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.
#
import argparse
from neutronclient.common import exceptions
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronV20
from neutronclient.openstack.common.gettextutils import _
def _format_allocation_pools(subnet):
try:
return '\n'.join([utils.dumps(pool) for pool in
subnet['allocation_pools']])
except Exception:
return ''
def _format_dns_nameservers(subnet):
try:
return '\n'.join([utils.dumps(server) for server in
subnet['dns_nameservers']])
except Exception:
return ''
def _format_host_routes(subnet):
try:
return '\n'.join([utils.dumps(route) for route in
subnet['host_routes']])
except Exception:
return ''
def add_updatable_arguments(parser):
parser.add_argument(
'--name',
help=_('Name of this subnet'))
parser.add_argument(
'--gateway', metavar='GATEWAY_IP',
help=_('Gateway ip of this subnet'))
parser.add_argument(
'--no-gateway',
action='store_true',
help=_('No distribution of gateway'))
parser.add_argument(
'--allocation-pool', metavar='start=IP_ADDR,end=IP_ADDR',
action='append', dest='allocation_pools', type=utils.str2dict,
help=_('Allocation pool IP addresses for this subnet '
'(This option can be repeated)'))
parser.add_argument(
'--allocation_pool',
action='append', dest='allocation_pools', type=utils.str2dict,
help=argparse.SUPPRESS)
parser.add_argument(
'--host-route', metavar='destination=CIDR,nexthop=IP_ADDR',
action='append', dest='host_routes', type=utils.str2dict,
help=_('Additional route (This option can be repeated)'))
parser.add_argument(
'--dns-nameserver', metavar='DNS_NAMESERVER',
action='append', dest='dns_nameservers',
help=_('DNS name server for this subnet '
'(This option can be repeated)'))
parser.add_argument(
'--disable-dhcp',
action='store_true',
help=_('Disable DHCP for this subnet'))
parser.add_argument(
'--enable-dhcp',
action='store_true',
help=_('Enable DHCP for this subnet'))
def updatable_args2body(parsed_args, body):
if parsed_args.gateway and parsed_args.no_gateway:
raise exceptions.CommandError(_("--gateway option and "
"--no-gateway option can "
"not be used same time"))
if parsed_args.disable_dhcp and parsed_args.enable_dhcp:
raise exceptions.CommandError(_("--enable-dhcp and --disable-dhcp can "
"not be used in the same command."))
if parsed_args.no_gateway:
body['subnet'].update({'gateway_ip': None})
if parsed_args.gateway:
body['subnet'].update({'gateway_ip': parsed_args.gateway})
if parsed_args.name:
body['subnet'].update({'name': parsed_args.name})
if parsed_args.disable_dhcp:
body['subnet'].update({'enable_dhcp': False})
if parsed_args.enable_dhcp:
body['subnet'].update({'enable_dhcp': True})
if parsed_args.allocation_pools:
body['subnet']['allocation_pools'] = parsed_args.allocation_pools
if parsed_args.host_routes:
body['subnet']['host_routes'] = parsed_args.host_routes
if parsed_args.dns_nameservers:
body['subnet']['dns_nameservers'] = parsed_args.dns_nameservers
class ListSubnet(neutronV20.ListCommand):
"""List subnets that belong to a given tenant."""
resource = 'subnet'
_formatters = {'allocation_pools': _format_allocation_pools,
'dns_nameservers': _format_dns_nameservers,
'host_routes': _format_host_routes, }
list_columns = ['id', 'name', 'cidr', 'allocation_pools']
pagination_support = True
sorting_support = True
class ShowSubnet(neutronV20.ShowCommand):
"""Show information of a given subnet."""
resource = 'subnet'
class CreateSubnet(neutronV20.CreateCommand):
"""Create a subnet for a given tenant."""
resource = 'subnet'
def add_known_arguments(self, parser):
add_updatable_arguments(parser)
parser.add_argument(
'--ip-version',
type=int,
default=4, choices=[4, 6],
help=_('IP version with default 4'))
parser.add_argument(
'--ip_version',
type=int,
choices=[4, 6],
help=argparse.SUPPRESS)
parser.add_argument(
'network_id', metavar='NETWORK',
help=_('Network id or name this subnet belongs to'))
parser.add_argument(
'cidr', metavar='CIDR',
help=_('CIDR of subnet to create'))
def args2body(self, parsed_args):
_network_id = neutronV20.find_resourceid_by_name_or_id(
self.get_client(), 'network', parsed_args.network_id)
body = {'subnet': {'cidr': parsed_args.cidr,
'network_id': _network_id,
'ip_version': parsed_args.ip_version, }, }
updatable_args2body(parsed_args, body)
if parsed_args.tenant_id:
body['subnet'].update({'tenant_id': parsed_args.tenant_id})
return body
class DeleteSubnet(neutronV20.DeleteCommand):
"""Delete a given subnet."""
resource = 'subnet'
class UpdateSubnet(neutronV20.UpdateCommand):
"""Update subnet's information."""
resource = 'subnet'
def add_known_arguments(self, parser):
add_updatable_arguments(parser)
def args2body(self, parsed_args):
body = {'subnet': {}}
updatable_args2body(parsed_args, body)
return body

View File

@ -1,130 +0,0 @@
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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.
#
# @author: Swaminathan Vasudevan, Hewlett-Packard.
#
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.neutron.v2_0.vpn import utils as vpn_utils
from neutronclient.openstack.common.gettextutils import _
class ListIKEPolicy(neutronv20.ListCommand):
"""List IKEPolicies that belong to a tenant."""
resource = 'ikepolicy'
list_columns = ['id', 'name', 'auth_algorithm',
'encryption_algorithm', 'ike_version', 'pfs']
_formatters = {}
pagination_support = True
sorting_support = True
class ShowIKEPolicy(neutronv20.ShowCommand):
"""Show information of a given IKEPolicy."""
resource = 'ikepolicy'
class CreateIKEPolicy(neutronv20.CreateCommand):
"""Create an IKEPolicy."""
resource = 'ikepolicy'
def add_known_arguments(self, parser):
parser.add_argument(
'--description',
help=_('Description of the IKE policy'))
parser.add_argument(
'--auth-algorithm',
default='sha1', choices=['sha1'],
help=_('Authentication algorithm in lowercase. '
'default:sha1'))
parser.add_argument(
'--encryption-algorithm',
default='aes-128', choices=['3des',
'aes-128',
'aes-192',
'aes-256'],
help=_('Encryption Algorithm in lowercase, default:aes-128'))
parser.add_argument(
'--phase1-negotiation-mode',
default='main', choices=['main'],
help=_('IKE Phase1 negotiation mode in lowercase, default:main'))
parser.add_argument(
'--ike-version',
default='v1', choices=['v1', 'v2'],
help=_('IKE version in lowercase, default:v1'))
parser.add_argument(
'--pfs',
default='group5', choices=['group2', 'group5', 'group14'],
help=_('Perfect Forward Secrecy in lowercase, default:group5'))
parser.add_argument(
'--lifetime',
metavar="units=UNITS,value=VALUE",
type=utils.str2dict,
help=vpn_utils.lifetime_help("IKE"))
parser.add_argument(
'name', metavar='NAME',
help=_('Name of the IKE Policy'))
def args2body(self, parsed_args):
body = {'ikepolicy': {
'auth_algorithm': parsed_args.auth_algorithm,
'encryption_algorithm': parsed_args.encryption_algorithm,
'phase1_negotiation_mode': parsed_args.phase1_negotiation_mode,
'ike_version': parsed_args.ike_version,
'pfs': parsed_args.pfs,
}, }
if parsed_args.name:
body['ikepolicy'].update({'name': parsed_args.name})
if parsed_args.description:
body['ikepolicy'].update({'description': parsed_args.description})
if parsed_args.tenant_id:
body['ikepolicy'].update({'tenant_id': parsed_args.tenant_id})
if parsed_args.lifetime:
vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
body['ikepolicy'].update({'lifetime': parsed_args.lifetime})
return body
class UpdateIKEPolicy(neutronv20.UpdateCommand):
"""Update a given IKE Policy."""
resource = 'ikepolicy'
def add_known_arguments(self, parser):
parser.add_argument(
'--lifetime',
metavar="units=UNITS,value=VALUE",
type=utils.str2dict,
help=vpn_utils.lifetime_help("IKE"))
def args2body(self, parsed_args):
body = {'ikepolicy': {
}, }
if parsed_args.lifetime:
vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
body['ikepolicy'].update({'lifetime': parsed_args.lifetime})
return body
class DeleteIKEPolicy(neutronv20.DeleteCommand):
"""Delete a given IKE Policy."""
resource = 'ikepolicy'

View File

@ -1,185 +0,0 @@
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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.
#
# @author: Swaminathan Vasudevan, Hewlett-Packard.
#
from neutronclient.common import exceptions
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.neutron.v2_0.vpn import utils as vpn_utils
from neutronclient.openstack.common.gettextutils import _
def _format_peer_cidrs(ipsec_site_connection):
try:
return '\n'.join([utils.dumps(cidrs) for cidrs in
ipsec_site_connection['peer_cidrs']])
except Exception:
return ''
class ListIPsecSiteConnection(neutronv20.ListCommand):
"""List IPsecSiteConnections that belong to a given tenant."""
resource = 'ipsec_site_connection'
_formatters = {'peer_cidrs': _format_peer_cidrs}
list_columns = [
'id', 'name', 'peer_address', 'peer_cidrs', 'route_mode',
'auth_mode', 'status']
pagination_support = True
sorting_support = True
class ShowIPsecSiteConnection(neutronv20.ShowCommand):
"""Show information of a given IPsecSiteConnection."""
resource = 'ipsec_site_connection'
class CreateIPsecSiteConnection(neutronv20.CreateCommand):
"""Create an IPsecSiteConnection."""
resource = 'ipsec_site_connection'
def add_known_arguments(self, parser):
parser.add_argument(
'--admin-state-down',
default=True, action='store_false',
help=_('Set admin state up to false'))
parser.add_argument(
'--name',
help=_('Set friendly name for the connection'))
parser.add_argument(
'--description',
help=_('Set a description for the connection'))
parser.add_argument(
'--mtu',
default='1500',
help=_('MTU size for the connection, default:1500'))
parser.add_argument(
'--initiator',
default='bi-directional', choices=['bi-directional',
'response-only'],
help=_('Initiator state in lowercase, default:bi-directional'))
parser.add_argument(
'--dpd',
metavar="action=ACTION,interval=INTERVAL,timeout=TIMEOUT",
type=utils.str2dict,
help=vpn_utils.dpd_help("IPsec Connection"))
parser.add_argument(
'--vpnservice-id', metavar='VPNSERVICE',
required=True,
help=_('VPNService instance id associated with this connection'))
parser.add_argument(
'--ikepolicy-id', metavar='IKEPOLICY',
required=True,
help=_('IKEPolicy id associated with this connection'))
parser.add_argument(
'--ipsecpolicy-id', metavar='IPSECPOLICY',
required=True,
help=_('IPsecPolicy id associated with this connection'))
parser.add_argument(
'--peer-address',
required=True,
help=_('Peer gateway public IPv4/IPv6 address or FQDN.'))
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-cidr',
action='append', dest='peer_cidrs',
required=True,
help=_('Remote subnet(s) in CIDR format'))
parser.add_argument(
'--psk',
required=True,
help=_('Pre-Shared Key string'))
def args2body(self, parsed_args):
_vpnservice_id = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'vpnservice',
parsed_args.vpnservice_id)
_ikepolicy_id = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'ikepolicy',
parsed_args.ikepolicy_id)
_ipsecpolicy_id = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'ipsecpolicy',
parsed_args.ipsecpolicy_id)
if int(parsed_args.mtu) < 68:
message = _("Invalid MTU value: MTU must be "
"greater than or equal to 68")
raise exceptions.CommandError(message)
body = {'ipsec_site_connection': {
'vpnservice_id': _vpnservice_id,
'ikepolicy_id': _ikepolicy_id,
'ipsecpolicy_id': _ipsecpolicy_id,
'peer_address': parsed_args.peer_address,
'peer_id': parsed_args.peer_id,
'mtu': parsed_args.mtu,
'initiator': parsed_args.initiator,
'psk': parsed_args.psk,
'admin_state_up': parsed_args.admin_state_down,
}, }
if parsed_args.name:
body['ipsec_site_connection'].update(
{'name': parsed_args.name}
)
if parsed_args.description:
body['ipsec_site_connection'].update(
{'description': parsed_args.description}
)
if parsed_args.tenant_id:
body['ipsec_site_connection'].update(
{'tenant_id': parsed_args.tenant_id}
)
if parsed_args.dpd:
vpn_utils.validate_dpd_dict(parsed_args.dpd)
body['ipsec_site_connection'].update({'dpd': parsed_args.dpd})
if parsed_args.peer_cidrs:
body['ipsec_site_connection'][
'peer_cidrs'] = parsed_args.peer_cidrs
return body
class UpdateIPsecSiteConnection(neutronv20.UpdateCommand):
"""Update a given IPsecSiteConnection."""
resource = 'ipsec_site_connection'
def add_known_arguments(self, parser):
parser.add_argument(
'--dpd',
metavar="action=ACTION,interval=INTERVAL,timeout=TIMEOUT",
type=utils.str2dict,
help=vpn_utils.dpd_help("IPsec Connection"))
def args2body(self, parsed_args):
body = {'ipsec_site_connection': {
}, }
if parsed_args.dpd:
vpn_utils.validate_dpd_dict(parsed_args.dpd)
body['ipsec_site_connection'].update({'dpd': parsed_args.dpd})
return body
class DeleteIPsecSiteConnection(neutronv20.DeleteCommand):
"""Delete a given IPsecSiteConnection."""
resource = 'ipsec_site_connection'

View File

@ -1,130 +0,0 @@
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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.
#
# @author: Swaminathan Vasudevan, Hewlett-Packard.
from neutronclient.common import utils
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.neutron.v2_0.vpn import utils as vpn_utils
from neutronclient.openstack.common.gettextutils import _
class ListIPsecPolicy(neutronv20.ListCommand):
"""List ipsecpolicies that belongs to a given tenant connection."""
resource = 'ipsecpolicy'
list_columns = ['id', 'name', 'auth_algorithm',
'encryption_algorithm', 'pfs']
_formatters = {}
pagination_support = True
sorting_support = True
class ShowIPsecPolicy(neutronv20.ShowCommand):
"""Show information of a given ipsecpolicy."""
resource = 'ipsecpolicy'
class CreateIPsecPolicy(neutronv20.CreateCommand):
"""Create an ipsecpolicy."""
resource = 'ipsecpolicy'
def add_known_arguments(self, parser):
parser.add_argument(
'--description',
help=_('Description of the IPsecPolicy'))
parser.add_argument(
'--transform-protocol',
default='esp', choices=['esp', 'ah', 'ah-esp'],
help=_('Transform Protocol in lowercase, default:esp'))
parser.add_argument(
'--auth-algorithm',
default='sha1', choices=['sha1'],
help=_('Authentication algorithm in lowercase, default:sha1'))
parser.add_argument(
'--encryption-algorithm',
default='aes-128', choices=['3des',
'aes-128',
'aes-192',
'aes-256'],
help=_('Encryption Algorithm in lowercase, default:aes-128'))
parser.add_argument(
'--encapsulation-mode',
default='tunnel', choices=['tunnel', 'transport'],
help=_('Encapsulation Mode in lowercase, default:tunnel'))
parser.add_argument(
'--pfs',
default='group5', choices=['group2', 'group5', 'group14'],
help=_('Perfect Forward Secrecy in lowercase, default:group5'))
parser.add_argument(
'--lifetime',
metavar="units=UNITS,value=VALUE",
type=utils.str2dict,
help=vpn_utils.lifetime_help("IPsec"))
parser.add_argument(
'name', metavar='NAME',
help=_('Name of the IPsecPolicy'))
def args2body(self, parsed_args):
body = {'ipsecpolicy': {
'auth_algorithm': parsed_args.auth_algorithm,
'encryption_algorithm': parsed_args.encryption_algorithm,
'encapsulation_mode': parsed_args.encapsulation_mode,
'transform_protocol': parsed_args.transform_protocol,
'pfs': parsed_args.pfs,
}, }
if parsed_args.name:
body['ipsecpolicy'].update({'name': parsed_args.name})
if parsed_args.description:
body['ipsecpolicy'].update(
{'description': parsed_args.description}
)
if parsed_args.tenant_id:
body['ipsecpolicy'].update({'tenant_id': parsed_args.tenant_id})
if parsed_args.lifetime:
vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
body['ipsecpolicy'].update({'lifetime': parsed_args.lifetime})
return body
class UpdateIPsecPolicy(neutronv20.UpdateCommand):
"""Update a given ipsec policy."""
resource = 'ipsecpolicy'
def add_known_arguments(self, parser):
parser.add_argument(
'--lifetime',
metavar="units=UNITS,value=VALUE",
type=utils.str2dict,
help=vpn_utils.lifetime_help("IPsec"))
def args2body(self, parsed_args):
body = {'ipsecpolicy': {
}, }
if parsed_args.lifetime:
vpn_utils.validate_lifetime_dict(parsed_args.lifetime)
body['ipsecpolicy'].update({'lifetime': parsed_args.lifetime})
return body
class DeleteIPsecPolicy(neutronv20.DeleteCommand):
"""Delete a given ipsecpolicy."""
resource = 'ipsecpolicy'

View File

@ -1,114 +0,0 @@
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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.
#
# @author: Swaminathan Vasudevan, Hewlett-Packard.
#
"""VPN Utilities and helper functions."""
from neutronclient.common import exceptions
from neutronclient.openstack.common.gettextutils import _
dpd_supported_actions = ['hold', 'clear', 'restart',
'restart-by-peer', 'disabled']
dpd_supported_keys = ['action', 'interval', 'timeout']
lifetime_keys = ['units', 'value']
lifetime_units = ['seconds']
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 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
def lifetime_help(policy):
lifetime = _("%s Lifetime Attributes."
"'units'-seconds,default:seconds. "
"'value'-non negative integer, default:3600.") % policy
return lifetime
def dpd_help(policy):
dpd = _(" %s Dead Peer Detection Attributes. "
" 'action'-hold,clear,disabled,restart,restart-by-peer."
" 'interval' and 'timeout' are non negative integers. "
" 'interval' should be less than 'timeout' value. "
" 'action', default:hold 'interval', default:30, "
" 'timeout', default:120.") % policy.capitalize()
return dpd

View File

@ -1,90 +0,0 @@
# (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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.
#
# @author: Swaminathan Vasudevan, Hewlett-Packard.
#
from neutronclient.neutron import v2_0 as neutronv20
from neutronclient.openstack.common.gettextutils import _
class ListVPNService(neutronv20.ListCommand):
"""List VPNService configurations that belong to a given tenant."""
resource = 'vpnservice'
list_columns = [
'id', 'name', 'router_id', 'status'
]
_formatters = {}
pagination_support = True
sorting_support = True
class ShowVPNService(neutronv20.ShowCommand):
"""Show information of a given VPNService."""
resource = 'vpnservice'
class CreateVPNService(neutronv20.CreateCommand):
"""Create a VPNService."""
resource = 'vpnservice'
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(
'--name',
help=_('Set a name for the vpnservice'))
parser.add_argument(
'--description',
help=_('Set a description for the vpnservice'))
parser.add_argument(
'router', metavar='ROUTER',
help=_('Router unique identifier for the vpnservice'))
parser.add_argument(
'subnet', metavar='SUBNET',
help=_('Subnet unique identifier for the vpnservice deployment'))
def args2body(self, parsed_args):
_subnet_id = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'subnet',
parsed_args.subnet)
_router_id = neutronv20.find_resourceid_by_name_or_id(
self.get_client(), 'router',
parsed_args.router)
body = {self.resource: {'subnet_id': _subnet_id,
'router_id': _router_id,
'admin_state_up': parsed_args.admin_state}, }
neutronv20.update_dict(parsed_args, body[self.resource],
['name', 'description',
'tenant_id'])
return body
class UpdateVPNService(neutronv20.UpdateCommand):
"""Update a given VPNService."""
resource = 'vpnservice'
class DeleteVPNService(neutronv20.DeleteCommand):
"""Delete a given VPNService."""
resource = 'vpnservice'

File diff suppressed because it is too large Load Diff