"Fossies" - the Fresh Open Source Software Archive

Member "manila-8.1.3/manila/tests/share/drivers/test_service_instance.py" (20 Jul 2020, 112773 Bytes) of package /linux/misc/openstack/manila-8.1.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "test_service_instance.py": 8.1.2_vs_8.1.3.

    1 # Copyright (c) 2014 NetApp, Inc.
    2 # Copyright (c) 2015 Mirantis, Inc.
    3 # All Rights Reserved.
    4 #
    5 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
    6 #    not use this file except in compliance with the License. You may obtain
    7 #    a copy of the License at
    8 #
    9 #         http://www.apache.org/licenses/LICENSE-2.0
   10 #
   11 #    Unless required by applicable law or agreed to in writing, software
   12 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
   13 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
   14 #    License for the specific language governing permissions and limitations
   15 #    under the License.
   16 
   17 """Unit tests for the instance module."""
   18 
   19 import os
   20 import time
   21 
   22 import ddt
   23 import mock
   24 import netaddr
   25 from oslo_config import cfg
   26 from oslo_utils import importutils
   27 import six
   28 
   29 from manila import exception
   30 from manila.share import configuration
   31 from manila.share import driver  # noqa
   32 from manila.share.drivers import service_instance
   33 from manila import test
   34 from manila.tests import fake_compute
   35 from manila.tests import fake_network
   36 from manila.tests import utils as test_utils
   37 
   38 CONF = cfg.CONF
   39 
   40 
   41 def fake_get_config_option(key):
   42     if key == 'driver_handles_share_servers':
   43         return True
   44     elif key == 'service_instance_password':
   45         return None
   46     elif key == 'service_instance_user':
   47         return 'fake_user'
   48     elif key == 'service_network_name':
   49         return 'fake_service_network_name'
   50     elif key == 'service_instance_flavor_id':
   51         return 100
   52     elif key == 'service_instance_name_template':
   53         return 'fake_manila_service_instance_%s'
   54     elif key == 'service_image_name':
   55         return 'fake_service_image_name'
   56     elif key == 'manila_service_keypair_name':
   57         return 'fake_manila_service_keypair_name'
   58     elif key == 'path_to_private_key':
   59         return 'fake_path_to_private_key'
   60     elif key == 'path_to_public_key':
   61         return 'fake_path_to_public_key'
   62     elif key == 'max_time_to_build_instance':
   63         return 500
   64     elif key == 'connect_share_server_to_tenant_network':
   65         return False
   66     elif key == 'service_network_cidr':
   67         return '99.254.0.0/24'
   68     elif key == 'service_network_division_mask':
   69         return 27
   70     elif key == 'service_network_name':
   71         return 'fake_service_network_name'
   72     elif key == 'interface_driver':
   73         return 'i.am.fake.VifDriver'
   74     elif key == 'admin_network_id':
   75         return None
   76     elif key == 'admin_subnet_id':
   77         return None
   78     elif key == 'backend_availability_zone':
   79         return None
   80     else:
   81         return mock.Mock()
   82 
   83 
   84 class FakeServiceInstance(object):
   85 
   86     def __init__(self, driver_config=None):
   87         super(FakeServiceInstance, self).__init__()
   88         self.compute_api = service_instance.compute.API()
   89         self.admin_context = service_instance.context.get_admin_context()
   90         self.driver_config = driver_config
   91 
   92     def get_config_option(self, key):
   93         return fake_get_config_option(key)
   94 
   95 
   96 class FakeNetworkHelper(service_instance.BaseNetworkhelper):
   97 
   98     @property
   99     def NAME(self):
  100         return service_instance.NEUTRON_NAME
  101 
  102     @property
  103     def neutron_api(self):
  104         if not hasattr(self, '_neutron_api'):
  105             self._neutron_api = mock.Mock()
  106         return self._neutron_api
  107 
  108     def __init__(self, service_instance_manager):
  109         self.get_config_option = service_instance_manager.get_config_option
  110 
  111     def get_network_name(self, network_info):
  112         """Return name of network."""
  113         return 'fake_network_name'
  114 
  115     def setup_connectivity_with_service_instances(self):
  116         """Nothing to do in fake network helper."""
  117 
  118     def setup_network(self, network_info):
  119         """Combine fake network data."""
  120         return dict()
  121 
  122     def teardown_network(self, server_details):
  123         """Nothing to do in fake network helper."""
  124 
  125 
  126 @ddt.ddt
  127 class ServiceInstanceManagerTestCase(test.TestCase):
  128     """Test suite for service instance manager."""
  129 
  130     def setUp(self):
  131         super(ServiceInstanceManagerTestCase, self).setUp()
  132         self.instance_id = 'fake_instance_id'
  133         self.config = configuration.Configuration(None)
  134         self.config.safe_get = mock.Mock(side_effect=fake_get_config_option)
  135         self.mock_object(service_instance.compute, 'API', fake_compute.API)
  136         self.mock_object(
  137             service_instance.os.path, 'exists', mock.Mock(return_value=True))
  138         self.mock_object(service_instance, 'NeutronNetworkHelper',
  139                          mock.Mock(side_effect=FakeNetworkHelper))
  140         self._manager = service_instance.ServiceInstanceManager(self.config)
  141         self._manager._execute = mock.Mock(return_value=('', ''))
  142         self.mock_object(time, 'sleep')
  143 
  144     def test_get_config_option_from_driver_config(self):
  145         username1 = 'fake_username_1_%s' % self.id()
  146         username2 = 'fake_username_2_%s' % self.id()
  147         config_data = dict(
  148             DEFAULT=dict(service_instance_user=username1),
  149             CUSTOM=dict(service_instance_user=username2))
  150         with test_utils.create_temp_config_with_opts(config_data):
  151             self.config = configuration.Configuration(
  152                 service_instance.common_opts, config_group='CUSTOM')
  153             self._manager = service_instance.ServiceInstanceManager(
  154                 self.config)
  155         result = self._manager.get_config_option('service_instance_user')
  156         self.assertEqual(username2, result)
  157 
  158     def test_get_config_option_from_common_config(self):
  159         username = 'fake_username_%s' % self.id()
  160         config_data = dict(DEFAULT=dict(service_instance_user=username))
  161         with test_utils.create_temp_config_with_opts(config_data):
  162             self._manager = service_instance.ServiceInstanceManager()
  163         result = self._manager.get_config_option('service_instance_user')
  164         self.assertEqual(username, result)
  165 
  166     def test_get_neutron_network_helper(self):
  167         # Mock it again, because it was called in setUp method.
  168         self.mock_object(service_instance, 'NeutronNetworkHelper')
  169         config_data = dict(DEFAULT=dict(service_instance_user='fake_username',
  170                                         driver_handles_share_servers=True))
  171 
  172         with test_utils.create_temp_config_with_opts(config_data):
  173             self._manager = service_instance.ServiceInstanceManager()
  174             self._manager.network_helper
  175         service_instance.NeutronNetworkHelper.assert_called_once_with(
  176             self._manager)
  177 
  178     def test_init_with_driver_config_and_handling_of_share_servers(self):
  179         self.mock_object(service_instance, 'NeutronNetworkHelper')
  180         config_data = dict(CUSTOM=dict(
  181             driver_handles_share_servers=True,
  182             service_instance_user='fake_user'))
  183         opts = service_instance.common_opts + driver.share_opts
  184         with test_utils.create_temp_config_with_opts(config_data):
  185             self.config = configuration.Configuration(opts, 'CUSTOM')
  186             self._manager = service_instance.ServiceInstanceManager(
  187                 self.config)
  188         self.assertTrue(
  189             self._manager.get_config_option("driver_handles_share_servers"))
  190         self.assertIsNotNone(self._manager.driver_config)
  191         self.assertTrue(hasattr(self._manager, 'network_helper'))
  192         self.assertTrue(service_instance.NeutronNetworkHelper.called)
  193 
  194     def test_init_with_driver_config_and_wo_handling_of_share_servers(self):
  195         self.mock_object(service_instance, 'NeutronNetworkHelper')
  196         config_data = dict(CUSTOM=dict(
  197             driver_handles_share_servers=False,
  198             service_instance_user='fake_user'))
  199         opts = service_instance.common_opts + driver.share_opts
  200         with test_utils.create_temp_config_with_opts(config_data):
  201             self.config = configuration.Configuration(opts, 'CUSTOM')
  202             self._manager = service_instance.ServiceInstanceManager(
  203                 self.config)
  204         self.assertIsNotNone(self._manager.driver_config)
  205         self.assertFalse(hasattr(self._manager, 'network_helper'))
  206         self.assertFalse(service_instance.NeutronNetworkHelper.called)
  207 
  208     def test_init_with_common_config_and_handling_of_share_servers(self):
  209         self.mock_object(service_instance, 'NeutronNetworkHelper')
  210         config_data = dict(DEFAULT=dict(
  211             service_instance_user='fake_username',
  212             driver_handles_share_servers=True))
  213         with test_utils.create_temp_config_with_opts(config_data):
  214             self._manager = service_instance.ServiceInstanceManager()
  215         self.assertTrue(
  216             self._manager.get_config_option("driver_handles_share_servers"))
  217         self.assertIsNone(self._manager.driver_config)
  218         self.assertTrue(hasattr(self._manager, 'network_helper'))
  219         self.assertTrue(service_instance.NeutronNetworkHelper.called)
  220 
  221     def test_init_with_common_config_and_wo_handling_of_share_servers(self):
  222         self.mock_object(service_instance, 'NeutronNetworkHelper')
  223         config_data = dict(DEFAULT=dict(
  224             service_instance_user='fake_username',
  225             driver_handles_share_servers=False))
  226         with test_utils.create_temp_config_with_opts(config_data):
  227             self._manager = service_instance.ServiceInstanceManager()
  228         self.assertEqual(
  229             False,
  230             self._manager.get_config_option("driver_handles_share_servers"))
  231         self.assertIsNone(self._manager.driver_config)
  232         self.assertFalse(hasattr(self._manager, 'network_helper'))
  233         self.assertFalse(service_instance.NeutronNetworkHelper.called)
  234 
  235     def test_no_service_user_defined(self):
  236         group_name = 'GROUP_%s' % self.id()
  237         config_data = {group_name: dict()}
  238         with test_utils.create_temp_config_with_opts(config_data):
  239             config = configuration.Configuration(
  240                 service_instance.common_opts, config_group=group_name)
  241         self.assertRaises(
  242             exception.ServiceInstanceException,
  243             service_instance.ServiceInstanceManager, config)
  244 
  245     def test_get_service_instance_name_using_driver_config(self):
  246         fake_server_id = 'fake_share_server_id_%s' % self.id()
  247         self.mock_object(service_instance, 'NeutronNetworkHelper')
  248         config_data = dict(CUSTOM=dict(
  249             driver_handles_share_servers=True,
  250             service_instance_user='fake_user'))
  251         opts = service_instance.common_opts + driver.share_opts
  252         with test_utils.create_temp_config_with_opts(config_data):
  253             self.config = configuration.Configuration(opts, 'CUSTOM')
  254             self._manager = service_instance.ServiceInstanceManager(
  255                 self.config)
  256         result = self._manager._get_service_instance_name(fake_server_id)
  257         self.assertIsNotNone(self._manager.driver_config)
  258         self.assertEqual(
  259             self._manager.get_config_option(
  260                 "service_instance_name_template") % "%s_%s" % (
  261                     self._manager.driver_config.config_group, fake_server_id),
  262             result)
  263         self.assertTrue(
  264             self._manager.get_config_option("driver_handles_share_servers"))
  265         self.assertTrue(hasattr(self._manager, 'network_helper'))
  266         self.assertTrue(service_instance.NeutronNetworkHelper.called)
  267 
  268     def test_get_service_instance_name_using_default_config(self):
  269         fake_server_id = 'fake_share_server_id_%s' % self.id()
  270         config_data = dict(CUSTOM=dict(
  271             service_instance_user='fake_user'))
  272         with test_utils.create_temp_config_with_opts(config_data):
  273             self._manager = service_instance.ServiceInstanceManager()
  274         result = self._manager._get_service_instance_name(fake_server_id)
  275         self.assertIsNone(self._manager.driver_config)
  276         self.assertEqual(
  277             self._manager.get_config_option(
  278                 "service_instance_name_template") % fake_server_id, result)
  279 
  280     def test__check_server_availability_available_from_start(self):
  281         fake_server = dict(id='fake_server', ip='127.0.0.1')
  282         self.mock_object(service_instance.socket.socket, 'connect')
  283         self.mock_object(service_instance.time, 'sleep')
  284         self.mock_object(service_instance.time, 'time',
  285                          mock.Mock(return_value=0))
  286 
  287         result = self._manager._check_server_availability(fake_server)
  288 
  289         self.assertTrue(result)
  290         service_instance.socket.socket.connect.assert_called_once_with(
  291             (fake_server['ip'], 22))
  292         service_instance.time.time.assert_has_calls([
  293             mock.call(), mock.call()])
  294         service_instance.time.time.assert_has_calls([])
  295 
  296     @ddt.data(True, False)
  297     def test__check_server_availability_with_recall(self, is_ok):
  298         fake_server = dict(id='fake_server', ip='fake_ip_address')
  299 
  300         self.fake_time = 0
  301 
  302         def fake_connect(addr):
  303             if not(is_ok and self.fake_time > 1):
  304                 raise service_instance.socket.error
  305 
  306         def fake_time():
  307             return self.fake_time
  308 
  309         def fake_sleep(time):
  310             self.fake_time += 5
  311 
  312         self.mock_object(service_instance.time, 'sleep',
  313                          mock.Mock(side_effect=fake_sleep))
  314         self.mock_object(service_instance.socket.socket, 'connect',
  315                          mock.Mock(side_effect=fake_connect))
  316         self.mock_object(service_instance.time, 'time',
  317                          mock.Mock(side_effect=fake_time))
  318         self._manager.max_time_to_build_instance = 6
  319 
  320         result = self._manager._check_server_availability(fake_server)
  321 
  322         if is_ok:
  323             self.assertTrue(result)
  324         else:
  325             self.assertFalse(result)
  326         service_instance.socket.socket.connect.assert_has_calls([
  327             mock.call((fake_server['ip'], 22)),
  328             mock.call((fake_server['ip'], 22))])
  329         service_instance.time.time.assert_has_calls([
  330             mock.call(), mock.call(), mock.call()])
  331         service_instance.time.time.assert_has_calls([mock.call()])
  332 
  333     def test_get_server_ip_found_in_networks_section(self):
  334         ip = '10.0.0.1'
  335         net_name = self._manager.get_config_option('service_network_name')
  336         fake_server = dict(networks={net_name: [ip]})
  337         result = self._manager._get_server_ip(fake_server, net_name)
  338         self.assertEqual(ip, result)
  339 
  340     def test_get_server_ip_found_in_addresses_section(self):
  341         ip = '10.0.0.1'
  342         net_name = self._manager.get_config_option('service_network_name')
  343         fake_server = dict(addresses={net_name: [dict(addr=ip, version=4)]})
  344         result = self._manager._get_server_ip(fake_server, net_name)
  345         self.assertEqual(ip, result)
  346 
  347     @ddt.data(
  348         {},
  349         {'networks': {fake_get_config_option('service_network_name'): []}},
  350         {'addresses': {fake_get_config_option('service_network_name'): []}})
  351     def test_get_server_ip_not_found(self, data):
  352         self.assertRaises(
  353             exception.ManilaException,
  354             self._manager._get_server_ip, data,
  355             fake_get_config_option('service_network_name'))
  356 
  357     def test_security_group_name_not_specified(self):
  358         self.mock_object(self._manager, 'get_config_option',
  359                          mock.Mock(return_value=None))
  360         result = self._manager._get_or_create_security_groups(
  361             self._manager.admin_context)
  362         self.assertIsNone(result)
  363         self._manager.get_config_option.assert_called_once_with(
  364             'service_instance_security_group')
  365 
  366     def test_security_group_name_from_config_and_sg_exist(self):
  367         name = "fake_sg_name_from_config"
  368         desc = "fake_sg_description"
  369         fake_secgroup = {'id': 'fake_sg_id', 'name': name, 'description': desc}
  370         self.mock_object(self._manager, 'get_config_option',
  371                          mock.Mock(return_value=name))
  372         neutron_api = self._manager.network_helper.neutron_api
  373         neutron_api.security_group_list.return_value = {
  374             'security_groups': [fake_secgroup]}
  375 
  376         result = self._manager._get_or_create_security_groups(
  377             self._manager.admin_context)
  378 
  379         self.assertEqual([fake_secgroup, ], result)
  380         self._manager.get_config_option.assert_called_once_with(
  381             'service_instance_security_group')
  382         neutron_api.security_group_list.assert_called_once_with({"name": name})
  383 
  384     @ddt.data(None, 'fake_name')
  385     def test_security_group_creation_with_name_from_config(self, name):
  386         config_name = "fake_sg_name_from_config"
  387         desc = "fake_sg_description"
  388         fake_secgroup = {'id': 'fake_sg_id', 'name': name, 'description': desc}
  389         self.mock_object(self._manager, 'get_config_option',
  390                          mock.Mock(return_value=name or config_name))
  391         neutron_api = self._manager.network_helper.neutron_api
  392         neutron_api.security_group_list.return_value = {'security_groups': []}
  393         neutron_api.security_group_create.return_value = {
  394             'security_group': fake_secgroup,
  395         }
  396 
  397         result = self._manager._get_or_create_security_groups(
  398             context=self._manager.admin_context,
  399             name=name,
  400             description=desc,
  401         )
  402 
  403         self.assertEqual([fake_secgroup, ], result)
  404         if not name:
  405             self._manager.get_config_option.assert_called_once_with(
  406                 'service_instance_security_group')
  407         neutron_api.security_group_list.assert_called_once_with(
  408             {"name": name or config_name})
  409         neutron_api.security_group_create.assert_called_once_with(
  410             name or config_name, desc)
  411 
  412     @ddt.data(None, 'fake_name')
  413     def test_security_group_creation_with_name_from_conf_allow_ssh(self, name):
  414         def fake_secgroup(*args, **kwargs):
  415             return {'security_group': {'id': 'fake_sg_id', 'name': args[0],
  416                     'description': args[1]}}
  417 
  418         config_name = "fake_sg_name_from_config"
  419         desc = "fake_sg_description"
  420         self.mock_object(self._manager, 'get_config_option',
  421                          mock.Mock(return_value=name or config_name))
  422         neutron_api = self._manager.network_helper.neutron_api
  423         neutron_api.security_group_list.return_value = {'security_groups': []}
  424         self.mock_object(neutron_api, 'security_group_create',
  425                          mock.Mock(side_effect=fake_secgroup))
  426         fake_ssh_allow_subnet = dict(cidr="10.254.0.1/24",
  427                                      id='allow_subnet_id')
  428         ssh_sg_name = 'manila-service-subnet-{}'.format(
  429             fake_ssh_allow_subnet['id'])
  430 
  431         result = self._manager._get_or_create_security_groups(
  432             context=self._manager.admin_context,
  433             name=name,
  434             description=desc,
  435             allow_ssh_subnet=fake_ssh_allow_subnet
  436         )
  437 
  438         self.assertEqual([fake_secgroup(name if name else config_name,
  439                                         desc)['security_group'],
  440                           fake_secgroup(ssh_sg_name, desc)['security_group']],
  441                          result)
  442         if not name:
  443             self._manager.get_config_option.assert_called_with(
  444                 'service_instance_security_group')
  445         neutron_api.security_group_list.assert_has_calls([
  446             mock.call({"name": name or config_name}),
  447             mock.call({"name": ssh_sg_name})])
  448         neutron_api.security_group_create.assert_has_calls([
  449             mock.call(name or config_name, desc),
  450             mock.call(ssh_sg_name, desc)])
  451 
  452     def test_security_group_limit_ssh_invalid_subnet(self):
  453         def fake_secgroup(*args, **kwargs):
  454             return {'security_group': {'id': 'fake_sg_id', 'name': args[0],
  455                                        'description': args[1]}}
  456 
  457         config_name = "fake_sg_name_from_config"
  458         desc = "fake_sg_description"
  459         self.mock_object(self._manager, 'get_config_option',
  460                          mock.Mock(config_name))
  461         neutron_api = self._manager.network_helper.neutron_api
  462         neutron_api.security_group_list.return_value = {'security_groups': []}
  463         self.mock_object(neutron_api, 'security_group_create',
  464                          mock.Mock(side_effect=fake_secgroup))
  465         fake_ssh_allow_subnet = dict(id='allow_subnet_id')
  466         self.assertRaises(exception.ManilaException,
  467                           self._manager._get_or_create_security_groups,
  468                           context=self._manager.admin_context,
  469                           name=None,
  470                           description=desc,
  471                           allow_ssh_subnet=fake_ssh_allow_subnet)
  472 
  473     def test_security_group_two_sg_in_list(self):
  474         name = "fake_name"
  475         fake_secgroup1 = {'id': 'fake_sg_id1', 'name': name}
  476         fake_secgroup2 = {'id': 'fake_sg_id2', 'name': name}
  477         neutron_api = self._manager.network_helper.neutron_api
  478         neutron_api.security_group_list.return_value = {
  479             'security_groups': [fake_secgroup1, fake_secgroup2]}
  480 
  481         self.assertRaises(exception.ServiceInstanceException,
  482                           self._manager._get_or_create_security_groups,
  483                           self._manager.admin_context,
  484                           name)
  485 
  486         neutron_api.security_group_list.assert_called_once_with(
  487             {"name": name})
  488 
  489     @ddt.data(
  490         dict(),
  491         dict(service_port_id='fake_service_port_id'),
  492         dict(public_port_id='fake_public_port_id'),
  493         dict(service_port_id='fake_service_port_id',
  494              public_port_id='fake_public_port_id'),
  495     )
  496     def test_set_up_service_instance(self, update_data):
  497         fake_network_info = {'foo': 'bar', 'server_id': 'fake_server_id'}
  498         fake_server = {
  499             'id': 'fake', 'ip': '1.2.3.4', 'public_address': '1.2.3.4',
  500             'pk_path': None, 'subnet_id': 'fake-subnet-id',
  501             'router_id': 'fake-router-id',
  502             'username': self._manager.get_config_option(
  503                 'service_instance_user'),
  504             'admin_ip': 'admin_ip'}
  505         fake_server.update(update_data)
  506         expected_details = fake_server.copy()
  507         expected_details.pop('pk_path')
  508         expected_details['instance_id'] = expected_details.pop('id')
  509         self.mock_object(self._manager, '_create_service_instance',
  510                          mock.Mock(return_value=fake_server))
  511         self.mock_object(self._manager, '_check_server_availability')
  512 
  513         result = self._manager.set_up_service_instance(
  514             self._manager.admin_context, fake_network_info)
  515 
  516         self._manager._create_service_instance.assert_called_once_with(
  517             self._manager.admin_context,
  518             fake_network_info['server_id'], fake_network_info)
  519         self._manager._check_server_availability.assert_called_once_with(
  520             expected_details)
  521         self.assertEqual(expected_details, result)
  522 
  523     def test_set_up_service_instance_not_available(self):
  524         fake_network_info = {'foo': 'bar', 'server_id': 'fake_server_id'}
  525         fake_server = {
  526             'id': 'fake', 'ip': '1.2.3.4', 'public_address': '1.2.3.4',
  527             'pk_path': None, 'subnet_id': 'fake-subnet-id',
  528             'router_id': 'fake-router-id',
  529             'username': self._manager.get_config_option(
  530                 'service_instance_user'),
  531             'admin_ip': 'admin_ip'}
  532         expected_details = fake_server.copy()
  533         expected_details.pop('pk_path')
  534         expected_details['instance_id'] = expected_details.pop('id')
  535         self.mock_object(self._manager, '_create_service_instance',
  536                          mock.Mock(return_value=fake_server))
  537         self.mock_object(self._manager, '_check_server_availability',
  538                          mock.Mock(return_value=False))
  539 
  540         result = self.assertRaises(
  541             exception.ServiceInstanceException,
  542             self._manager.set_up_service_instance,
  543             self._manager.admin_context, fake_network_info)
  544 
  545         self.assertTrue(hasattr(result, 'detail_data'))
  546         self.assertEqual(
  547             {'server_details': expected_details}, result.detail_data)
  548         self._manager._create_service_instance.assert_called_once_with(
  549             self._manager.admin_context,
  550             fake_network_info['server_id'], fake_network_info)
  551         self._manager._check_server_availability.assert_called_once_with(
  552             expected_details)
  553 
  554     def test_ensure_server(self):
  555         server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
  556         fake_server = fake_compute.FakeServer()
  557         self.mock_object(self._manager, '_check_server_availability',
  558                          mock.Mock(return_value=True))
  559         self.mock_object(self._manager.compute_api, 'server_get',
  560                          mock.Mock(return_value=fake_server))
  561         result = self._manager.ensure_service_instance(
  562             self._manager.admin_context, server_details)
  563         self._manager.compute_api.server_get.assert_called_once_with(
  564             self._manager.admin_context, server_details['instance_id'])
  565         self._manager._check_server_availability.assert_called_once_with(
  566             server_details)
  567         self.assertTrue(result)
  568 
  569     def test_ensure_server_not_exists(self):
  570         server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
  571         self.mock_object(self._manager, '_check_server_availability',
  572                          mock.Mock(return_value=True))
  573         self.mock_object(self._manager.compute_api, 'server_get',
  574                          mock.Mock(side_effect=exception.InstanceNotFound(
  575                              instance_id=server_details['instance_id'])))
  576         result = self._manager.ensure_service_instance(
  577             self._manager.admin_context, server_details)
  578         self._manager.compute_api.server_get.assert_called_once_with(
  579             self._manager.admin_context, server_details['instance_id'])
  580         self.assertFalse(self._manager._check_server_availability.called)
  581         self.assertFalse(result)
  582 
  583     def test_ensure_server_exception(self):
  584         server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
  585         self.mock_object(self._manager, '_check_server_availability',
  586                          mock.Mock(return_value=True))
  587         self.mock_object(self._manager.compute_api, 'server_get',
  588                          mock.Mock(side_effect=exception.ManilaException))
  589         self.assertRaises(exception.ManilaException,
  590                           self._manager.ensure_service_instance,
  591                           self._manager.admin_context,
  592                           server_details)
  593         self._manager.compute_api.server_get.assert_called_once_with(
  594             self._manager.admin_context, server_details['instance_id'])
  595         self.assertFalse(self._manager._check_server_availability.called)
  596 
  597     def test_ensure_server_non_active(self):
  598         server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
  599         fake_server = fake_compute.FakeServer(status='ERROR')
  600         self.mock_object(self._manager.compute_api, 'server_get',
  601                          mock.Mock(return_value=fake_server))
  602         self.mock_object(self._manager, '_check_server_availability',
  603                          mock.Mock(return_value=True))
  604         result = self._manager.ensure_service_instance(
  605             self._manager.admin_context, server_details)
  606         self.assertFalse(self._manager._check_server_availability.called)
  607         self.assertFalse(result)
  608 
  609     def test_ensure_server_no_instance_id(self):
  610         # Tests that we avoid a KeyError if the share details don't have an
  611         # instance_id key set (so we can't find the share instance).
  612         self.assertFalse(self._manager.ensure_service_instance(
  613             self._manager.admin_context, {'ip': '1.2.3.4'}))
  614 
  615     def test_get_key_create_new(self):
  616         keypair_name = self._manager.get_config_option(
  617             'manila_service_keypair_name')
  618         fake_keypair = fake_compute.FakeKeypair(name=keypair_name)
  619         self.mock_object(self._manager.compute_api, 'keypair_list',
  620                          mock.Mock(return_value=[]))
  621         self.mock_object(self._manager.compute_api, 'keypair_import',
  622                          mock.Mock(return_value=fake_keypair))
  623 
  624         result = self._manager._get_key(self._manager.admin_context)
  625 
  626         self.assertEqual(
  627             (fake_keypair.name,
  628              os.path.expanduser(self._manager.get_config_option(
  629                  'path_to_private_key'))),
  630             result)
  631         self._manager.compute_api.keypair_list.assert_called_once_with(
  632             self._manager.admin_context)
  633         self._manager.compute_api.keypair_import.assert_called_once_with(
  634             self._manager.admin_context, keypair_name, '')
  635 
  636     def test_get_key_exists(self):
  637         fake_keypair = fake_compute.FakeKeypair(
  638             name=self._manager.get_config_option(
  639                 'manila_service_keypair_name'),
  640             public_key='fake_public_key')
  641         self.mock_object(self._manager.compute_api, 'keypair_list',
  642                          mock.Mock(return_value=[fake_keypair]))
  643         self.mock_object(self._manager.compute_api, 'keypair_import',
  644                          mock.Mock(return_value=fake_keypair))
  645         self.mock_object(self._manager, '_execute',
  646                          mock.Mock(return_value=('fake_public_key', '')))
  647 
  648         result = self._manager._get_key(self._manager.admin_context)
  649 
  650         self._manager.compute_api.keypair_list.assert_called_once_with(
  651             self._manager.admin_context)
  652         self.assertFalse(self._manager.compute_api.keypair_import.called)
  653         self.assertEqual(
  654             (fake_keypair.name,
  655              os.path.expanduser(self._manager.get_config_option(
  656                  'path_to_private_key'))),
  657             result)
  658 
  659     def test_get_key_exists_recreate(self):
  660         fake_keypair = fake_compute.FakeKeypair(
  661             name=self._manager.get_config_option(
  662                 'manila_service_keypair_name'),
  663             public_key='fake_public_key1')
  664         self.mock_object(self._manager.compute_api, 'keypair_list',
  665                          mock.Mock(return_value=[fake_keypair]))
  666         self.mock_object(self._manager.compute_api, 'keypair_import',
  667                          mock.Mock(return_value=fake_keypair))
  668         self.mock_object(self._manager.compute_api, 'keypair_delete')
  669         self.mock_object(self._manager, '_execute',
  670                          mock.Mock(return_value=('fake_public_key2', '')))
  671 
  672         result = self._manager._get_key(self._manager.admin_context)
  673 
  674         self._manager.compute_api.keypair_list.assert_called_once_with(
  675             self._manager.admin_context)
  676         self._manager.compute_api.keypair_delete.assert_called_once_with(
  677             self._manager.admin_context, fake_keypair.id)
  678         self._manager.compute_api.keypair_import.assert_called_once_with(
  679             self._manager.admin_context, fake_keypair.name, 'fake_public_key2')
  680         self.assertEqual(
  681             (fake_keypair.name,
  682              os.path.expanduser(self._manager.get_config_option(
  683                  'path_to_private_key'))),
  684             result)
  685 
  686     def test_get_key_more_than_one_exist(self):
  687         fake_keypair = fake_compute.FakeKeypair(
  688             name=self._manager.get_config_option(
  689                 'manila_service_keypair_name'),
  690             public_key='fake_public_key1')
  691         self.mock_object(self._manager.compute_api, 'keypair_list',
  692                          mock.Mock(return_value=[fake_keypair, fake_keypair]))
  693 
  694         self.assertRaises(
  695             exception.ServiceInstanceException,
  696             self._manager._get_key, self._manager.admin_context)
  697         self._manager.compute_api.keypair_list.assert_called_once_with(
  698             self._manager.admin_context)
  699 
  700     def test_get_key_keypath_to_public_not_set(self):
  701         self._manager.path_to_public_key = None
  702         result = self._manager._get_key(self._manager.admin_context)
  703         self.assertEqual((None, None), result)
  704 
  705     def test_get_key_keypath_to_private_not_set(self):
  706         self._manager.path_to_private_key = None
  707         result = self._manager._get_key(self._manager.admin_context)
  708         self.assertEqual((None, None), result)
  709 
  710     def test_get_key_incorrect_keypath_to_public(self):
  711         def exists_side_effect(path):
  712             return False if path == 'fake_path' else True
  713 
  714         self._manager.path_to_public_key = 'fake_path'
  715         os_path_exists_mock = mock.Mock(side_effect=exists_side_effect)
  716         with mock.patch.object(os.path, 'exists', os_path_exists_mock):
  717             with mock.patch.object(os.path, 'expanduser',
  718                                    mock.Mock(side_effect=lambda value: value)):
  719                 result = self._manager._get_key(self._manager.admin_context)
  720                 self.assertEqual((None, None), result)
  721 
  722     def test_get_key_incorrect_keypath_to_private(self):
  723         def exists_side_effect(path):
  724             return False if path == 'fake_path' else True
  725 
  726         self._manager.path_to_private_key = 'fake_path'
  727         os_path_exists_mock = mock.Mock(side_effect=exists_side_effect)
  728         with mock.patch.object(os.path, 'exists', os_path_exists_mock):
  729             with mock.patch.object(os.path, 'expanduser',
  730                                    mock.Mock(side_effect=lambda value: value)):
  731                 result = self._manager._get_key(self._manager.admin_context)
  732                 self.assertEqual((None, None), result)
  733 
  734     def test_get_service_image(self):
  735         fake_image1 = fake_compute.FakeImage(
  736             name=self._manager.get_config_option('service_image_name'),
  737             status='active')
  738         fake_image2 = fake_compute.FakeImage(
  739             name='service_image_name',
  740             status='error')
  741         fake_image3 = fake_compute.FakeImage(
  742             name='another-image',
  743             status='active')
  744         self.mock_object(self._manager.compute_api, 'image_list',
  745                          mock.Mock(return_value=[fake_image1,
  746                                                  fake_image2,
  747                                                  fake_image3]))
  748 
  749         result = self._manager._get_service_image(self._manager.admin_context)
  750         self.assertEqual(fake_image1.id, result)
  751 
  752     def test_get_service_image_not_found(self):
  753         self.mock_object(self._manager.compute_api, 'image_list',
  754                          mock.Mock(return_value=[]))
  755         self.assertRaises(
  756             exception.ServiceInstanceException,
  757             self._manager._get_service_image, self._manager.admin_context)
  758 
  759         fake_error_image = fake_compute.FakeImage(
  760             name='service_image_name',
  761             status='error')
  762         self.mock_object(self._manager.compute_api, 'image_list',
  763                          mock.Mock(return_value=[fake_error_image]))
  764         self.assertRaises(
  765             exception.ServiceInstanceException,
  766             self._manager._get_service_image, self._manager.admin_context)
  767 
  768     def test_get_service_image_ambiguous(self):
  769         fake_image = fake_compute.FakeImage(
  770             name=fake_get_config_option('service_image_name'),
  771             status='active')
  772         fake_images = [fake_image, fake_image]
  773         self.mock_object(self._manager.compute_api, 'image_list',
  774                          mock.Mock(return_value=fake_images))
  775         self.assertRaises(
  776             exception.ServiceInstanceException,
  777             self._manager._get_service_image, self._manager.admin_context)
  778 
  779     def test__delete_server_not_found(self):
  780         self.mock_object(self._manager.compute_api, 'server_delete')
  781         self.mock_object(
  782             self._manager.compute_api, 'server_get',
  783             mock.Mock(side_effect=exception.InstanceNotFound(
  784                 instance_id=self.instance_id)))
  785 
  786         self._manager._delete_server(
  787             self._manager.admin_context, self.instance_id)
  788 
  789         self.assertFalse(self._manager.compute_api.server_delete.called)
  790         self._manager.compute_api.server_get.assert_called_once_with(
  791             self._manager.admin_context, self.instance_id)
  792 
  793     def test__delete_server(self):
  794         def fake_server_get(*args, **kwargs):
  795             ctx = args[0]
  796             if not hasattr(ctx, 'called'):
  797                 ctx.called = True
  798                 return
  799             else:
  800                 raise exception.InstanceNotFound(instance_id=self.instance_id)
  801 
  802         self.mock_object(self._manager.compute_api, 'server_delete')
  803         self.mock_object(self._manager.compute_api, 'server_get',
  804                          mock.Mock(side_effect=fake_server_get))
  805 
  806         self._manager._delete_server(
  807             self._manager.admin_context, self.instance_id)
  808 
  809         self._manager.compute_api.server_delete.assert_called_once_with(
  810             self._manager.admin_context, self.instance_id)
  811         self._manager.compute_api.server_get.assert_has_calls([
  812             mock.call(self._manager.admin_context, self.instance_id),
  813             mock.call(self._manager.admin_context, self.instance_id)])
  814 
  815     def test__delete_server_found_always(self):
  816         self.fake_time = 0
  817 
  818         def fake_time():
  819             return self.fake_time
  820 
  821         def fake_sleep(time):
  822             self.fake_time += 1
  823 
  824         self.mock_object(self._manager.compute_api, 'server_delete')
  825         self.mock_object(self._manager.compute_api, 'server_get')
  826         self.mock_object(service_instance, 'time')
  827         self.mock_object(
  828             service_instance.time, 'time', mock.Mock(side_effect=fake_time))
  829         self.mock_object(
  830             service_instance.time, 'sleep', mock.Mock(side_effect=fake_sleep))
  831         self.mock_object(self._manager, 'max_time_to_build_instance', 2)
  832 
  833         self.assertRaises(
  834             exception.ServiceInstanceException, self._manager._delete_server,
  835             self._manager.admin_context, self.instance_id)
  836 
  837         self._manager.compute_api.server_delete.assert_called_once_with(
  838             self._manager.admin_context, self.instance_id)
  839         service_instance.time.sleep.assert_has_calls(
  840             [mock.call(mock.ANY) for i in range(2)])
  841         service_instance.time.time.assert_has_calls(
  842             [mock.call() for i in range(4)])
  843         self._manager.compute_api.server_get.assert_has_calls(
  844             [mock.call(self._manager.admin_context,
  845                        self.instance_id) for i in range(3)])
  846 
  847     def test_delete_service_instance(self):
  848         fake_server_details = dict(
  849             router_id='foo', subnet_id='bar', instance_id='quuz')
  850         self.mock_object(self._manager, '_delete_server')
  851         self.mock_object(self._manager.network_helper, 'teardown_network')
  852 
  853         self._manager.delete_service_instance(
  854             self._manager.admin_context, fake_server_details)
  855 
  856         self._manager._delete_server.assert_called_once_with(
  857             self._manager.admin_context, fake_server_details['instance_id'])
  858         self._manager.network_helper.teardown_network.assert_called_once_with(
  859             fake_server_details)
  860 
  861     @ddt.data(
  862         *[{'service_config': service_config,
  863            'tenant_config': tenant_config,
  864            'server': server}
  865             for service_config, tenant_config in (
  866                 ('fake_net_s', 'fake_net_t'),
  867                 ('fake_net_s', '12.34.56.78'),
  868                 ('98.76.54.123', 'fake_net_t'),
  869                 ('98.76.54.123', '12.34.56.78'))
  870             for server in (
  871                 {'networks': {
  872                     'fake_net_s': ['foo', '98.76.54.123', 'bar'],
  873                     'fake_net_t': ['baar', '12.34.56.78', 'quuz']}},
  874                 {'addresses': {
  875                     'fake_net_s': [
  876                         {'addr': 'fake1'},
  877                         {'addr': '98.76.54.123'},
  878                         {'addr': 'fake2'}],
  879                     'fake_net_t': [
  880                         {'addr': 'fake3'},
  881                         {'addr': '12.34.56.78'},
  882                         {'addr': 'fake4'}],
  883                 }})])
  884     @ddt.unpack
  885     def test_get_common_server_valid_cases(self, service_config,
  886                                            tenant_config, server):
  887         self._get_common_server(service_config, tenant_config, server,
  888                                 '98.76.54.123', '12.34.56.78', True)
  889 
  890     @ddt.data(
  891         *[{'service_config': service_config,
  892            'tenant_config': tenant_config,
  893            'server': server}
  894             for service_config, tenant_config in (
  895                 ('fake_net_s', 'fake'),
  896                 ('fake', 'fake_net_t'),
  897                 ('fake', 'fake'),
  898                 ('98.76.54.123', '12.12.12.1212'),
  899                 ('12.12.12.1212', '12.34.56.78'),
  900                 ('12.12.12.1212', '12.12.12.1212'),
  901                 ('1001::1001', '1001::100G'),
  902                 ('1001::10G1', '1001::1001'),
  903                 )
  904             for server in (
  905                 {'networks': {
  906                     'fake_net_s': ['foo', '98.76.54.123', 'bar'],
  907                     'fake_net_t': ['baar', '12.34.56.78', 'quuz']}},
  908                 {'addresses': {
  909                     'fake_net_s': [
  910                         {'addr': 'fake1'},
  911                         {'addr': '98.76.54.123'},
  912                         {'addr': 'fake2'}],
  913                     'fake_net_t': [
  914                         {'addr': 'fake3'},
  915                         {'addr': '12.34.56.78'},
  916                         {'addr': 'fake4'}],
  917                 }})])
  918     @ddt.unpack
  919     def test_get_common_server_invalid_cases(self, service_config,
  920                                              tenant_config, server):
  921         self._get_common_server(service_config, tenant_config, server,
  922                                 '98.76.54.123', '12.34.56.78', False)
  923 
  924     @ddt.data(
  925         *[{'service_config': service_config,
  926             'tenant_config': tenant_config,
  927             'server': server}
  928             for service_config, tenant_config in (
  929             ('fake_net_s', '1001::1002'),
  930             ('1001::1001', 'fake_net_t'),
  931             ('1001::1001', '1001::1002'))
  932             for server in (
  933                 {'networks': {
  934                  'fake_net_s': ['foo', '1001::1001'],
  935                  'fake_net_t': ['bar', '1001::1002']}},
  936                 {'addresses': {
  937                  'fake_net_s': [{'addr': 'foo'}, {'addr': '1001::1001'}],
  938                  'fake_net_t': [{'addr': 'bar'}, {'addr': '1001::1002'}]}})])
  939     @ddt.unpack
  940     def test_get_common_server_valid_ipv6_address(self, service_config,
  941                                                   tenant_config, server):
  942         self._get_common_server(service_config, tenant_config, server,
  943                                 '1001::1001', '1001::1002', True)
  944 
  945     def _get_common_server(self, service_config, tenant_config,
  946                            server, service_address, network_address,
  947                            is_valid=True):
  948         fake_instance_id = 'fake_instance_id'
  949         fake_user = 'fake_user'
  950         fake_pass = 'fake_pass'
  951         fake_server = {'id': fake_instance_id}
  952         fake_server.update(server)
  953         expected = {
  954             'backend_details': {
  955                 'username': fake_user,
  956                 'password': fake_pass,
  957                 'pk_path': self._manager.path_to_private_key,
  958                 'ip': service_address,
  959                 'public_address': network_address,
  960                 'instance_id': fake_instance_id,
  961             }
  962         }
  963 
  964         def fake_get_config_option(attr):
  965             if attr == 'service_net_name_or_ip':
  966                 return service_config
  967             elif attr == 'tenant_net_name_or_ip':
  968                 return tenant_config
  969             elif attr == 'service_instance_name_or_id':
  970                 return fake_instance_id
  971             elif attr == 'service_instance_user':
  972                 return fake_user
  973             elif attr == 'service_instance_password':
  974                 return fake_pass
  975             else:
  976                 raise exception.ManilaException("Wrong test data provided.")
  977 
  978         self.mock_object(
  979             self._manager.compute_api, 'server_get_by_name_or_id',
  980             mock.Mock(return_value=fake_server))
  981         self.mock_object(
  982             self._manager, 'get_config_option',
  983             mock.Mock(side_effect=fake_get_config_option))
  984 
  985         if is_valid:
  986             actual = self._manager.get_common_server()
  987             self.assertEqual(expected, actual)
  988         else:
  989             self.assertRaises(
  990                 exception.ManilaException,
  991                 self._manager.get_common_server)
  992         self.assertTrue(
  993             self._manager.compute_api.server_get_by_name_or_id.called)
  994 
  995     def test___create_service_instance_with_sg_success(self):
  996         self.mock_object(service_instance, 'NeutronNetworkHelper',
  997                          mock.Mock(side_effect=FakeNetworkHelper))
  998         config_data = dict(DEFAULT=dict(
  999             driver_handles_share_servers=True,
 1000             service_instance_user='fake_user',
 1001             limit_ssh_access=True))
 1002         with test_utils.create_temp_config_with_opts(config_data):
 1003             self._manager = service_instance.ServiceInstanceManager()
 1004 
 1005         server_create = dict(id='fakeid', status='CREATING', networks=dict())
 1006         net_name = self._manager.get_config_option("service_network_name")
 1007         sg = [{'id': 'fakeid', 'name': 'fakename'}, ]
 1008         ip_address = 'fake_ip_address'
 1009         service_image_id = 'fake_service_image_id'
 1010         key_data = 'fake_key_name', 'fake_key_path'
 1011         instance_name = 'fake_instance_name'
 1012         network_info = dict()
 1013         network_data = {'nics': ['fake_nic1', 'fake_nic2']}
 1014         network_data['router'] = dict(id='fake_router_id')
 1015         server_get = dict(
 1016             id='fakeid', status='ACTIVE', networks={net_name: [ip_address]})
 1017         network_data.update(dict(
 1018             router_id='fake_router_id', subnet_id='fake_subnet_id',
 1019             public_port=dict(id='fake_public_port',
 1020                              fixed_ips=[dict(ip_address=ip_address)]),
 1021             service_port=dict(id='fake_service_port',
 1022                               fixed_ips=[{'ip_address': ip_address}]),
 1023             admin_port={'id': 'fake_admin_port',
 1024                         'fixed_ips': [{'ip_address': ip_address}]},
 1025             service_subnet={'id': 'fake_subnet_id',
 1026                             'cidr': '10.254.0.0/28'})
 1027         )
 1028         self.mock_object(service_instance.time, 'time',
 1029                          mock.Mock(return_value=5))
 1030         self.mock_object(self._manager.network_helper, 'setup_network',
 1031                          mock.Mock(return_value=network_data))
 1032         self.mock_object(self._manager.network_helper, 'get_network_name',
 1033                          mock.Mock(return_value=net_name))
 1034         self.mock_object(self._manager, '_get_service_image',
 1035                          mock.Mock(return_value=service_image_id))
 1036         self.mock_object(self._manager, '_get_key',
 1037                          mock.Mock(return_value=key_data))
 1038         self.mock_object(self._manager, '_get_or_create_security_groups',
 1039                          mock.Mock(return_value=sg))
 1040         self.mock_object(self._manager.compute_api, 'server_create',
 1041                          mock.Mock(return_value=server_create))
 1042         self.mock_object(self._manager.compute_api, 'server_get',
 1043                          mock.Mock(return_value=server_get))
 1044         self.mock_object(self._manager.compute_api,
 1045                          'add_security_group_to_server')
 1046         expected = {
 1047             'id': server_get['id'],
 1048             'status': server_get['status'],
 1049             'pk_path': key_data[1],
 1050             'public_address': ip_address,
 1051             'router_id': network_data.get('router_id'),
 1052             'subnet_id': network_data.get('subnet_id'),
 1053             'instance_id': server_get['id'],
 1054             'ip': ip_address,
 1055             'networks': server_get['networks'],
 1056             'router_id': network_data['router']['id'],
 1057             'public_port_id': 'fake_public_port',
 1058             'service_port_id': 'fake_service_port',
 1059             'admin_port_id': 'fake_admin_port',
 1060             'admin_ip': 'fake_ip_address',
 1061         }
 1062 
 1063         result = self._manager._create_service_instance(
 1064             self._manager.admin_context, instance_name, network_info)
 1065 
 1066         self.assertEqual(expected, result)
 1067         self.assertTrue(service_instance.time.time.called)
 1068         self._manager.network_helper.setup_network.assert_called_once_with(
 1069             network_info)
 1070         self._manager._get_service_image.assert_called_once_with(
 1071             self._manager.admin_context)
 1072         self._manager._get_key.assert_called_once_with(
 1073             self._manager.admin_context)
 1074         self._manager._get_or_create_security_groups.assert_called_once_with(
 1075             self._manager.admin_context,
 1076             allow_ssh_subnet=network_data['service_subnet'])
 1077         self._manager.compute_api.server_create.assert_called_once_with(
 1078             self._manager.admin_context, name=instance_name,
 1079             image=service_image_id, flavor=100,
 1080             key_name=key_data[0], nics=network_data['nics'],
 1081             availability_zone=service_instance.CONF.storage_availability_zone)
 1082         self._manager.compute_api.server_get.assert_called_once_with(
 1083             self._manager.admin_context, server_create['id'])
 1084         (self._manager.compute_api.add_security_group_to_server.
 1085             assert_called_once_with(
 1086                 self._manager.admin_context,
 1087                 server_get['id'],
 1088                 sg[0]['id']))
 1089         self._manager.network_helper.get_network_name.assert_has_calls([])
 1090 
 1091     def test___create_service_instance_neutron_no_admin_ip(self):
 1092         self.mock_object(service_instance, 'NeutronNetworkHelper',
 1093                          mock.Mock(side_effect=FakeNetworkHelper))
 1094         config_data = {'DEFAULT': {
 1095             'driver_handles_share_servers': True,
 1096             'service_instance_user': 'fake_user',
 1097             'limit_ssh_access': True}}
 1098         with test_utils.create_temp_config_with_opts(config_data):
 1099             self._manager = service_instance.ServiceInstanceManager()
 1100 
 1101         server_create = {'id': 'fakeid', 'status': 'CREATING', 'networks': {}}
 1102         net_name = self._manager.get_config_option("service_network_name")
 1103         sg = {'id': 'fakeid', 'name': 'fakename'}
 1104         ip_address = 'fake_ip_address'
 1105         service_image_id = 'fake_service_image_id'
 1106         key_data = 'fake_key_name', 'fake_key_path'
 1107         instance_name = 'fake_instance_name'
 1108         network_info = {}
 1109         network_data = {
 1110             'nics': ['fake_nic1', 'fake_nic2'],
 1111             'router_id': 'fake_router_id', 'subnet_id': 'fake_subnet_id',
 1112             'public_port': {'id': 'fake_public_port',
 1113                             'fixed_ips': [{'ip_address': ip_address}]},
 1114             'service_port': {'id': 'fake_service_port',
 1115                              'fixed_ips': [{'ip_address': ip_address}]},
 1116             'admin_port': {'id': 'fake_admin_port',
 1117                            'fixed_ips': []},
 1118             'router': {'id': 'fake_router_id'},
 1119             'service_subnet': {'id': 'fake_id',
 1120                                'cidr': '10.254.0.0/28'}
 1121         }
 1122         server_get = {
 1123             'id': 'fakeid', 'status': 'ACTIVE', 'networks':
 1124             {net_name: [ip_address]}}
 1125 
 1126         self.mock_object(service_instance.time, 'time',
 1127                          mock.Mock(return_value=5))
 1128         self.mock_object(self._manager.network_helper, 'setup_network',
 1129                          mock.Mock(return_value=network_data))
 1130         self.mock_object(self._manager.network_helper, 'get_network_name',
 1131                          mock.Mock(return_value=net_name))
 1132         self.mock_object(self._manager, '_get_service_image',
 1133                          mock.Mock(return_value=service_image_id))
 1134         self.mock_object(self._manager, '_get_key',
 1135                          mock.Mock(return_value=key_data))
 1136         self.mock_object(self._manager, '_get_or_create_security_groups',
 1137                          mock.Mock(return_value=[sg, ]))
 1138         self.mock_object(self._manager.compute_api, 'server_create',
 1139                          mock.Mock(return_value=server_create))
 1140         self.mock_object(self._manager.compute_api, 'server_get',
 1141                          mock.Mock(return_value=server_get))
 1142         self.mock_object(self._manager.compute_api,
 1143                          'add_security_group_to_server')
 1144 
 1145         self.assertRaises(
 1146             exception.AdminIPNotFound, self._manager._create_service_instance,
 1147             self._manager.admin_context, instance_name, network_info)
 1148 
 1149         self.assertTrue(service_instance.time.time.called)
 1150         self._manager.network_helper.setup_network.assert_called_once_with(
 1151             network_info)
 1152         self._manager._get_service_image.assert_called_once_with(
 1153             self._manager.admin_context)
 1154         self._manager._get_key.assert_called_once_with(
 1155             self._manager.admin_context)
 1156         self._manager._get_or_create_security_groups.assert_called_once_with(
 1157             self._manager.admin_context,
 1158             allow_ssh_subnet=network_data['service_subnet'])
 1159         self._manager.compute_api.server_create.assert_called_once_with(
 1160             self._manager.admin_context, name=instance_name,
 1161             image=service_image_id, flavor=100,
 1162             key_name=key_data[0], nics=network_data['nics'],
 1163             availability_zone=service_instance.CONF.storage_availability_zone)
 1164         self._manager.compute_api.server_get.assert_called_once_with(
 1165             self._manager.admin_context, server_create['id'])
 1166         (self._manager.compute_api.add_security_group_to_server.
 1167             assert_called_once_with(
 1168                 self._manager.admin_context, server_get['id'], sg['id']))
 1169         self._manager.network_helper.get_network_name.assert_has_calls([])
 1170 
 1171     @ddt.data(
 1172         dict(
 1173             instance_id_included=False,
 1174             mockobj=mock.Mock(side_effect=exception.ServiceInstanceException)),
 1175         dict(
 1176             instance_id_included=True,
 1177             mockobj=mock.Mock(return_value=dict(id='fakeid', status='ERROR'))))
 1178     @ddt.unpack
 1179     def test___create_service_instance_failed_to_create(
 1180             self, instance_id_included, mockobj):
 1181         service_image_id = 'fake_service_image_id'
 1182         key_data = 'fake_key_name', 'fake_key_path'
 1183         instance_name = 'fake_instance_name'
 1184         network_info = dict()
 1185         network_data = dict(
 1186             nics=['fake_nic1', 'fake_nic2'],
 1187             router_id='fake_router_id', subnet_id='fake_subnet_id')
 1188         self.mock_object(self._manager.network_helper, 'setup_network',
 1189                          mock.Mock(return_value=network_data))
 1190         self.mock_object(self._manager, '_get_service_image',
 1191                          mock.Mock(return_value=service_image_id))
 1192         self.mock_object(self._manager, '_get_key',
 1193                          mock.Mock(return_value=key_data))
 1194         self.mock_object(
 1195             self._manager.compute_api, 'server_create', mockobj)
 1196         self.mock_object(
 1197             self._manager, 'wait_for_instance_to_be_active',
 1198             mock.Mock(side_effect=exception.ServiceInstanceException))
 1199 
 1200         try:
 1201             self._manager._create_service_instance(
 1202                 self._manager.admin_context, instance_name, network_info)
 1203         except exception.ServiceInstanceException as e:
 1204             expected = dict(server_details=dict(
 1205                 subnet_id=network_data['subnet_id'],
 1206                 router_id=network_data['router_id']))
 1207             if instance_id_included:
 1208                 expected['server_details']['instance_id'] = 'fakeid'
 1209             self.assertEqual(expected, e.detail_data)
 1210         else:
 1211             raise exception.ManilaException('Expected error was not raised.')
 1212 
 1213         self._manager.network_helper.setup_network.assert_called_once_with(
 1214             network_info)
 1215         self._manager._get_service_image.assert_called_once_with(
 1216             self._manager.admin_context)
 1217         self._manager._get_key.assert_called_once_with(
 1218             self._manager.admin_context)
 1219         self._manager.compute_api.server_create.assert_called_once_with(
 1220             self._manager.admin_context, name=instance_name,
 1221             image=service_image_id, flavor=100,
 1222             key_name=key_data[0], nics=network_data['nics'],
 1223             availability_zone=service_instance.CONF.storage_availability_zone)
 1224 
 1225     def test___create_service_instance_limit_ssh_no_service_subnet(self):
 1226         self.mock_object(service_instance, 'NeutronNetworkHelper',
 1227                          mock.Mock(side_effect=FakeNetworkHelper))
 1228         config_data = dict(DEFAULT=dict(
 1229             driver_handles_share_servers=True,
 1230             service_instance_user='fake_user',
 1231             limit_ssh_access=True))
 1232         with test_utils.create_temp_config_with_opts(config_data):
 1233             self._manager = service_instance.ServiceInstanceManager()
 1234 
 1235         server_create = dict(id='fakeid', status='CREATING', networks=dict())
 1236         net_name = self._manager.get_config_option("service_network_name")
 1237         ip_address = 'fake_ip_address'
 1238         service_image_id = 'fake_service_image_id'
 1239         key_data = 'fake_key_name', 'fake_key_path'
 1240         instance_name = 'fake_instance_name'
 1241         network_info = dict()
 1242         network_data = {'nics': ['fake_nic1', 'fake_nic2']}
 1243         network_data['router'] = dict(id='fake_router_id')
 1244         server_get = dict(
 1245             id='fakeid', status='ACTIVE', networks={net_name: [ip_address]})
 1246         network_data.update(dict(
 1247             router_id='fake_router_id', subnet_id='fake_subnet_id',
 1248             public_port=dict(id='fake_public_port',
 1249                              fixed_ips=[dict(ip_address=ip_address)]),
 1250             service_port=dict(id='fake_service_port',
 1251                               fixed_ips=[{'ip_address': ip_address}]),
 1252             admin_port={'id': 'fake_admin_port',
 1253                         'fixed_ips': [{'ip_address': ip_address}]},)
 1254         )
 1255         self.mock_object(service_instance.time, 'time',
 1256                          mock.Mock(return_value=5))
 1257         self.mock_object(self._manager.network_helper, 'setup_network',
 1258                          mock.Mock(return_value=network_data))
 1259         self.mock_object(self._manager.network_helper, 'get_network_name',
 1260                          mock.Mock(return_value=net_name))
 1261         self.mock_object(self._manager, '_get_service_image',
 1262                          mock.Mock(return_value=service_image_id))
 1263         self.mock_object(self._manager, '_get_key',
 1264                          mock.Mock(return_value=key_data))
 1265         self.mock_object(self._manager.compute_api, 'server_create',
 1266                          mock.Mock(return_value=server_create))
 1267         self.mock_object(self._manager.compute_api, 'server_get',
 1268                          mock.Mock(return_value=server_get))
 1269 
 1270         self.assertRaises(exception.ManilaException,
 1271                           self._manager._create_service_instance,
 1272                           self._manager.admin_context, instance_name,
 1273                           network_info)
 1274 
 1275     def test___create_service_instance_failed_to_build(self):
 1276         server_create = dict(id='fakeid', status='CREATING', networks=dict())
 1277         service_image_id = 'fake_service_image_id'
 1278         key_data = 'fake_key_name', 'fake_key_path'
 1279         instance_name = 'fake_instance_name'
 1280         network_info = dict()
 1281         network_data = dict(
 1282             nics=['fake_nic1', 'fake_nic2'],
 1283             router_id='fake_router_id', subnet_id='fake_subnet_id')
 1284         self.mock_object(self._manager.network_helper, 'setup_network',
 1285                          mock.Mock(return_value=network_data))
 1286         self.mock_object(self._manager, '_get_service_image',
 1287                          mock.Mock(return_value=service_image_id))
 1288         self.mock_object(self._manager, '_get_key',
 1289                          mock.Mock(return_value=key_data))
 1290         self.mock_object(self._manager.compute_api, 'server_create',
 1291                          mock.Mock(return_value=server_create))
 1292         self.mock_object(
 1293             self._manager, 'wait_for_instance_to_be_active',
 1294             mock.Mock(side_effect=exception.ServiceInstanceException))
 1295 
 1296         try:
 1297             self._manager._create_service_instance(
 1298                 self._manager.admin_context, instance_name, network_info)
 1299         except exception.ServiceInstanceException as e:
 1300             self.assertEqual(
 1301                 dict(server_details=dict(subnet_id=network_data['subnet_id'],
 1302                                          router_id=network_data['router_id'],
 1303                                          instance_id=server_create['id'])),
 1304                 e.detail_data)
 1305         else:
 1306             raise exception.ManilaException('Expected error was not raised.')
 1307 
 1308         self._manager.network_helper.setup_network.assert_called_once_with(
 1309             network_info)
 1310         self._manager._get_service_image.assert_called_once_with(
 1311             self._manager.admin_context)
 1312         self._manager._get_key.assert_called_once_with(
 1313             self._manager.admin_context)
 1314         self._manager.compute_api.server_create.assert_called_once_with(
 1315             self._manager.admin_context, name=instance_name,
 1316             image=service_image_id, flavor=100,
 1317             key_name=key_data[0], nics=network_data['nics'],
 1318             availability_zone=service_instance.CONF.storage_availability_zone)
 1319 
 1320     @ddt.data(
 1321         dict(name=None, path=None),
 1322         dict(name=None, path='/tmp'))
 1323     @ddt.unpack
 1324     def test__create_service_instance_no_key_and_no_path(self, name, path):
 1325         key_data = name, path
 1326         self.mock_object(self._manager, '_get_service_image')
 1327         self.mock_object(self._manager, '_get_key',
 1328                          mock.Mock(return_value=key_data))
 1329 
 1330         self.assertRaises(
 1331             exception.ServiceInstanceException,
 1332             self._manager._create_service_instance,
 1333             self._manager.admin_context, 'fake_instance_name', dict())
 1334 
 1335         self._manager._get_service_image.assert_called_once_with(
 1336             self._manager.admin_context)
 1337         self._manager._get_key.assert_called_once_with(
 1338             self._manager.admin_context)
 1339 
 1340     @mock.patch('time.sleep')
 1341     @mock.patch('time.time')
 1342     def _test_wait_for_instance(self, mock_time, mock_sleep,
 1343                                 server_get_side_eff=None,
 1344                                 expected_try_count=1,
 1345                                 expected_sleep_count=0,
 1346                                 expected_ret_val=None,
 1347                                 expected_exc=None):
 1348         mock_server_get = mock.Mock(side_effect=server_get_side_eff)
 1349         self.mock_object(self._manager.compute_api, 'server_get',
 1350                          mock_server_get)
 1351 
 1352         self.fake_time = 0
 1353 
 1354         def fake_time():
 1355             return self.fake_time
 1356 
 1357         def fake_sleep(sleep_time):
 1358             self.fake_time += sleep_time
 1359 
 1360         # Note(lpetrut): LOG methods can call time.time
 1361         mock_time.side_effect = fake_time
 1362         mock_sleep.side_effect = fake_sleep
 1363         timeout = 3
 1364 
 1365         if expected_exc:
 1366             self.assertRaises(
 1367                 expected_exc,
 1368                 self._manager.wait_for_instance_to_be_active,
 1369                 instance_id=mock.sentinel.instance_id,
 1370                 timeout=timeout)
 1371         else:
 1372             instance = self._manager.wait_for_instance_to_be_active(
 1373                 instance_id=mock.sentinel.instance_id,
 1374                 timeout=timeout)
 1375             self.assertEqual(expected_ret_val, instance)
 1376 
 1377         mock_server_get.assert_has_calls(
 1378             [mock.call(self._manager.admin_context,
 1379                        mock.sentinel.instance_id)] * expected_try_count)
 1380         mock_sleep.assert_has_calls([mock.call(1)] * expected_sleep_count)
 1381 
 1382     def test_wait_for_instance_timeout(self):
 1383         server_get_side_eff = [
 1384             exception.InstanceNotFound(
 1385                 instance_id=mock.sentinel.instance_id),
 1386             {'status': 'BUILDING'},
 1387             {'status': 'ACTIVE'}]
 1388         # Note that in this case, although the status is active, the
 1389         # 'networks' field is missing.
 1390         self._test_wait_for_instance(  # pylint: disable=no-value-for-parameter
 1391             server_get_side_eff=server_get_side_eff,
 1392             expected_exc=exception.ServiceInstanceException,
 1393             expected_try_count=3,
 1394             expected_sleep_count=3)
 1395 
 1396     def test_wait_for_instance_error_state(self):
 1397         mock_instance = {'status': 'ERROR'}
 1398         self._test_wait_for_instance(  # pylint: disable=no-value-for-parameter
 1399             server_get_side_eff=[mock_instance],
 1400             expected_exc=exception.ServiceInstanceException,
 1401             expected_try_count=1)
 1402 
 1403     def test_wait_for_instance_available(self):
 1404         mock_instance = {'status': 'ACTIVE',
 1405                          'networks': mock.sentinel.networks}
 1406         self._test_wait_for_instance(  # pylint: disable=no-value-for-parameter
 1407             server_get_side_eff=[mock_instance],
 1408             expected_try_count=1,
 1409             expected_ret_val=mock_instance)
 1410 
 1411     def test_reboot_server(self):
 1412         fake_server = {'instance_id': mock.sentinel.instance_id}
 1413         soft_reboot = True
 1414 
 1415         mock_reboot = mock.Mock()
 1416         self.mock_object(self._manager.compute_api, 'server_reboot',
 1417                          mock_reboot)
 1418 
 1419         self._manager.reboot_server(fake_server, soft_reboot)
 1420 
 1421         mock_reboot.assert_called_once_with(self._manager.admin_context,
 1422                                             fake_server['instance_id'],
 1423                                             soft_reboot)
 1424 
 1425 
 1426 class BaseNetworkHelperTestCase(test.TestCase):
 1427     """Tests Base network helper for service instance."""
 1428 
 1429     def test_instantiate_valid(self):
 1430         class FakeNetworkHelper(service_instance.BaseNetworkhelper):
 1431             @property
 1432             def NAME(self):
 1433                 return 'fake_NAME'
 1434 
 1435             def __init__(self, service_instance_manager):
 1436                 self.fake_init = 'fake_init_value'
 1437 
 1438             def get_network_name(self, network_info):
 1439                 return 'fake_network_name'
 1440 
 1441             def setup_connectivity_with_service_instances(self):
 1442                 return 'fake_setup_connectivity_with_service_instances'
 1443 
 1444             def setup_network(self, network_info):
 1445                 return 'fake_setup_network'
 1446 
 1447             def teardown_network(self, server_details):
 1448                 return 'fake_teardown_network'
 1449 
 1450         instance = FakeNetworkHelper('fake')
 1451 
 1452         attrs = [
 1453             'fake_init', 'NAME', 'get_network_name', 'teardown_network',
 1454             'setup_connectivity_with_service_instances', 'setup_network',
 1455         ]
 1456         for attr in attrs:
 1457             self.assertTrue(hasattr(instance, attr))
 1458         self.assertEqual('fake_init_value', instance.fake_init)
 1459         self.assertEqual('fake_NAME', instance.NAME)
 1460         self.assertEqual(
 1461             'fake_network_name', instance.get_network_name('fake'))
 1462         self.assertEqual(
 1463             'fake_setup_connectivity_with_service_instances',
 1464             instance.setup_connectivity_with_service_instances())
 1465         self.assertEqual('fake_setup_network', instance.setup_network('fake'))
 1466         self.assertEqual(
 1467             'fake_teardown_network', instance.teardown_network('fake'))
 1468 
 1469     def test_instantiate_invalid(self):
 1470         self.assertRaises(
 1471             TypeError, service_instance.BaseNetworkhelper, 'fake')
 1472 
 1473 
 1474 @ddt.ddt
 1475 class NeutronNetworkHelperTestCase(test.TestCase):
 1476     """Tests Neutron network helper for service instance."""
 1477 
 1478     def setUp(self):
 1479         super(NeutronNetworkHelperTestCase, self).setUp()
 1480         self.mock_object(importutils, 'import_class')
 1481         self.fake_manager = FakeServiceInstance()
 1482 
 1483     def _init_neutron_network_plugin(self):
 1484         self.mock_object(
 1485             service_instance.NeutronNetworkHelper, '_get_service_network_id',
 1486             mock.Mock(return_value='fake_service_network_id'))
 1487         return service_instance.NeutronNetworkHelper(self.fake_manager)
 1488 
 1489     def test_init_neutron_network_plugin(self):
 1490         instance = self._init_neutron_network_plugin()
 1491         self.assertEqual(service_instance.NEUTRON_NAME, instance.NAME)
 1492         attrs = [
 1493             'neutron_api', 'vif_driver', 'service_network_id',
 1494             'connect_share_server_to_tenant_network', 'get_config_option']
 1495         for attr in attrs:
 1496             self.assertTrue(hasattr(instance, attr), "No attr '%s'" % attr)
 1497         (service_instance.NeutronNetworkHelper._get_service_network_id.
 1498             assert_called_once_with())
 1499         self.assertEqual('DEFAULT', instance.neutron_api.config_group_name)
 1500 
 1501     def test_init_neutron_network_plugin_with_driver_config_group(self):
 1502         self.fake_manager.driver_config = mock.Mock()
 1503         self.fake_manager.driver_config.config_group = (
 1504             'fake_config_group')
 1505         self.fake_manager.driver_config.network_config_group = None
 1506         instance = self._init_neutron_network_plugin()
 1507         self.assertEqual('fake_config_group',
 1508                          instance.neutron_api.config_group_name)
 1509 
 1510     def test_init_neutron_network_plugin_with_network_config_group(self):
 1511         self.fake_manager.driver_config = mock.Mock()
 1512         self.fake_manager.driver_config.config_group = (
 1513             "fake_config_group")
 1514         self.fake_manager.driver_config.network_config_group = (
 1515             "fake_network_config_group")
 1516         instance = self._init_neutron_network_plugin()
 1517         self.assertEqual('fake_network_config_group',
 1518                          instance.neutron_api.config_group_name)
 1519 
 1520     def test_admin_project_id(self):
 1521         instance = self._init_neutron_network_plugin()
 1522         admin_project_id = 'fake_admin_project_id'
 1523         self.mock_class('manila.network.neutron.api.API', mock.Mock())
 1524         instance.neutron_api.admin_project_id = admin_project_id
 1525         self.assertEqual(admin_project_id, instance.admin_project_id)
 1526 
 1527     def test_get_network_name(self):
 1528         network_info = dict(neutron_net_id='fake_neutron_net_id')
 1529         network = dict(name='fake_network_name')
 1530         instance = self._init_neutron_network_plugin()
 1531         self.mock_object(
 1532             instance.neutron_api, 'get_network',
 1533             mock.Mock(return_value=network))
 1534 
 1535         result = instance.get_network_name(network_info)
 1536 
 1537         self.assertEqual(network['name'], result)
 1538         instance.neutron_api.get_network.assert_called_once_with(
 1539             network_info['neutron_net_id'])
 1540 
 1541     def test_get_service_network_id_none_exist(self):
 1542         service_network_name = fake_get_config_option('service_network_name')
 1543         network = dict(id='fake_network_id')
 1544         admin_project_id = 'fake_admin_project_id'
 1545         self.mock_object(
 1546             service_instance.neutron.API, 'get_all_admin_project_networks',
 1547             mock.Mock(return_value=[]))
 1548         self.mock_object(
 1549             service_instance.neutron.API, 'admin_project_id',
 1550             mock.Mock(return_value=admin_project_id))
 1551         self.mock_object(
 1552             service_instance.neutron.API, 'network_create',
 1553             mock.Mock(return_value=network))
 1554         instance = service_instance.NeutronNetworkHelper(self.fake_manager)
 1555 
 1556         result = instance._get_service_network_id()
 1557 
 1558         self.assertEqual(network['id'], result)
 1559         self.assertTrue(service_instance.neutron.API.
 1560                         get_all_admin_project_networks.called)
 1561         service_instance.neutron.API.network_create.assert_has_calls([
 1562             mock.call(instance.admin_project_id, service_network_name)])
 1563 
 1564     def test_get_service_network_id_one_exist(self):
 1565         service_network_name = fake_get_config_option('service_network_name')
 1566         network = dict(id='fake_network_id', name=service_network_name)
 1567         admin_project_id = 'fake_admin_project_id'
 1568         self.mock_object(
 1569             service_instance.neutron.API, 'get_all_admin_project_networks',
 1570             mock.Mock(return_value=[network]))
 1571         self.mock_object(
 1572             service_instance.neutron.API, 'admin_project_id',
 1573             mock.Mock(return_value=admin_project_id))
 1574         instance = service_instance.NeutronNetworkHelper(self.fake_manager)
 1575 
 1576         result = instance._get_service_network_id()
 1577 
 1578         self.assertEqual(network['id'], result)
 1579         self.assertTrue(service_instance.neutron.API.
 1580                         get_all_admin_project_networks.called)
 1581 
 1582     def test_get_service_network_id_two_exist(self):
 1583         service_network_name = fake_get_config_option('service_network_name')
 1584         network = dict(id='fake_network_id', name=service_network_name)
 1585         self.mock_object(
 1586             service_instance.neutron.API, 'get_all_admin_project_networks',
 1587             mock.Mock(return_value=[network, network]))
 1588 
 1589         helper = service_instance.NeutronNetworkHelper(self.fake_manager)
 1590         self.assertRaises(exception.ManilaException,
 1591                           lambda: helper.service_network_id)
 1592 
 1593         (service_instance.neutron.API.get_all_admin_project_networks.
 1594             assert_has_calls([mock.call()]))
 1595 
 1596     @ddt.data(dict(), dict(subnet_id='foo'), dict(router_id='bar'))
 1597     def test_teardown_network_no_service_data(self, server_details):
 1598         instance = self._init_neutron_network_plugin()
 1599         self.mock_object(
 1600             service_instance.neutron.API, 'router_remove_interface')
 1601 
 1602         instance.teardown_network(server_details)
 1603 
 1604         self.assertFalse(
 1605             service_instance.neutron.API.router_remove_interface.called)
 1606 
 1607     @ddt.data(
 1608         *[dict(server_details=sd, fail=f) for f in (True, False)
 1609             for sd in (dict(service_port_id='fake_service_port_id'),
 1610                        dict(public_port_id='fake_public_port_id'),
 1611                        dict(service_port_id='fake_service_port_id',
 1612                             public_port_id='fake_public_port_id'))]
 1613     )
 1614     @ddt.unpack
 1615     def test_teardown_network_with_ports(self, server_details, fail):
 1616         instance = self._init_neutron_network_plugin()
 1617         self.mock_object(
 1618             service_instance.neutron.API, 'router_remove_interface')
 1619         if fail:
 1620             delete_port_mock = mock.Mock(
 1621                 side_effect=exception.NetworkException(code=404))
 1622         else:
 1623             delete_port_mock = mock.Mock()
 1624         self.mock_object(instance.neutron_api, 'delete_port', delete_port_mock)
 1625         self.mock_object(service_instance.LOG, 'debug')
 1626 
 1627         instance.teardown_network(server_details)
 1628 
 1629         self.assertFalse(instance.neutron_api.router_remove_interface.called)
 1630         self.assertEqual(
 1631             len(server_details),
 1632             len(instance.neutron_api.delete_port.mock_calls))
 1633         for k, v in server_details.items():
 1634             self.assertIn(
 1635                 mock.call(v), instance.neutron_api.delete_port.mock_calls)
 1636         if fail:
 1637             service_instance.LOG.debug.assert_has_calls([
 1638                 mock.call(mock.ANY, mock.ANY) for sd in server_details
 1639             ])
 1640         else:
 1641             service_instance.LOG.debug.assert_has_calls([])
 1642 
 1643     @ddt.data(
 1644         dict(service_port_id='fake_service_port_id'),
 1645         dict(public_port_id='fake_public_port_id'),
 1646         dict(service_port_id='fake_service_port_id',
 1647              public_port_id='fake_public_port_id'),
 1648     )
 1649     def test_teardown_network_with_ports_unhandled_exception(self,
 1650                                                              server_details):
 1651         instance = self._init_neutron_network_plugin()
 1652         self.mock_object(
 1653             service_instance.neutron.API, 'router_remove_interface')
 1654         delete_port_mock = mock.Mock(
 1655             side_effect=exception.NetworkException(code=500))
 1656         self.mock_object(
 1657             service_instance.neutron.API, 'delete_port', delete_port_mock)
 1658         self.mock_object(service_instance.LOG, 'debug')
 1659 
 1660         self.assertRaises(
 1661             exception.NetworkException,
 1662             instance.teardown_network,
 1663             server_details,
 1664         )
 1665 
 1666         self.assertFalse(
 1667             service_instance.neutron.API.router_remove_interface.called)
 1668         service_instance.neutron.API.delete_port.assert_called_once_with(
 1669             mock.ANY)
 1670         service_instance.LOG.debug.assert_has_calls([])
 1671 
 1672     def test_teardown_network_with_wrong_ports(self):
 1673         instance = self._init_neutron_network_plugin()
 1674         self.mock_object(
 1675             service_instance.neutron.API, 'router_remove_interface')
 1676         self.mock_object(
 1677             service_instance.neutron.API, 'delete_port')
 1678         self.mock_object(service_instance.LOG, 'debug')
 1679 
 1680         instance.teardown_network(dict(foo_id='fake_service_port_id'))
 1681 
 1682         service_instance.neutron.API.router_remove_interface.assert_has_calls(
 1683             [])
 1684         service_instance.neutron.API.delete_port.assert_has_calls([])
 1685         service_instance.LOG.debug.assert_has_calls([])
 1686 
 1687     def test_teardown_network_subnet_is_used(self):
 1688         server_details = dict(subnet_id='foo', router_id='bar')
 1689         fake_ports = [
 1690             {'device_id': 'fake_device_id',
 1691              'device_owner': 'compute:foo'},
 1692         ]
 1693         instance = self._init_neutron_network_plugin()
 1694         self.mock_object(
 1695             service_instance.neutron.API, 'router_remove_interface')
 1696         self.mock_object(
 1697             service_instance.neutron.API, 'update_subnet')
 1698         self.mock_object(
 1699             service_instance.neutron.API, 'list_ports',
 1700             mock.Mock(return_value=fake_ports))
 1701 
 1702         instance.teardown_network(server_details)
 1703 
 1704         self.assertFalse(
 1705             service_instance.neutron.API.router_remove_interface.called)
 1706         self.assertFalse(service_instance.neutron.API.update_subnet.called)
 1707         service_instance.neutron.API.list_ports.assert_called_once_with(
 1708             fields=['device_id', 'device_owner'], fixed_ips=['subnet_id=foo'])
 1709 
 1710     def test_teardown_network_subnet_not_used(self):
 1711         server_details = dict(subnet_id='foo', router_id='bar')
 1712         fake_ports = [
 1713             {'device_id': 'fake_device_id',
 1714              'device_owner': 'network:router_interface'},
 1715             {'device_id': 'fake_device_id',
 1716              'device_owner': 'compute'},
 1717             {'device_id': '',
 1718              'device_owner': 'compute'},
 1719         ]
 1720         instance = self._init_neutron_network_plugin()
 1721         self.mock_object(
 1722             service_instance.neutron.API, 'router_remove_interface')
 1723         self.mock_object(
 1724             service_instance.neutron.API, 'update_subnet')
 1725         self.mock_object(
 1726             service_instance.neutron.API, 'list_ports',
 1727             mock.Mock(return_value=fake_ports))
 1728 
 1729         instance.teardown_network(server_details)
 1730 
 1731         (service_instance.neutron.API.router_remove_interface.
 1732             assert_called_once_with('bar', 'foo'))
 1733         (service_instance.neutron.API.update_subnet.
 1734             assert_called_once_with('foo', ''))
 1735         service_instance.neutron.API.list_ports.assert_called_once_with(
 1736             fields=['device_id', 'device_owner'], fixed_ips=['subnet_id=foo'])
 1737 
 1738     def test_teardown_network_subnet_not_used_and_get_error_404(self):
 1739         server_details = dict(subnet_id='foo', router_id='bar')
 1740         fake_ports = [
 1741             {'device_id': 'fake_device_id',
 1742              'device_owner': 'fake'},
 1743         ]
 1744         instance = self._init_neutron_network_plugin()
 1745         self.mock_object(
 1746             service_instance.neutron.API, 'router_remove_interface',
 1747             mock.Mock(side_effect=exception.NetworkException(code=404)))
 1748         self.mock_object(
 1749             service_instance.neutron.API, 'update_subnet')
 1750         self.mock_object(
 1751             service_instance.neutron.API, 'list_ports',
 1752             mock.Mock(return_value=fake_ports))
 1753 
 1754         instance.teardown_network(server_details)
 1755 
 1756         (service_instance.neutron.API.router_remove_interface.
 1757             assert_called_once_with('bar', 'foo'))
 1758         (service_instance.neutron.API.update_subnet.
 1759             assert_called_once_with('foo', ''))
 1760         service_instance.neutron.API.list_ports.assert_called_once_with(
 1761             fields=['device_id', 'device_owner'], fixed_ips=['subnet_id=foo'])
 1762 
 1763     def test_teardown_network_subnet_not_used_get_unhandled_error(self):
 1764         server_details = dict(subnet_id='foo', router_id='bar')
 1765         fake_ports = [
 1766             {'device_id': 'fake_device_id',
 1767              'device_owner': 'fake'},
 1768         ]
 1769         instance = self._init_neutron_network_plugin()
 1770         self.mock_object(
 1771             service_instance.neutron.API, 'router_remove_interface',
 1772             mock.Mock(side_effect=exception.NetworkException(code=500)))
 1773         self.mock_object(
 1774             service_instance.neutron.API, 'update_subnet')
 1775         self.mock_object(
 1776             service_instance.neutron.API, 'list_ports',
 1777             mock.Mock(return_value=fake_ports))
 1778 
 1779         self.assertRaises(
 1780             exception.NetworkException,
 1781             instance.teardown_network, server_details)
 1782 
 1783         (service_instance.neutron.API.router_remove_interface.
 1784             assert_called_once_with('bar', 'foo'))
 1785         self.assertFalse(service_instance.neutron.API.update_subnet.called)
 1786         service_instance.neutron.API.list_ports.assert_called_once_with(
 1787             fields=['device_id', 'device_owner'], fixed_ips=['subnet_id=foo'])
 1788 
 1789     def test_setup_network_and_connect_share_server_to_tenant_net(self):
 1790         def fake_create_port(*aargs, **kwargs):
 1791             if aargs[1] == 'fake_service_network_id':
 1792                 return self.service_port
 1793             elif aargs[1] == 'fake_tenant_network_id':
 1794                 return self.public_port
 1795             else:
 1796                 raise exception.ManilaException('Got unexpected data')
 1797 
 1798         admin_project_id = 'fake_admin_project_id'
 1799         network_info = dict(
 1800             neutron_net_id='fake_tenant_network_id',
 1801             neutron_subnet_id='fake_tenant_subnet_id')
 1802         cidr = '13.0.0.0/24'
 1803         self.service_port = dict(
 1804             id='fake_service_port_id',
 1805             fixed_ips=[dict(ip_address='fake_service_port_ip_address')])
 1806         self.public_port = dict(
 1807             id='fake_tenant_port_id',
 1808             fixed_ips=[dict(ip_address='fake_public_port_ip_address')])
 1809         service_subnet = dict(id='fake_service_subnet')
 1810         instance = self._init_neutron_network_plugin()
 1811         instance.connect_share_server_to_tenant_network = True
 1812         self.mock_object(instance, '_get_service_network_id',
 1813                          mock.Mock(return_value='fake_service_network_id'))
 1814         self.mock_object(
 1815             service_instance.neutron.API, 'admin_project_id',
 1816             mock.Mock(return_value=admin_project_id))
 1817         self.mock_object(
 1818             service_instance.neutron.API, 'create_port',
 1819             mock.Mock(side_effect=fake_create_port))
 1820         self.mock_object(
 1821             service_instance.neutron.API, 'subnet_create',
 1822             mock.Mock(return_value=service_subnet))
 1823         self.mock_object(
 1824             instance, 'setup_connectivity_with_service_instances',
 1825             mock.Mock(return_value=service_subnet))
 1826         self.mock_object(
 1827             instance, '_get_cidr_for_subnet', mock.Mock(return_value=cidr))
 1828         self.mock_object(
 1829             instance, '_get_service_subnet', mock.Mock(return_value=None))
 1830         expected = {
 1831             'ip_address': self.public_port['fixed_ips'][0]['ip_address'],
 1832             'public_port': self.public_port,
 1833             'service_port': self.service_port,
 1834             'service_subnet': service_subnet,
 1835             'ports': [self.public_port, self.service_port],
 1836             'nics': [{'port-id': self.public_port['id']},
 1837                      {'port-id': self.service_port['id']}]}
 1838 
 1839         result = instance.setup_network(network_info)
 1840 
 1841         self.assertEqual(expected, result)
 1842         (instance.setup_connectivity_with_service_instances.
 1843             assert_called_once_with())
 1844         instance._get_service_subnet.assert_called_once_with(mock.ANY)
 1845         instance._get_cidr_for_subnet.assert_called_once_with()
 1846         self.assertTrue(service_instance.neutron.API.subnet_create.called)
 1847         self.assertTrue(service_instance.neutron.API.create_port.called)
 1848 
 1849     def test_setup_network_and_connect_share_server_to_tenant_net_admin(self):
 1850         def fake_create_port(*aargs, **kwargs):
 1851             if aargs[1] == 'fake_admin_network_id':
 1852                 return self.admin_port
 1853             elif aargs[1] == 'fake_tenant_network_id':
 1854                 return self.public_port
 1855             else:
 1856                 raise exception.ManilaException('Got unexpected data')
 1857 
 1858         admin_project_id = 'fake_admin_project_id'
 1859         network_info = {
 1860             'neutron_net_id': 'fake_tenant_network_id',
 1861             'neutron_subnet_id': 'fake_tenant_subnet_id'}
 1862         self.admin_port = {
 1863             'id': 'fake_admin_port_id',
 1864             'fixed_ips': [{'ip_address': 'fake_admin_port_ip_address'}]}
 1865         self.public_port = {
 1866             'id': 'fake_tenant_port_id',
 1867             'fixed_ips': [{'ip_address': 'fake_public_port_ip_address'}]}
 1868         instance = self._init_neutron_network_plugin()
 1869         instance.use_admin_port = True
 1870         instance.use_service_network = False
 1871         instance.admin_network_id = 'fake_admin_network_id'
 1872         instance.admin_subnet_id = 'fake_admin_subnet_id'
 1873         instance.connect_share_server_to_tenant_network = True
 1874         self.mock_object(
 1875             service_instance.neutron.API, 'admin_project_id',
 1876             mock.Mock(return_value=admin_project_id))
 1877         self.mock_object(
 1878             service_instance.neutron.API, 'create_port',
 1879             mock.Mock(side_effect=fake_create_port))
 1880         self.mock_object(
 1881             instance, 'setup_connectivity_with_service_instances')
 1882         expected = {
 1883             'ip_address': self.public_port['fixed_ips'][0]['ip_address'],
 1884             'public_port': self.public_port,
 1885             'admin_port': self.admin_port,
 1886             'ports': [self.public_port, self.admin_port],
 1887             'nics': [{'port-id': self.public_port['id']},
 1888                      {'port-id': self.admin_port['id']}]}
 1889 
 1890         result = instance.setup_network(network_info)
 1891 
 1892         self.assertEqual(expected, result)
 1893         (instance.setup_connectivity_with_service_instances.
 1894             assert_called_once_with())
 1895         self.assertTrue(service_instance.neutron.API.create_port.called)
 1896 
 1897     @ddt.data(None, exception.NetworkException(code=400))
 1898     def test_setup_network_using_router_success(self, return_obj):
 1899         admin_project_id = 'fake_admin_project_id'
 1900         network_info = dict(
 1901             neutron_net_id='fake_tenant_network_id',
 1902             neutron_subnet_id='fake_tenant_subnet_id')
 1903         cidr = '13.0.0.0/24'
 1904         self.admin_port = {
 1905             'id': 'fake_admin_port_id',
 1906             'fixed_ips': [{'ip_address': 'fake_admin_port_ip_address'}]}
 1907         self.service_port = dict(
 1908             id='fake_service_port_id',
 1909             fixed_ips=[dict(ip_address='fake_service_port_ip_address')])
 1910         service_subnet = dict(id='fake_service_subnet')
 1911         instance = self._init_neutron_network_plugin()
 1912         instance.use_admin_port = True
 1913         instance.admin_network_id = 'fake_admin_network_id'
 1914         instance.admin_subnet_id = 'fake_admin_subnet_id'
 1915         instance.connect_share_server_to_tenant_network = False
 1916         self.mock_object(instance, '_get_service_network_id',
 1917                          mock.Mock(return_value='fake_service_network_id'))
 1918         router = dict(id='fake_router_id')
 1919         self.mock_object(
 1920             service_instance.neutron.API, 'admin_project_id',
 1921             mock.Mock(return_value=admin_project_id))
 1922         self.mock_object(
 1923             service_instance.neutron.API, 'create_port',
 1924             mock.Mock(side_effect=[self.service_port, self.admin_port]))
 1925         self.mock_object(
 1926             service_instance.neutron.API, 'subnet_create',
 1927             mock.Mock(return_value=service_subnet))
 1928         self.mock_object(
 1929             instance, '_get_private_router', mock.Mock(return_value=router))
 1930         self.mock_object(
 1931             service_instance.neutron.API, 'router_add_interface',
 1932             mock.Mock(side_effect=return_obj))
 1933         self.mock_object(instance, 'setup_connectivity_with_service_instances')
 1934         self.mock_object(
 1935             instance, '_get_cidr_for_subnet', mock.Mock(return_value=cidr))
 1936         self.mock_object(
 1937             instance, '_get_service_subnet', mock.Mock(return_value=None))
 1938         expected = {
 1939             'ip_address': self.service_port['fixed_ips'][0]['ip_address'],
 1940             'service_port': self.service_port,
 1941             'service_subnet': service_subnet,
 1942             'admin_port': self.admin_port, 'router': router,
 1943             'ports': [self.service_port, self.admin_port],
 1944             'nics': [{'port-id': self.service_port['id']},
 1945                      {'port-id': self.admin_port['id']}]}
 1946 
 1947         result = instance.setup_network(network_info)
 1948 
 1949         self.assertEqual(expected, result)
 1950         (instance.setup_connectivity_with_service_instances.
 1951             assert_called_once_with())
 1952         instance._get_service_subnet.assert_called_once_with(mock.ANY)
 1953         instance._get_cidr_for_subnet.assert_called_once_with()
 1954         self.assertTrue(service_instance.neutron.API.subnet_create.called)
 1955         self.assertTrue(service_instance.neutron.API.create_port.called)
 1956         instance._get_private_router.assert_called_once_with(
 1957             network_info['neutron_net_id'], network_info['neutron_subnet_id'])
 1958         (service_instance.neutron.API.router_add_interface.
 1959             assert_called_once_with(router['id'], service_subnet['id']))
 1960 
 1961     def test_setup_network_using_router_addon_of_interface_failed(self):
 1962         network_info = dict(
 1963             neutron_net_id='fake_tenant_network_id',
 1964             neutron_subnet_id='fake_tenant_subnet_id')
 1965         service_subnet = dict(id='fake_service_subnet')
 1966         instance = self._init_neutron_network_plugin()
 1967         instance.connect_share_server_to_tenant_network = False
 1968         self.mock_object(instance, '_get_service_network_id',
 1969                          mock.Mock(return_value='fake_service_network_id'))
 1970         router = dict(id='fake_router_id')
 1971         self.mock_object(
 1972             instance, '_get_private_router', mock.Mock(return_value=router))
 1973         self.mock_object(
 1974             service_instance.neutron.API, 'router_add_interface',
 1975             mock.Mock(side_effect=exception.NetworkException(code=500)))
 1976         self.mock_object(
 1977             instance, '_get_service_subnet',
 1978             mock.Mock(return_value=service_subnet))
 1979 
 1980         self.assertRaises(
 1981             exception.NetworkException,
 1982             instance.setup_network, network_info)
 1983 
 1984         instance._get_service_subnet.assert_called_once_with(mock.ANY)
 1985         instance._get_private_router.assert_called_once_with(
 1986             network_info['neutron_net_id'], network_info['neutron_subnet_id'])
 1987         (service_instance.neutron.API.router_add_interface.
 1988             assert_called_once_with(router['id'], service_subnet['id']))
 1989 
 1990     def test_setup_network_using_router_connectivity_verification_fail(self):
 1991         admin_project_id = 'fake_admin_project_id'
 1992         network_info = dict(
 1993             neutron_net_id='fake_tenant_network_id',
 1994             neutron_subnet_id='fake_tenant_subnet_id')
 1995         cidr = '13.0.0.0/24'
 1996         self.service_port = dict(
 1997             id='fake_service_port_id',
 1998             fixed_ips=[dict(ip_address='fake_service_port_ip_address')])
 1999         service_subnet = dict(id='fake_service_subnet')
 2000         instance = self._init_neutron_network_plugin()
 2001         instance.connect_share_server_to_tenant_network = False
 2002         self.mock_object(instance, '_get_service_network_id',
 2003                          mock.Mock(return_value='fake_service_network_id'))
 2004         router = dict(id='fake_router_id')
 2005         self.mock_object(
 2006             service_instance.neutron.API, 'admin_project_id',
 2007             mock.Mock(return_value=admin_project_id))
 2008         self.mock_object(
 2009             service_instance.neutron.API, 'create_port',
 2010             mock.Mock(return_value=self.service_port))
 2011         self.mock_object(
 2012             service_instance.neutron.API, 'subnet_create',
 2013             mock.Mock(return_value=service_subnet))
 2014         self.mock_object(service_instance.neutron.API, 'delete_port')
 2015         self.mock_object(
 2016             instance, '_get_private_router', mock.Mock(return_value=router))
 2017         self.mock_object(
 2018             service_instance.neutron.API, 'router_add_interface')
 2019         self.mock_object(
 2020             instance, 'setup_connectivity_with_service_instances',
 2021             mock.Mock(side_effect=exception.ManilaException('Fake')))
 2022         self.mock_object(
 2023             instance, '_get_cidr_for_subnet', mock.Mock(return_value=cidr))
 2024         self.mock_object(
 2025             instance, '_get_service_subnet', mock.Mock(return_value=None))
 2026 
 2027         self.assertRaises(
 2028             exception.ManilaException, instance.setup_network, network_info)
 2029 
 2030         (instance.setup_connectivity_with_service_instances.
 2031             assert_called_once_with())
 2032         instance._get_service_subnet.assert_called_once_with(mock.ANY)
 2033         instance._get_cidr_for_subnet.assert_called_once_with()
 2034         self.assertTrue(service_instance.neutron.API.subnet_create.called)
 2035         self.assertTrue(service_instance.neutron.API.create_port.called)
 2036         instance._get_private_router.assert_called_once_with(
 2037             network_info['neutron_net_id'], network_info['neutron_subnet_id'])
 2038         (service_instance.neutron.API.router_add_interface.
 2039             assert_called_once_with(router['id'], service_subnet['id']))
 2040         service_instance.neutron.API.delete_port.assert_has_calls([
 2041             mock.call(self.service_port['id'])])
 2042 
 2043     def test__get_cidr_for_subnet_success(self):
 2044         expected = (
 2045             fake_get_config_option('service_network_cidr').split('/')[0] +
 2046             '/' + six.text_type(
 2047                 fake_get_config_option('service_network_division_mask')))
 2048         instance = self._init_neutron_network_plugin()
 2049         self.mock_object(
 2050             instance, '_get_all_service_subnets', mock.Mock(return_value=[]))
 2051 
 2052         result = instance._get_cidr_for_subnet()
 2053 
 2054         self.assertEqual(expected, result)
 2055         instance._get_all_service_subnets.assert_called_once_with()
 2056 
 2057     def test__get_cidr_for_subnet_failure(self):
 2058         subnets = []
 2059         serv_cidr = netaddr.IPNetwork(
 2060             fake_get_config_option('service_network_cidr'))
 2061         division_mask = fake_get_config_option('service_network_division_mask')
 2062         for subnet in serv_cidr.subnet(division_mask):
 2063             subnets.append(dict(cidr=six.text_type(subnet.cidr)))
 2064         instance = self._init_neutron_network_plugin()
 2065         self.mock_object(
 2066             instance, '_get_all_service_subnets',
 2067             mock.Mock(return_value=subnets))
 2068 
 2069         self.assertRaises(
 2070             exception.ServiceInstanceException,
 2071             instance._get_cidr_for_subnet)
 2072 
 2073         instance._get_all_service_subnets.assert_called_once_with()
 2074 
 2075     def test_setup_connectivity_with_service_instances(self):
 2076         instance = self._init_neutron_network_plugin()
 2077         instance.use_admin_port = True
 2078         instance.admin_network_id = 'fake_admin_network_id'
 2079         instance.admin_subnet_id = 'fake_admin_subnet_id'
 2080         interface_name_service = 'fake_interface_name_service'
 2081         interface_name_admin = 'fake_interface_name_admin'
 2082         fake_division_mask = fake_get_config_option(
 2083             'service_network_division_mask')
 2084         fake_subnet_service = fake_network.FakeSubnet(
 2085             cidr='10.254.0.0/%s' % fake_division_mask)
 2086         fake_subnet_admin = fake_network.FakeSubnet(id='fake_admin_subnet_id',
 2087                                                     cidr='10.0.0.0/24')
 2088         fake_service_port = fake_network.FakePort(fixed_ips=[
 2089             {'subnet_id': fake_subnet_service['id'],
 2090              'ip_address': '10.254.0.2'}], mac_address='fake_mac_address')
 2091         fake_admin_port = fake_network.FakePort(fixed_ips=[
 2092             {'subnet_id': fake_subnet_admin['id'], 'ip_address': '10.0.0.4'}],
 2093             mac_address='fake_mac_address')
 2094 
 2095         self.mock_object(instance, '_get_service_port',
 2096                          mock.Mock(side_effect=[fake_service_port,
 2097                                                 fake_admin_port]))
 2098         self.mock_object(instance, '_add_fixed_ips_to_service_port',
 2099                          mock.Mock(return_value=fake_service_port))
 2100         self.mock_object(instance.vif_driver, 'get_device_name',
 2101                          mock.Mock(side_effect=[interface_name_service,
 2102                                                 interface_name_admin]))
 2103         self.mock_object(instance.neutron_api, 'get_subnet',
 2104                          mock.Mock(side_effect=[fake_subnet_service,
 2105                                                 fake_subnet_admin,
 2106                                                 fake_subnet_admin]))
 2107         self.mock_object(instance, '_remove_outdated_interfaces')
 2108         self.mock_object(instance.vif_driver, 'plug')
 2109         device_mock = mock.Mock()
 2110         self.mock_object(service_instance.ip_lib, 'IPDevice',
 2111                          mock.Mock(return_value=device_mock))
 2112 
 2113         instance.setup_connectivity_with_service_instances()
 2114 
 2115         instance._get_service_port.assert_has_calls([
 2116             mock.call(instance.service_network_id, None, 'manila-share'),
 2117             mock.call('fake_admin_network_id', 'fake_admin_subnet_id',
 2118                       'manila-admin-share')])
 2119         instance.vif_driver.get_device_name.assert_has_calls([
 2120             mock.call(fake_service_port), mock.call(fake_admin_port)])
 2121         instance.vif_driver.plug.assert_has_calls([
 2122             mock.call(interface_name_service, fake_service_port['id'],
 2123                       fake_service_port['mac_address']),
 2124             mock.call(interface_name_admin, fake_admin_port['id'],
 2125                       fake_admin_port['mac_address'])])
 2126         instance.neutron_api.get_subnet.assert_has_calls([
 2127             mock.call(fake_subnet_service['id']),
 2128             mock.call(fake_subnet_admin['id']),
 2129             mock.call(fake_subnet_admin['id'])])
 2130         instance.vif_driver.init_l3.assert_has_calls([
 2131             mock.call(interface_name_service,
 2132                       ['10.254.0.2/%s' % fake_division_mask]),
 2133             mock.call(interface_name_admin, ['10.0.0.4/24'])])
 2134         service_instance.ip_lib.IPDevice.assert_has_calls([
 2135             mock.call(interface_name_service),
 2136             mock.call(interface_name_admin)])
 2137         device_mock.route.pullup_route.assert_has_calls([
 2138             mock.call(interface_name_service),
 2139             mock.call(interface_name_admin)])
 2140         instance._remove_outdated_interfaces.assert_called_with(device_mock)
 2141 
 2142     def test__get_set_of_device_cidrs(self):
 2143         device = fake_network.FakeDevice('foo')
 2144         expected = set(('1.0.0.0/27', '2.0.0.0/27'))
 2145         instance = self._init_neutron_network_plugin()
 2146 
 2147         result = instance._get_set_of_device_cidrs(device)
 2148 
 2149         self.assertEqual(expected, result)
 2150 
 2151     def test__get_set_of_device_cidrs_exception(self):
 2152         device = fake_network.FakeDevice('foo')
 2153         self.mock_object(device.addr, 'list', mock.Mock(
 2154             side_effect=Exception('foo does not exist')))
 2155         instance = self._init_neutron_network_plugin()
 2156 
 2157         result = instance._get_set_of_device_cidrs(device)
 2158 
 2159         self.assertEqual(set(), result)
 2160 
 2161     def test__remove_outdated_interfaces(self):
 2162         device = fake_network.FakeDevice(
 2163             'foobarquuz', [dict(ip_version=4, cidr='1.0.0.0/27')])
 2164         devices = [fake_network.FakeDevice('foobar')]
 2165         instance = self._init_neutron_network_plugin()
 2166         self.mock_object(instance.vif_driver, 'unplug')
 2167         self.mock_object(
 2168             service_instance.ip_lib.IPWrapper, 'get_devices',
 2169             mock.Mock(return_value=devices))
 2170 
 2171         instance._remove_outdated_interfaces(device)
 2172 
 2173         instance.vif_driver.unplug.assert_called_once_with('foobar')
 2174 
 2175     def test__get_service_port_none_exist(self):
 2176         instance = self._init_neutron_network_plugin()
 2177         admin_project_id = 'fake_admin_project_id'
 2178         fake_port_values = {'device_id': 'manila-share',
 2179                             'binding:host_id': 'fake_host'}
 2180         self.mock_object(
 2181             service_instance.neutron.API, 'admin_project_id',
 2182             mock.Mock(return_value=admin_project_id))
 2183         fake_service_port = fake_network.FakePort(device_id='manila-share')
 2184         self.mock_object(instance.neutron_api, 'list_ports',
 2185                          mock.Mock(return_value=[]))
 2186         self.mock_object(service_instance.socket, 'gethostname',
 2187                          mock.Mock(return_value='fake_host'))
 2188         self.mock_object(instance.neutron_api, 'create_port',
 2189                          mock.Mock(return_value=fake_service_port))
 2190         self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
 2191                          mock.Mock(return_value=fake_service_port))
 2192 
 2193         result = instance._get_service_port(instance.service_network_id,
 2194                                             None, 'manila-share')
 2195 
 2196         instance.neutron_api.list_ports.assert_called_once_with(
 2197             **fake_port_values)
 2198         instance.neutron_api.create_port.assert_called_once_with(
 2199             instance.admin_project_id, instance.service_network_id,
 2200             device_id='manila-share', device_owner='manila:share',
 2201             host_id='fake_host', subnet_id=None, port_security_enabled=False)
 2202         service_instance.socket.gethostname.assert_called_once_with()
 2203         self.assertFalse(instance.neutron_api.update_port_fixed_ips.called)
 2204         self.assertEqual(fake_service_port, result)
 2205 
 2206     def test__get_service_port_one_exist_on_same_host(self):
 2207         instance = self._init_neutron_network_plugin()
 2208         fake_port_values = {'device_id': 'manila-share',
 2209                             'binding:host_id': 'fake_host'}
 2210         fake_service_port = fake_network.FakePort(**fake_port_values)
 2211         self.mock_object(service_instance.socket, 'gethostname',
 2212                          mock.Mock(return_value='fake_host'))
 2213         self.mock_object(instance.neutron_api, 'list_ports',
 2214                          mock.Mock(return_value=[fake_service_port]))
 2215         self.mock_object(instance.neutron_api, 'create_port',
 2216                          mock.Mock(return_value=fake_service_port))
 2217         self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
 2218                          mock.Mock(return_value=fake_service_port))
 2219 
 2220         result = instance._get_service_port(instance.service_network_id,
 2221                                             None, 'manila-share')
 2222 
 2223         instance.neutron_api.list_ports.assert_called_once_with(
 2224             **fake_port_values)
 2225         self.assertFalse(instance.neutron_api.create_port.called)
 2226         self.assertFalse(instance.neutron_api.update_port_fixed_ips.called)
 2227         self.assertEqual(fake_service_port, result)
 2228 
 2229     def test__get_service_port_one_exist_on_different_host(self):
 2230         instance = self._init_neutron_network_plugin()
 2231         admin_project_id = 'fake_admin_project_id'
 2232         fake_port = {'device_id': 'manila-share',
 2233                      'binding:host_id': 'fake_host'}
 2234         self.mock_object(
 2235             service_instance.neutron.API, 'admin_project_id',
 2236             mock.Mock(return_value=admin_project_id))
 2237         fake_service_port = fake_network.FakePort(**fake_port)
 2238         self.mock_object(instance.neutron_api, 'list_ports',
 2239                          mock.Mock(return_value=[]))
 2240         self.mock_object(service_instance.socket, 'gethostname',
 2241                          mock.Mock(return_value='fake_host'))
 2242         self.mock_object(instance.neutron_api, 'create_port',
 2243                          mock.Mock(return_value=fake_service_port))
 2244         self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
 2245                          mock.Mock(return_value=fake_service_port))
 2246 
 2247         result = instance._get_service_port(instance.service_network_id,
 2248                                             None, 'manila-share')
 2249 
 2250         instance.neutron_api.list_ports.assert_called_once_with(
 2251             **fake_port)
 2252         instance.neutron_api.create_port.assert_called_once_with(
 2253             instance.admin_project_id, instance.service_network_id,
 2254             device_id='manila-share', device_owner='manila:share',
 2255             host_id='fake_host', subnet_id=None, port_security_enabled=False)
 2256         service_instance.socket.gethostname.assert_called_once_with()
 2257         self.assertFalse(instance.neutron_api.update_port_fixed_ips.called)
 2258         self.assertEqual(fake_service_port, result)
 2259 
 2260     def test__get_service_port_two_exist_on_same_host(self):
 2261         instance = self._init_neutron_network_plugin()
 2262         fake_service_port = fake_network.FakePort(**{
 2263             'device_id': 'manila-share', 'binding:host_id': 'fake_host'})
 2264         self.mock_object(
 2265             instance.neutron_api, 'list_ports',
 2266             mock.Mock(return_value=[fake_service_port, fake_service_port]))
 2267         self.mock_object(service_instance.socket, 'gethostname',
 2268                          mock.Mock(return_value='fake_host'))
 2269         self.mock_object(instance.neutron_api, 'create_port',
 2270                          mock.Mock(return_value=fake_service_port))
 2271         self.assertRaises(
 2272             exception.ServiceInstanceException, instance._get_service_port,
 2273             instance.service_network_id, None, 'manila-share')
 2274         self.assertFalse(instance.neutron_api.create_port.called)
 2275 
 2276     def test__add_fixed_ips_to_service_port(self):
 2277         ip_address1 = '13.0.0.13'
 2278         subnet_id1 = 'fake_subnet_id1'
 2279         subnet_id2 = 'fake_subnet_id2'
 2280         port = dict(id='fooport', fixed_ips=[dict(
 2281             subnet_id=subnet_id1, ip_address=ip_address1)])
 2282         expected = mock.Mock()
 2283         network = dict(subnets=[subnet_id1, subnet_id2])
 2284         instance = self._init_neutron_network_plugin()
 2285         self.mock_object(instance.neutron_api, 'get_network',
 2286                          mock.Mock(return_value=network))
 2287         self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
 2288                          mock.Mock(return_value=expected))
 2289 
 2290         result = instance._add_fixed_ips_to_service_port(port)
 2291 
 2292         self.assertEqual(expected, result)
 2293         instance.neutron_api.get_network.assert_called_once_with(
 2294             instance.service_network_id)
 2295         instance.neutron_api.update_port_fixed_ips.assert_called_once_with(
 2296             port['id'], dict(fixed_ips=[
 2297                 dict(subnet_id=subnet_id1, ip_address=ip_address1),
 2298                 dict(subnet_id=subnet_id2)]))
 2299 
 2300     def test__get_private_router_success(self):
 2301         instance = self._init_neutron_network_plugin()
 2302         network = fake_network.FakeNetwork()
 2303         subnet = fake_network.FakeSubnet(gateway_ip='fake_ip')
 2304         router = fake_network.FakeRouter(id='fake_router_id')
 2305         port = fake_network.FakePort(fixed_ips=[
 2306             dict(subnet_id=subnet['id'],
 2307                  ip_address=subnet['gateway_ip'])],
 2308             device_id=router['id'])
 2309         self.mock_object(instance.neutron_api, 'get_subnet',
 2310                          mock.Mock(return_value=subnet))
 2311         self.mock_object(instance.neutron_api, 'list_ports',
 2312                          mock.Mock(return_value=[port]))
 2313         self.mock_object(instance.neutron_api, 'show_router',
 2314                          mock.Mock(return_value=router))
 2315 
 2316         result = instance._get_private_router(network['id'], subnet['id'])
 2317 
 2318         self.assertEqual(router, result)
 2319         instance.neutron_api.get_subnet.assert_called_once_with(subnet['id'])
 2320         instance.neutron_api.list_ports.assert_called_once_with(
 2321             network_id=network['id'])
 2322         instance.neutron_api.show_router.assert_called_once_with(router['id'])
 2323 
 2324     def test__get_private_router_no_gateway(self):
 2325         instance = self._init_neutron_network_plugin()
 2326         subnet = fake_network.FakeSubnet(gateway_ip='')
 2327         self.mock_object(instance.neutron_api, 'get_subnet',
 2328                          mock.Mock(return_value=subnet))
 2329 
 2330         self.assertRaises(
 2331             exception.ServiceInstanceException,
 2332             instance._get_private_router, 'fake_network_id', subnet['id'])
 2333 
 2334         instance.neutron_api.get_subnet.assert_called_once_with(
 2335             subnet['id'])
 2336 
 2337     def test__get_private_router_subnet_is_not_attached_to_the_router(self):
 2338         instance = self._init_neutron_network_plugin()
 2339         network_id = 'fake_network_id'
 2340         subnet = fake_network.FakeSubnet(gateway_ip='fake_ip')
 2341         self.mock_object(instance.neutron_api, 'get_subnet',
 2342                          mock.Mock(return_value=subnet))
 2343         self.mock_object(instance.neutron_api, 'list_ports',
 2344                          mock.Mock(return_value=[]))
 2345 
 2346         self.assertRaises(
 2347             exception.ServiceInstanceException,
 2348             instance._get_private_router, network_id, subnet['id'])
 2349 
 2350         instance.neutron_api.get_subnet.assert_called_once_with(
 2351             subnet['id'])
 2352         instance.neutron_api.list_ports.assert_called_once_with(
 2353             network_id=network_id)
 2354 
 2355     def test__get_service_subnet_none_found(self):
 2356         subnet_name = 'fake_subnet_name'
 2357         instance = self._init_neutron_network_plugin()
 2358         self.mock_object(instance, '_get_all_service_subnets',
 2359                          mock.Mock(return_value=[]))
 2360 
 2361         result = instance._get_service_subnet(subnet_name)
 2362 
 2363         self.assertIsNone(result)
 2364         instance._get_all_service_subnets.assert_called_once_with()
 2365 
 2366     def test__get_service_subnet_unused_found(self):
 2367         subnet_name = 'fake_subnet_name'
 2368         subnets = [fake_network.FakeSubnet(id='foo', name=''),
 2369                    fake_network.FakeSubnet(id='bar', name='quuz')]
 2370         instance = self._init_neutron_network_plugin()
 2371         self.mock_object(instance.neutron_api, 'update_subnet')
 2372         self.mock_object(instance, '_get_all_service_subnets',
 2373                          mock.Mock(return_value=subnets))
 2374 
 2375         result = instance._get_service_subnet(subnet_name)
 2376 
 2377         self.assertEqual(subnets[0], result)
 2378         instance._get_all_service_subnets.assert_called_once_with()
 2379         instance.neutron_api.update_subnet.assert_called_once_with(
 2380             subnets[0]['id'], subnet_name)
 2381 
 2382     def test__get_service_subnet_one_found(self):
 2383         subnet_name = 'fake_subnet_name'
 2384         subnets = [fake_network.FakeSubnet(id='foo', name='quuz'),
 2385                    fake_network.FakeSubnet(id='bar', name=subnet_name)]
 2386         instance = self._init_neutron_network_plugin()
 2387         self.mock_object(instance, '_get_all_service_subnets',
 2388                          mock.Mock(return_value=subnets))
 2389 
 2390         result = instance._get_service_subnet(subnet_name)
 2391 
 2392         self.assertEqual(subnets[1], result)
 2393         instance._get_all_service_subnets.assert_called_once_with()
 2394 
 2395     def test__get_service_subnet_two_found(self):
 2396         subnet_name = 'fake_subnet_name'
 2397         subnets = [fake_network.FakeSubnet(id='foo', name=subnet_name),
 2398                    fake_network.FakeSubnet(id='bar', name=subnet_name)]
 2399         instance = self._init_neutron_network_plugin()
 2400         self.mock_object(instance, '_get_all_service_subnets',
 2401                          mock.Mock(return_value=subnets))
 2402 
 2403         self.assertRaises(
 2404             exception.ServiceInstanceException,
 2405             instance._get_service_subnet, subnet_name)
 2406 
 2407         instance._get_all_service_subnets.assert_called_once_with()
 2408 
 2409     def test__get_all_service_subnets(self):
 2410         subnet_id1 = 'fake_subnet_id1'
 2411         subnet_id2 = 'fake_subnet_id2'
 2412         instance = self._init_neutron_network_plugin()
 2413         network = dict(subnets=[subnet_id1, subnet_id2])
 2414         self.mock_object(instance.neutron_api, 'get_subnet',
 2415                          mock.Mock(side_effect=lambda s_id: dict(id=s_id)))
 2416         self.mock_object(instance.neutron_api, 'get_network',
 2417                          mock.Mock(return_value=network))
 2418 
 2419         result = instance._get_all_service_subnets()
 2420 
 2421         self.assertEqual([dict(id=subnet_id1), dict(id=subnet_id2)], result)
 2422         instance.neutron_api.get_network.assert_called_once_with(
 2423             instance.service_network_id)
 2424         instance.neutron_api.get_subnet.assert_has_calls([
 2425             mock.call(subnet_id1), mock.call(subnet_id2)])