~ajkavanagh/+junk/useful-things

« back to all changes in this revision

Viewing changes to charm-manual-testing/manila/v2_keystone/neutron-ext-net.py

  • Committer: Alex Kavanagh
  • Date: 2016-12-01 17:01:49 UTC
  • Revision ID: alex.kavanagh@canonical.com-20161201170149-ytewr1hw7z2xre8o
Added serverstack.yaml for juju & manila testing scripts

Note that the manila testing scripts are for serverstack ONLY.
There's a different github repo for manual testing of
manila.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
 
 
3
# Stolen from charm-openstack-testing!
 
4
 
 
5
from neutronclient.v2_0 import client
 
6
 
 
7
from keystoneclient.v2_0 import client as ks_client
 
8
from keystoneclient.auth import identity
 
9
from keystoneclient import session
 
10
import optparse
 
11
import os
 
12
import sys
 
13
import logging
 
14
 
 
15
 
 
16
usage = """Usage: %prog [options] ext_net_name
 
17
 
 
18
For example:
 
19
 
 
20
  %prog -g 192.168.21.1 -c 192.168.21.0/25 \\
 
21
      -f 192.168.21.100:192.168.21.200 ext_net
 
22
"""
 
23
 
 
24
if __name__ == '__main__':
 
25
    parser = optparse.OptionParser(usage)
 
26
    parser.add_option('-t', '--tenant',
 
27
                      help='Tenant name to create network for',
 
28
                      dest='tenant', action='store',
 
29
                      default=None)
 
30
    parser.add_option("-d", "--debug",
 
31
                      help="Enable debug logging",
 
32
                      dest="debug", action="store_true", default=False)
 
33
    parser.add_option("-g", "--gateway",
 
34
                      help="Default gateway to use.",
 
35
                      dest="default_gateway", action="store", default=None)
 
36
    parser.add_option("-c", "--cidr",
 
37
                      help="CIDR of external network.",
 
38
                      dest="cidr", action="store", default=None)
 
39
    parser.add_option("-f", "--floating-range",
 
40
                      help="Range of floating IP's to use (separated by :).",
 
41
                      dest="floating_range", action="store", default=None)
 
42
    parser.add_option("--network-type",
 
43
                      help="Network type.",
 
44
                      dest="network_type", action="store", default='gre')
 
45
    (opts, args) = parser.parse_args()
 
46
 
 
47
    if len(args) != 1:
 
48
        parser.print_help()
 
49
        sys.exit(1)
 
50
 
 
51
    if opts.debug:
 
52
        logging.basicConfig(level=logging.DEBUG)
 
53
    else:
 
54
        logging.basicConfig(level=logging.INFO)
 
55
 
 
56
    net_name = args[0]
 
57
    subnet_name = '{}_subnet'.format(net_name)
 
58
 
 
59
    if (opts.floating_range):
 
60
        (start_floating_ip, end_floating_ip) = opts.floating_range.split(':')
 
61
    else:
 
62
        start_floating_ip = None
 
63
        end_floating_ip = None
 
64
 
 
65
    # use session based authentication
 
66
    ep = os.environ['OS_AUTH_URL']
 
67
    if not ep.endswith('v2.0'):
 
68
        ep = "{}/v2.0".format(ep)
 
69
    auth = identity.v2.Password(username=os.environ['OS_USERNAME'],
 
70
                                password=os.environ['OS_PASSWORD'],
 
71
                                tenant_name=os.environ['OS_TENANT_NAME'],
 
72
                                auth_url=ep)
 
73
    sess = session.Session(auth=auth)
 
74
    keystone = ks_client.Client(session=sess)
 
75
    keystone.auth_ref = auth.get_access(sess)
 
76
    # keystone = ks_client.Client(username=os.environ['OS_USERNAME'],
 
77
                                # password=os.environ['OS_PASSWORD'],
 
78
                                # tenant_name=os.environ['OS_TENANT_NAME'],
 
79
                                # auth_url=os.environ['OS_AUTH_URL'],
 
80
                                # region_name=os.environ['OS_REGION_NAME'])
 
81
    # neutron = client.Client(username=os.environ['OS_USERNAME'],
 
82
                            # password=os.environ['OS_PASSWORD'],
 
83
                            # tenant_name=os.environ['OS_TENANT_NAME'],
 
84
                            # auth_url=os.environ['OS_AUTH_URL'],
 
85
                            # region_name=os.environ['OS_REGION_NAME'])
 
86
    neutron_ep = keystone.service_catalog.url_for(
 
87
            service_type='network', endpoint_type='publicURL')
 
88
    neutron = client.Client(session=sess)
 
89
 
 
90
    # Resolve tenant id
 
91
    tenant_id = None
 
92
    for tenant in [t._info for t in keystone.tenants.list()]:
 
93
        if (tenant['name'] == (opts.tenant or os.environ['OS_TENANT_NAME'])):
 
94
            tenant_id = tenant['id']
 
95
            break  # Tenant ID found - stop looking
 
96
    if not tenant_id:
 
97
        logging.error("Unable to locate tenant id for %s.", opts.tenant)
 
98
        sys.exit(1)
 
99
 
 
100
    networks = neutron.list_networks(name=net_name)
 
101
    if len(networks['networks']) == 0:
 
102
        logging.info("Configuring external network '%s'", net_name)
 
103
        network_msg = {
 
104
            'network': {
 
105
                'name': net_name,
 
106
                'router:external': True,
 
107
                'tenant_id': tenant_id,
 
108
                'provider:network_type': opts.network_type,
 
109
            }
 
110
        }
 
111
 
 
112
        if opts.network_type == 'vxlan':
 
113
            network_msg['network']['provider:segmentation_id'] = 1234
 
114
        elif opts.network_type == 'vlan':
 
115
            network_msg['network']['provider:segmentation_id'] = 2
 
116
            network_msg['network']['provider:physical_network'] = 'physnet1'
 
117
        elif opts.network_type == 'flat':
 
118
            network_msg['network']['provider:physical_network'] = 'physnet1'
 
119
        else:
 
120
            network_msg['network']['provider:segmentation_id'] = 2
 
121
 
 
122
        logging.info('Creating new external network definition: %s', net_name)
 
123
        network = neutron.create_network(network_msg)['network']
 
124
        logging.info('New external network created: %s', network['id'])
 
125
    else:
 
126
        logging.warning('Network %s already exists.', net_name)
 
127
        network = networks['networks'][0]
 
128
 
 
129
    subnets = neutron.list_subnets(name=subnet_name)
 
130
    if len(subnets['subnets']) == 0:
 
131
        subnet_msg = {
 
132
            'name': subnet_name,
 
133
            'network_id': network['id'],
 
134
            'enable_dhcp': False,
 
135
            'ip_version': 4,
 
136
            'tenant_id': tenant_id
 
137
        }
 
138
 
 
139
        if opts.default_gateway:
 
140
            subnet_msg['gateway_ip'] = opts.default_gateway
 
141
        if opts.cidr:
 
142
            subnet_msg['cidr'] = opts.cidr
 
143
        if (start_floating_ip and end_floating_ip):
 
144
            subnet_msg['allocation_pools'] = [{
 
145
                'start': start_floating_ip,
 
146
                'end': end_floating_ip
 
147
            }]
 
148
 
 
149
        logging.info('Creating new subnet for %s', net_name)
 
150
        subnet = neutron.create_subnet({'subnet': subnet_msg})['subnet']
 
151
        logging.info('New subnet created: %s', subnet['id'])
 
152
    else:
 
153
        logging.warning('Subnet %s already exists.', subnet_name)
 
154
        subnet = subnets['subnets'][0]
 
155
 
 
156
    routers = neutron.list_routers(name='provider-router')
 
157
    if len(routers['routers']) == 0:
 
158
        logging.info('Creating provider router for external network access')
 
159
        router = neutron.create_router(
 
160
            {'router': {'name': 'provider-router', 'tenant_id': tenant_id}}
 
161
        )['router']
 
162
        logging.info('New router created: %s', (router['id']))
 
163
    else:
 
164
        logging.warning('Router provider-router already exists.')
 
165
        router = routers['routers'][0]
 
166
 
 
167
    ports = neutron.list_ports(device_owner='network:router_gateway',
 
168
                               network_id=network['id'])
 
169
    if len(ports['ports']) == 0:
 
170
        logging.info('Plugging router into ext_net')
 
171
        router = (
 
172
            neutron.add_gateway_router(
 
173
                            router=router['id'],
 
174
                            body={'network_id': network['id']}))
 
175
        logging.info('Router connected to %s', net_name)
 
176
    else:
 
177
        logging.warning('Router already connect to %s', net_name)