OpenStack Compute (Nova)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2236 lines
88KB

  1. # Copyright 2010 United States Government as represented by the
  2. # Administrator of the National Aeronautics and Space Administration.
  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. """Fixtures for Nova tests."""
  17. from __future__ import absolute_import
  18. import collections
  19. from contextlib import contextmanager
  20. import copy
  21. import logging as std_logging
  22. import os
  23. import random
  24. import warnings
  25. import fixtures
  26. import futurist
  27. from keystoneauth1 import adapter as ksa_adap
  28. import mock
  29. from neutronclient.common import exceptions as neutron_client_exc
  30. from openstack import service_description
  31. import os_resource_classes as orc
  32. from oslo_concurrency import lockutils
  33. from oslo_config import cfg
  34. from oslo_db import exception as db_exc
  35. from oslo_log import log as logging
  36. import oslo_messaging as messaging
  37. from oslo_messaging import conffixture as messaging_conffixture
  38. from oslo_privsep import daemon as privsep_daemon
  39. from oslo_serialization import jsonutils
  40. from oslo_utils.fixture import uuidsentinel
  41. from oslo_utils import uuidutils
  42. from requests import adapters
  43. from sqlalchemy import exc as sqla_exc
  44. from wsgi_intercept import interceptor
  45. from nova.api.openstack.compute import tenant_networks
  46. from nova.api.openstack import wsgi_app
  47. from nova.api import wsgi
  48. from nova.compute import multi_cell_list
  49. from nova.compute import rpcapi as compute_rpcapi
  50. from nova import context
  51. from nova.db import migration
  52. from nova.db.sqlalchemy import api as session
  53. from nova import exception
  54. from nova.network import model as network_model
  55. from nova.network.neutronv2 import constants as neutron_constants
  56. from nova import objects
  57. from nova.objects import base as obj_base
  58. from nova.objects import service as service_obj
  59. import nova.privsep
  60. from nova import quota as nova_quota
  61. from nova import rpc
  62. from nova.scheduler import weights
  63. from nova import service
  64. from nova.tests.functional.api import client
  65. from nova.tests.unit import fake_requests
  66. _TRUE_VALUES = ('True', 'true', '1', 'yes')
  67. CONF = cfg.CONF
  68. DB_SCHEMA = {'main': "", 'api': ""}
  69. SESSION_CONFIGURED = False
  70. LOG = logging.getLogger(__name__)
  71. class ServiceFixture(fixtures.Fixture):
  72. """Run a service as a test fixture."""
  73. def __init__(self, name, host=None, cell=None, **kwargs):
  74. name = name
  75. # If not otherwise specified, the host will default to the
  76. # name of the service. Some things like aggregates care that
  77. # this is stable.
  78. host = host or name
  79. kwargs.setdefault('host', host)
  80. kwargs.setdefault('binary', 'nova-%s' % name)
  81. self.cell = cell
  82. self.kwargs = kwargs
  83. def setUp(self):
  84. super(ServiceFixture, self).setUp()
  85. self.ctxt = context.get_admin_context()
  86. if self.cell:
  87. context.set_target_cell(self.ctxt, self.cell)
  88. # NOTE(mikal): we don't have root to manipulate iptables, so just
  89. # zero that bit out.
  90. self.useFixture(fixtures.MockPatch(
  91. 'nova.network.linux_net.IptablesManager._apply'))
  92. with mock.patch('nova.context.get_admin_context',
  93. return_value=self.ctxt):
  94. self.service = service.Service.create(**self.kwargs)
  95. self.service.start()
  96. self.addCleanup(self.service.kill)
  97. class NullHandler(std_logging.Handler):
  98. """custom default NullHandler to attempt to format the record.
  99. Used in conjunction with
  100. log_fixture.get_logging_handle_error_fixture to detect formatting errors in
  101. debug level logs without saving the logs.
  102. """
  103. def handle(self, record):
  104. self.format(record)
  105. def emit(self, record):
  106. pass
  107. def createLock(self):
  108. self.lock = None
  109. class StandardLogging(fixtures.Fixture):
  110. """Setup Logging redirection for tests.
  111. There are a number of things we want to handle with logging in tests:
  112. * Redirect the logging to somewhere that we can test or dump it later.
  113. * Ensure that as many DEBUG messages as possible are actually
  114. executed, to ensure they are actually syntactically valid (they
  115. often have not been).
  116. * Ensure that we create useful output for tests that doesn't
  117. overwhelm the testing system (which means we can't capture the
  118. 100 MB of debug logging on every run).
  119. To do this we create a logger fixture at the root level, which
  120. defaults to INFO and create a Null Logger at DEBUG which lets
  121. us execute log messages at DEBUG but not keep the output.
  122. To support local debugging OS_DEBUG=True can be set in the
  123. environment, which will print out the full debug logging.
  124. There are also a set of overrides for particularly verbose
  125. modules to be even less than INFO.
  126. """
  127. def setUp(self):
  128. super(StandardLogging, self).setUp()
  129. # set root logger to debug
  130. root = std_logging.getLogger()
  131. root.setLevel(std_logging.DEBUG)
  132. # supports collecting debug level for local runs
  133. if os.environ.get('OS_DEBUG') in _TRUE_VALUES:
  134. level = std_logging.DEBUG
  135. else:
  136. level = std_logging.INFO
  137. # Collect logs
  138. fs = '%(asctime)s %(levelname)s [%(name)s] %(message)s'
  139. self.logger = self.useFixture(
  140. fixtures.FakeLogger(format=fs, level=None))
  141. # TODO(sdague): why can't we send level through the fake
  142. # logger? Tests prove that it breaks, but it's worth getting
  143. # to the bottom of.
  144. root.handlers[0].setLevel(level)
  145. if level > std_logging.DEBUG:
  146. # Just attempt to format debug level logs, but don't save them
  147. handler = NullHandler()
  148. self.useFixture(fixtures.LogHandler(handler, nuke_handlers=False))
  149. handler.setLevel(std_logging.DEBUG)
  150. # Don't log every single DB migration step
  151. std_logging.getLogger(
  152. 'migrate.versioning.api').setLevel(std_logging.WARNING)
  153. # Or alembic for model comparisons.
  154. std_logging.getLogger('alembic').setLevel(std_logging.WARNING)
  155. # At times we end up calling back into main() functions in
  156. # testing. This has the possibility of calling logging.setup
  157. # again, which completely unwinds the logging capture we've
  158. # created here. Once we've setup the logging the way we want,
  159. # disable the ability for the test to change this.
  160. def fake_logging_setup(*args):
  161. pass
  162. self.useFixture(
  163. fixtures.MonkeyPatch('oslo_log.log.setup', fake_logging_setup))
  164. def delete_stored_logs(self):
  165. # NOTE(gibi): this depends on the internals of the fixtures.FakeLogger.
  166. # This could be enhanced once the PR
  167. # https://github.com/testing-cabal/fixtures/pull/42 merges
  168. self.logger._output.truncate(0)
  169. class OutputStreamCapture(fixtures.Fixture):
  170. """Capture output streams during tests.
  171. This fixture captures errant printing to stderr / stdout during
  172. the tests and lets us see those streams at the end of the test
  173. runs instead. Useful to see what was happening during failed
  174. tests.
  175. """
  176. def setUp(self):
  177. super(OutputStreamCapture, self).setUp()
  178. if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
  179. self.out = self.useFixture(fixtures.StringStream('stdout'))
  180. self.useFixture(
  181. fixtures.MonkeyPatch('sys.stdout', self.out.stream))
  182. if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
  183. self.err = self.useFixture(fixtures.StringStream('stderr'))
  184. self.useFixture(
  185. fixtures.MonkeyPatch('sys.stderr', self.err.stream))
  186. @property
  187. def stderr(self):
  188. return self.err._details["stderr"].as_text()
  189. @property
  190. def stdout(self):
  191. return self.out._details["stdout"].as_text()
  192. class Timeout(fixtures.Fixture):
  193. """Setup per test timeouts.
  194. In order to avoid test deadlocks we support setting up a test
  195. timeout parameter read from the environment. In almost all
  196. cases where the timeout is reached this means a deadlock.
  197. A class level TIMEOUT_SCALING_FACTOR also exists, which allows
  198. extremely long tests to specify they need more time.
  199. """
  200. def __init__(self, timeout, scaling=1):
  201. super(Timeout, self).__init__()
  202. try:
  203. self.test_timeout = int(timeout)
  204. except ValueError:
  205. # If timeout value is invalid do not set a timeout.
  206. self.test_timeout = 0
  207. if scaling >= 1:
  208. self.test_timeout *= scaling
  209. else:
  210. raise ValueError('scaling value must be >= 1')
  211. def setUp(self):
  212. super(Timeout, self).setUp()
  213. if self.test_timeout > 0:
  214. self.useFixture(fixtures.Timeout(self.test_timeout, gentle=True))
  215. class DatabasePoisonFixture(fixtures.Fixture):
  216. def setUp(self):
  217. super(DatabasePoisonFixture, self).setUp()
  218. self.useFixture(fixtures.MonkeyPatch(
  219. 'oslo_db.sqlalchemy.enginefacade._TransactionFactory.'
  220. '_create_session',
  221. self._poison_configure))
  222. def _poison_configure(self, *a, **k):
  223. # If you encounter this error, you might be tempted to just not
  224. # inherit from NoDBTestCase. Bug #1568414 fixed a few hundred of these
  225. # errors, and not once was that the correct solution. Instead,
  226. # consider some of the following tips (when applicable):
  227. #
  228. # - mock at the object layer rather than the db layer, for example:
  229. # nova.objects.instance.Instance.get
  230. # vs.
  231. # nova.db.instance_get
  232. #
  233. # - mock at the api layer rather than the object layer, for example:
  234. # nova.api.openstack.common.get_instance
  235. # vs.
  236. # nova.objects.instance.Instance.get
  237. #
  238. # - mock code that requires the database but is otherwise tangential
  239. # to the code you're testing (for example: EventReporterStub)
  240. #
  241. # - peruse some of the other database poison warning fixes here:
  242. # https://review.opendev.org/#/q/topic:bug/1568414
  243. raise Exception('This test uses methods that set internal oslo_db '
  244. 'state, but it does not claim to use the database. '
  245. 'This will conflict with the setup of tests that '
  246. 'do use the database and cause failures later.')
  247. class SingleCellSimple(fixtures.Fixture):
  248. """Setup the simplest cells environment possible
  249. This should be used when you do not care about multiple cells,
  250. or having a "real" environment for tests that should not care.
  251. This will give you a single cell, and map any and all accesses
  252. to that cell (even things that would go to cell0).
  253. If you need to distinguish between cell0 and cellN, then you
  254. should use the CellDatabases fixture.
  255. If instances should appear to still be in scheduling state, pass
  256. instances_created=False to init.
  257. """
  258. def __init__(self, instances_created=True):
  259. self.instances_created = instances_created
  260. def setUp(self):
  261. super(SingleCellSimple, self).setUp()
  262. self.useFixture(fixtures.MonkeyPatch(
  263. 'nova.objects.CellMappingList._get_all_from_db',
  264. self._fake_cell_list))
  265. self.useFixture(fixtures.MonkeyPatch(
  266. 'nova.objects.CellMappingList._get_by_project_id_from_db',
  267. self._fake_cell_list))
  268. self.useFixture(fixtures.MonkeyPatch(
  269. 'nova.objects.CellMapping._get_by_uuid_from_db',
  270. self._fake_cell_get))
  271. self.useFixture(fixtures.MonkeyPatch(
  272. 'nova.objects.HostMapping._get_by_host_from_db',
  273. self._fake_hostmapping_get))
  274. self.useFixture(fixtures.MonkeyPatch(
  275. 'nova.objects.InstanceMapping._get_by_instance_uuid_from_db',
  276. self._fake_instancemapping_get))
  277. self.useFixture(fixtures.MonkeyPatch(
  278. 'nova.objects.InstanceMappingList._get_by_instance_uuids_from_db',
  279. self._fake_instancemapping_get_uuids))
  280. self.useFixture(fixtures.MonkeyPatch(
  281. 'nova.objects.InstanceMapping._save_in_db',
  282. self._fake_instancemapping_get_save))
  283. self.useFixture(fixtures.MonkeyPatch(
  284. 'nova.context.target_cell',
  285. self._fake_target_cell))
  286. self.useFixture(fixtures.MonkeyPatch(
  287. 'nova.context.set_target_cell',
  288. lambda c, m: None))
  289. def _fake_hostmapping_get(self, *args):
  290. return {'id': 1,
  291. 'updated_at': None,
  292. 'created_at': None,
  293. 'host': 'host1',
  294. 'cell_mapping': self._fake_cell_list()[0]}
  295. def _fake_instancemapping_get_common(self, instance_uuid):
  296. return {
  297. 'id': 1,
  298. 'updated_at': None,
  299. 'created_at': None,
  300. 'instance_uuid': instance_uuid,
  301. 'cell_id': (self.instances_created and 1 or None),
  302. 'project_id': 'project',
  303. 'cell_mapping': (
  304. self.instances_created and self._fake_cell_get() or None),
  305. }
  306. def _fake_instancemapping_get_save(self, *args):
  307. return self._fake_instancemapping_get_common(args[-2])
  308. def _fake_instancemapping_get(self, *args):
  309. return self._fake_instancemapping_get_common(args[-1])
  310. def _fake_instancemapping_get_uuids(self, *args):
  311. return [self._fake_instancemapping_get(uuid)
  312. for uuid in args[-1]]
  313. def _fake_cell_get(self, *args):
  314. return self._fake_cell_list()[0]
  315. def _fake_cell_list(self, *args):
  316. return [{'id': 1,
  317. 'updated_at': None,
  318. 'created_at': None,
  319. 'uuid': uuidsentinel.cell1,
  320. 'name': 'onlycell',
  321. 'transport_url': 'fake://nowhere/',
  322. 'database_connection': 'sqlite:///',
  323. 'disabled': False}]
  324. @contextmanager
  325. def _fake_target_cell(self, context, target_cell):
  326. # NOTE(danms): Just pass through the context without actually
  327. # targeting anything.
  328. yield context
  329. class CheatingSerializer(rpc.RequestContextSerializer):
  330. """A messaging.RequestContextSerializer that helps with cells.
  331. Our normal serializer does not pass in the context like db_connection
  332. and mq_connection, for good reason. We don't really want/need to
  333. force a remote RPC server to use our values for this. However,
  334. during unit and functional tests, since we're all in the same
  335. process, we want cell-targeted RPC calls to preserve these values.
  336. Unless we had per-service config and database layer state for
  337. the fake services we start, this is a reasonable cheat.
  338. """
  339. def serialize_context(self, context):
  340. """Serialize context with the db_connection inside."""
  341. values = super(CheatingSerializer, self).serialize_context(context)
  342. values['db_connection'] = context.db_connection
  343. values['mq_connection'] = context.mq_connection
  344. return values
  345. def deserialize_context(self, values):
  346. """Deserialize context and honor db_connection if present."""
  347. ctxt = super(CheatingSerializer, self).deserialize_context(values)
  348. ctxt.db_connection = values.pop('db_connection', None)
  349. ctxt.mq_connection = values.pop('mq_connection', None)
  350. return ctxt
  351. class CellDatabases(fixtures.Fixture):
  352. """Create per-cell databases for testing.
  353. How to use::
  354. fix = CellDatabases()
  355. fix.add_cell_database('connection1')
  356. fix.add_cell_database('connection2', default=True)
  357. self.useFixture(fix)
  358. Passing default=True tells the fixture which database should
  359. be given to code that doesn't target a specific cell.
  360. """
  361. def __init__(self):
  362. self._ctxt_mgrs = {}
  363. self._last_ctxt_mgr = None
  364. self._default_ctxt_mgr = None
  365. # NOTE(danms): Use a ReaderWriterLock to synchronize our
  366. # global database muckery here. If we change global db state
  367. # to point to a cell, we need to take an exclusive lock to
  368. # prevent any other calls to get_context_manager() until we
  369. # reset to the default.
  370. self._cell_lock = lockutils.ReaderWriterLock()
  371. def _cache_schema(self, connection_str):
  372. # NOTE(melwitt): See the regular Database fixture for why
  373. # we do this.
  374. global DB_SCHEMA
  375. if not DB_SCHEMA['main']:
  376. ctxt_mgr = self._ctxt_mgrs[connection_str]
  377. engine = ctxt_mgr.writer.get_engine()
  378. conn = engine.connect()
  379. migration.db_sync(database='main')
  380. DB_SCHEMA['main'] = "".join(line for line
  381. in conn.connection.iterdump())
  382. engine.dispose()
  383. @contextmanager
  384. def _wrap_target_cell(self, context, cell_mapping):
  385. # NOTE(danms): This method is responsible for switching global
  386. # database state in a safe way such that code that doesn't
  387. # know anything about cell targeting (i.e. compute node code)
  388. # can continue to operate when called from something that has
  389. # targeted a specific cell. In order to make this safe from a
  390. # dining-philosopher-style deadlock, we need to be able to
  391. # support multiple threads talking to the same cell at the
  392. # same time and potentially recursion within the same thread
  393. # from code that would otherwise be running on separate nodes
  394. # in real life, but where we're actually recursing in the
  395. # tests.
  396. #
  397. # The basic logic here is:
  398. # 1. Grab a reader lock to see if the state is already pointing at
  399. # the cell we want. If it is, we can yield and return without
  400. # altering the global state further. The read lock ensures that
  401. # global state won't change underneath us, and multiple threads
  402. # can be working at the same time, as long as they are looking
  403. # for the same cell.
  404. # 2. If we do need to change the global state, grab a writer lock
  405. # to make that change, which assumes that nothing else is looking
  406. # at a cell right now. We do only non-schedulable things while
  407. # holding that lock to avoid the deadlock mentioned above.
  408. # 3. We then re-lock with a reader lock just as step #1 above and
  409. # yield to do the actual work. We can do schedulable things
  410. # here and not exclude other threads from making progress.
  411. # If an exception is raised, we capture that and save it.
  412. # 4. If we changed state in #2, we need to change it back. So we grab
  413. # a writer lock again and do that.
  414. # 5. Finally, if an exception was raised in #3 while state was
  415. # changed, we raise it to the caller.
  416. if cell_mapping:
  417. desired = self._ctxt_mgrs[cell_mapping.database_connection]
  418. else:
  419. desired = self._default_ctxt_mgr
  420. with self._cell_lock.read_lock():
  421. if self._last_ctxt_mgr == desired:
  422. with self._real_target_cell(context, cell_mapping) as c:
  423. yield c
  424. return
  425. raised_exc = None
  426. with self._cell_lock.write_lock():
  427. if cell_mapping is not None:
  428. # This assumes the next local DB access is the same cell that
  429. # was targeted last time.
  430. self._last_ctxt_mgr = desired
  431. with self._cell_lock.read_lock():
  432. if self._last_ctxt_mgr != desired:
  433. # NOTE(danms): This is unlikely to happen, but it's possible
  434. # another waiting writer changed the state between us letting
  435. # it go and re-acquiring as a reader. If lockutils supported
  436. # upgrading and downgrading locks, this wouldn't be a problem.
  437. # Regardless, assert that it is still as we left it here
  438. # so we don't hit the wrong cell. If this becomes a problem,
  439. # we just need to retry the write section above until we land
  440. # here with the cell we want.
  441. raise RuntimeError('Global DB state changed underneath us')
  442. try:
  443. with self._real_target_cell(context, cell_mapping) as ccontext:
  444. yield ccontext
  445. except Exception as exc:
  446. raised_exc = exc
  447. with self._cell_lock.write_lock():
  448. # Once we have returned from the context, we need
  449. # to restore the default context manager for any
  450. # subsequent calls
  451. self._last_ctxt_mgr = self._default_ctxt_mgr
  452. if raised_exc:
  453. raise raised_exc
  454. def _wrap_create_context_manager(self, connection=None):
  455. ctxt_mgr = self._ctxt_mgrs[connection]
  456. return ctxt_mgr
  457. def _wrap_get_context_manager(self, context):
  458. try:
  459. # If already targeted, we can proceed without a lock
  460. if context.db_connection:
  461. return context.db_connection
  462. except AttributeError:
  463. # Unit tests with None, FakeContext, etc
  464. pass
  465. # NOTE(melwitt): This is a hack to try to deal with
  466. # local accesses i.e. non target_cell accesses.
  467. with self._cell_lock.read_lock():
  468. # FIXME(mriedem): This is actually misleading and means we don't
  469. # catch things like bug 1717000 where a context should be targeted
  470. # to a cell but it's not, and the fixture here just returns the
  471. # last targeted context that was used.
  472. return self._last_ctxt_mgr
  473. def _wrap_get_server(self, target, endpoints, serializer=None):
  474. """Mirror rpc.get_server() but with our special sauce."""
  475. serializer = CheatingSerializer(serializer)
  476. return messaging.get_rpc_server(rpc.TRANSPORT,
  477. target,
  478. endpoints,
  479. executor='eventlet',
  480. serializer=serializer)
  481. def _wrap_get_client(self, target, version_cap=None, serializer=None,
  482. call_monitor_timeout=None):
  483. """Mirror rpc.get_client() but with our special sauce."""
  484. serializer = CheatingSerializer(serializer)
  485. return messaging.RPCClient(rpc.TRANSPORT,
  486. target,
  487. version_cap=version_cap,
  488. serializer=serializer,
  489. call_monitor_timeout=call_monitor_timeout)
  490. def add_cell_database(self, connection_str, default=False):
  491. """Add a cell database to the fixture.
  492. :param connection_str: An identifier used to represent the connection
  493. string for this database. It should match the database_connection field
  494. in the corresponding CellMapping.
  495. """
  496. # NOTE(danms): Create a new context manager for the cell, which
  497. # will house the sqlite:// connection for this cell's in-memory
  498. # database. Store/index it by the connection string, which is
  499. # how we identify cells in CellMapping.
  500. ctxt_mgr = session.create_context_manager()
  501. self._ctxt_mgrs[connection_str] = ctxt_mgr
  502. # NOTE(melwitt): The first DB access through service start is
  503. # local so this initializes _last_ctxt_mgr for that and needs
  504. # to be a compute cell.
  505. self._last_ctxt_mgr = ctxt_mgr
  506. # NOTE(danms): Record which context manager should be the default
  507. # so we can restore it when we return from target-cell contexts.
  508. # If none has been provided yet, store the current one in case
  509. # no default is ever specified.
  510. if self._default_ctxt_mgr is None or default:
  511. self._default_ctxt_mgr = ctxt_mgr
  512. def get_context_manager(context):
  513. return ctxt_mgr
  514. # NOTE(danms): This is a temporary MonkeyPatch just to get
  515. # a new database created with the schema we need and the
  516. # context manager for it stashed.
  517. with fixtures.MonkeyPatch(
  518. 'nova.db.sqlalchemy.api.get_context_manager',
  519. get_context_manager):
  520. self._cache_schema(connection_str)
  521. engine = ctxt_mgr.writer.get_engine()
  522. engine.dispose()
  523. conn = engine.connect()
  524. conn.connection.executescript(DB_SCHEMA['main'])
  525. def setUp(self):
  526. super(CellDatabases, self).setUp()
  527. self.addCleanup(self.cleanup)
  528. self._real_target_cell = context.target_cell
  529. # NOTE(danms): These context managers are in place for the
  530. # duration of the test (unlike the temporary ones above) and
  531. # provide the actual "runtime" switching of connections for us.
  532. self.useFixture(fixtures.MonkeyPatch(
  533. 'nova.db.sqlalchemy.api.create_context_manager',
  534. self._wrap_create_context_manager))
  535. self.useFixture(fixtures.MonkeyPatch(
  536. 'nova.db.sqlalchemy.api.get_context_manager',
  537. self._wrap_get_context_manager))
  538. self.useFixture(fixtures.MonkeyPatch(
  539. 'nova.context.target_cell',
  540. self._wrap_target_cell))
  541. self.useFixture(fixtures.MonkeyPatch(
  542. 'nova.rpc.get_server',
  543. self._wrap_get_server))
  544. self.useFixture(fixtures.MonkeyPatch(
  545. 'nova.rpc.get_client',
  546. self._wrap_get_client))
  547. def cleanup(self):
  548. for ctxt_mgr in self._ctxt_mgrs.values():
  549. engine = ctxt_mgr.writer.get_engine()
  550. engine.dispose()
  551. class Database(fixtures.Fixture):
  552. def __init__(self, database='main', connection=None):
  553. """Create a database fixture.
  554. :param database: The type of database, 'main', or 'api'
  555. :param connection: The connection string to use
  556. """
  557. super(Database, self).__init__()
  558. # NOTE(pkholkin): oslo_db.enginefacade is configured in tests the same
  559. # way as it is done for any other service that uses db
  560. global SESSION_CONFIGURED
  561. if not SESSION_CONFIGURED:
  562. session.configure(CONF)
  563. SESSION_CONFIGURED = True
  564. self.database = database
  565. if database == 'main':
  566. if connection is not None:
  567. ctxt_mgr = session.create_context_manager(
  568. connection=connection)
  569. self.get_engine = ctxt_mgr.writer.get_engine
  570. else:
  571. self.get_engine = session.get_engine
  572. elif database == 'api':
  573. self.get_engine = session.get_api_engine
  574. def _cache_schema(self):
  575. global DB_SCHEMA
  576. if not DB_SCHEMA[self.database]:
  577. engine = self.get_engine()
  578. conn = engine.connect()
  579. migration.db_sync(database=self.database)
  580. DB_SCHEMA[self.database] = "".join(line for line
  581. in conn.connection.iterdump())
  582. engine.dispose()
  583. def cleanup(self):
  584. engine = self.get_engine()
  585. engine.dispose()
  586. def reset(self):
  587. self._cache_schema()
  588. engine = self.get_engine()
  589. engine.dispose()
  590. conn = engine.connect()
  591. conn.connection.executescript(DB_SCHEMA[self.database])
  592. def setUp(self):
  593. super(Database, self).setUp()
  594. self.reset()
  595. self.addCleanup(self.cleanup)
  596. class DatabaseAtVersion(fixtures.Fixture):
  597. def __init__(self, version, database='main'):
  598. """Create a database fixture.
  599. :param version: Max version to sync to (or None for current)
  600. :param database: The type of database, 'main', 'api'
  601. """
  602. super(DatabaseAtVersion, self).__init__()
  603. self.database = database
  604. self.version = version
  605. if database == 'main':
  606. self.get_engine = session.get_engine
  607. elif database == 'api':
  608. self.get_engine = session.get_api_engine
  609. def cleanup(self):
  610. engine = self.get_engine()
  611. engine.dispose()
  612. def reset(self):
  613. engine = self.get_engine()
  614. engine.dispose()
  615. engine.connect()
  616. migration.db_sync(version=self.version, database=self.database)
  617. def setUp(self):
  618. super(DatabaseAtVersion, self).setUp()
  619. self.reset()
  620. self.addCleanup(self.cleanup)
  621. class DefaultFlavorsFixture(fixtures.Fixture):
  622. def setUp(self):
  623. super(DefaultFlavorsFixture, self).setUp()
  624. ctxt = context.get_admin_context()
  625. defaults = {'rxtx_factor': 1.0, 'disabled': False, 'is_public': True,
  626. 'ephemeral_gb': 0, 'swap': 0}
  627. extra_specs = {
  628. "hw:numa_nodes": "1"
  629. }
  630. default_flavors = [
  631. objects.Flavor(context=ctxt, memory_mb=512, vcpus=1,
  632. root_gb=1, flavorid='1', name='m1.tiny',
  633. **defaults),
  634. objects.Flavor(context=ctxt, memory_mb=2048, vcpus=1,
  635. root_gb=20, flavorid='2', name='m1.small',
  636. **defaults),
  637. objects.Flavor(context=ctxt, memory_mb=4096, vcpus=2,
  638. root_gb=40, flavorid='3', name='m1.medium',
  639. **defaults),
  640. objects.Flavor(context=ctxt, memory_mb=8192, vcpus=4,
  641. root_gb=80, flavorid='4', name='m1.large',
  642. **defaults),
  643. objects.Flavor(context=ctxt, memory_mb=16384, vcpus=8,
  644. root_gb=160, flavorid='5', name='m1.xlarge',
  645. **defaults),
  646. objects.Flavor(context=ctxt, memory_mb=512, vcpus=1,
  647. root_gb=1, flavorid='6', name='m1.tiny.specs',
  648. extra_specs=extra_specs, **defaults),
  649. ]
  650. for flavor in default_flavors:
  651. flavor.create()
  652. class RPCFixture(fixtures.Fixture):
  653. def __init__(self, *exmods):
  654. super(RPCFixture, self).__init__()
  655. self.exmods = []
  656. self.exmods.extend(exmods)
  657. self._buses = {}
  658. def _fake_create_transport(self, url):
  659. # FIXME(danms): Right now, collapse all connections
  660. # to a single bus. This is how our tests expect things
  661. # to work. When the tests are fixed, this fixture can
  662. # support simulating multiple independent buses, and this
  663. # hack should be removed.
  664. url = None
  665. # NOTE(danms): This will be called with a non-None url by
  666. # cells-aware code that is requesting to contact something on
  667. # one of the many transports we're multplexing here.
  668. if url not in self._buses:
  669. exmods = rpc.get_allowed_exmods()
  670. self._buses[url] = messaging.get_rpc_transport(
  671. CONF,
  672. url=url,
  673. allowed_remote_exmods=exmods)
  674. return self._buses[url]
  675. def setUp(self):
  676. super(RPCFixture, self).setUp()
  677. self.addCleanup(rpc.cleanup)
  678. rpc.add_extra_exmods(*self.exmods)
  679. self.addCleanup(rpc.clear_extra_exmods)
  680. self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
  681. self.messaging_conf.transport_url = 'fake:/'
  682. self.useFixture(self.messaging_conf)
  683. self.useFixture(fixtures.MonkeyPatch(
  684. 'nova.rpc.create_transport', self._fake_create_transport))
  685. # NOTE(danms): Execute the init with get_transport_url() as None,
  686. # instead of the parsed TransportURL(None) so that we can cache
  687. # it as it will be called later if the default is requested by
  688. # one of our mq-switching methods.
  689. with mock.patch('nova.rpc.get_transport_url') as mock_gtu:
  690. mock_gtu.return_value = None
  691. rpc.init(CONF)
  692. def cleanup_in_flight_rpc_messages():
  693. messaging._drivers.impl_fake.FakeExchangeManager._exchanges = {}
  694. self.addCleanup(cleanup_in_flight_rpc_messages)
  695. class WarningsFixture(fixtures.Fixture):
  696. """Filters out warnings during test runs."""
  697. def setUp(self):
  698. super(WarningsFixture, self).setUp()
  699. # NOTE(sdague): Make deprecation warnings only happen once. Otherwise
  700. # this gets kind of crazy given the way that upstream python libs use
  701. # this.
  702. warnings.simplefilter("once", DeprecationWarning)
  703. warnings.filterwarnings('ignore',
  704. message='With-statements now directly support'
  705. ' multiple context managers')
  706. # NOTE(sdague): nova does not use pkg_resources directly, this
  707. # is all very long standing deprecations about other tools
  708. # using it. None of this is useful to Nova development.
  709. warnings.filterwarnings('ignore',
  710. module='pkg_resources')
  711. # NOTE(sdague): this remains an unresolved item around the way
  712. # forward on is_admin, the deprecation is definitely really premature.
  713. warnings.filterwarnings('ignore',
  714. message='Policy enforcement is depending on the value of is_admin.'
  715. ' This key is deprecated. Please update your policy '
  716. 'file to use the standard policy values.')
  717. # TODO(takashin): Remove filtering warnings about mox
  718. # after removing tests which uses mox and are related to
  719. # nova-network in the following files.
  720. #
  721. # - nova/tests/unit/api/openstack/compute/test_floating_ips.py
  722. # - nova/tests/unit/api/openstack/compute/test_security_groups.py
  723. # - nova/tests/unit/fake_network.py
  724. # - nova/tests/unit/network/test_manager.py
  725. warnings.filterwarnings('ignore',
  726. module='mox3.mox')
  727. # NOTE(gibi): we can remove this once we get rid of Mox in nova
  728. warnings.filterwarnings('ignore', message="Using class 'MoxStubout'")
  729. # NOTE(mriedem): Ignore scope check UserWarnings from oslo.policy.
  730. warnings.filterwarnings('ignore',
  731. message="Policy .* failed scope check",
  732. category=UserWarning)
  733. # NOTE(gibi): The UUIDFields emits a warning if the value is not a
  734. # valid UUID. Let's escalate that to an exception in the test to
  735. # prevent adding violations.
  736. warnings.filterwarnings('error', message=".*invalid UUID.*")
  737. # NOTE(mriedem): Avoid adding anything which tries to convert an
  738. # object to a primitive which jsonutils.to_primitive() does not know
  739. # how to handle (or isn't given a fallback callback).
  740. warnings.filterwarnings(
  741. 'error',
  742. message="Cannot convert <oslo_db.sqlalchemy.enginefacade"
  743. "._Default object at ",
  744. category=UserWarning)
  745. warnings.filterwarnings(
  746. 'error', message='Evaluating non-mapped column expression',
  747. category=sqla_exc.SAWarning)
  748. # TODO(jangutter): Change (or remove) this to an error during the Train
  749. # cycle when the os-vif port profile is no longer used.
  750. warnings.filterwarnings(
  751. 'ignore', message=".* 'VIFPortProfileOVSRepresentor' .* "
  752. "is deprecated", category=PendingDeprecationWarning)
  753. # TODO(mriedem): Change (or remove) this DeprecationWarning once
  754. # https://bugs.launchpad.net/sqlalchemy-migrate/+bug/1814288 is fixed.
  755. warnings.filterwarnings(
  756. 'ignore', message=r'inspect.getargspec\(\) is deprecated',
  757. category=DeprecationWarning,
  758. module='migrate.versioning.script.py')
  759. # TODO(stephenfin): Remove once we bump our sqlalchemy-migrate version
  760. # to whatever is released early in Ussuri and includes change
  761. # I319785d7dd83ffe2c6e651a2494b073becc84684
  762. warnings.filterwarnings(
  763. 'ignore', message='The Engine.contextual_connect.*',
  764. category=sqla_exc.SADeprecationWarning,
  765. module='migrate.changeset.databases.visitor')
  766. self.addCleanup(warnings.resetwarnings)
  767. class ConfPatcher(fixtures.Fixture):
  768. """Fixture to patch and restore global CONF.
  769. This also resets overrides for everything that is patched during
  770. it's teardown.
  771. """
  772. def __init__(self, **kwargs):
  773. """Constructor
  774. :params group: if specified all config options apply to that group.
  775. :params **kwargs: the rest of the kwargs are processed as a
  776. set of key/value pairs to be set as configuration override.
  777. """
  778. super(ConfPatcher, self).__init__()
  779. self.group = kwargs.pop('group', None)
  780. self.args = kwargs
  781. def setUp(self):
  782. super(ConfPatcher, self).setUp()
  783. for k, v in self.args.items():
  784. self.addCleanup(CONF.clear_override, k, self.group)
  785. CONF.set_override(k, v, self.group)
  786. class OSAPIFixture(fixtures.Fixture):
  787. """Create an OS API server as a fixture.
  788. This spawns an OS API server as a fixture in a new greenthread in
  789. the current test. The fixture has a .api parameter with is a
  790. simple rest client that can communicate with it.
  791. This fixture is extremely useful for testing REST responses
  792. through the WSGI stack easily in functional tests.
  793. Usage:
  794. api = self.useFixture(fixtures.OSAPIFixture()).api
  795. resp = api.api_request('/someurl')
  796. self.assertEqual(200, resp.status_code)
  797. resp = api.api_request('/otherurl', method='POST', body='{foo}')
  798. The resp is a requests library response. Common attributes that
  799. you'll want to use are:
  800. - resp.status_code - integer HTTP status code returned by the request
  801. - resp.content - the body of the response
  802. - resp.headers - dictionary of HTTP headers returned
  803. """
  804. def __init__(self, api_version='v2',
  805. project_id='6f70656e737461636b20342065766572'):
  806. """Constructor
  807. :param api_version: the API version that we're interested in
  808. using. Currently this expects 'v2' or 'v2.1' as possible
  809. options.
  810. :param project_id: the project id to use on the API.
  811. """
  812. super(OSAPIFixture, self).__init__()
  813. self.api_version = api_version
  814. self.project_id = project_id
  815. def setUp(self):
  816. super(OSAPIFixture, self).setUp()
  817. # A unique hostname for the wsgi-intercept.
  818. hostname = uuidsentinel.osapi_host
  819. port = 80
  820. service_name = 'osapi_compute'
  821. endpoint = 'http://%s:%s/' % (hostname, port)
  822. conf_overrides = {
  823. 'osapi_compute_listen': hostname,
  824. 'osapi_compute_listen_port': port,
  825. 'debug': True,
  826. }
  827. self.useFixture(ConfPatcher(**conf_overrides))
  828. # Turn off manipulation of socket_options in TCPKeepAliveAdapter
  829. # to keep wsgi-intercept happy. Replace it with the method
  830. # from its superclass.
  831. self.useFixture(fixtures.MonkeyPatch(
  832. 'keystoneauth1.session.TCPKeepAliveAdapter.init_poolmanager',
  833. adapters.HTTPAdapter.init_poolmanager))
  834. loader = wsgi.Loader().load_app(service_name)
  835. app = lambda: loader
  836. # re-use service setup code from wsgi_app to register
  837. # service, which is looked for in some tests
  838. wsgi_app._setup_service(CONF.host, service_name)
  839. intercept = interceptor.RequestsInterceptor(app, url=endpoint)
  840. intercept.install_intercept()
  841. self.addCleanup(intercept.uninstall_intercept)
  842. self.auth_url = 'http://%(host)s:%(port)s/%(api_version)s' % ({
  843. 'host': hostname, 'port': port, 'api_version': self.api_version})
  844. self.api = client.TestOpenStackClient('fake', 'fake', self.auth_url,
  845. self.project_id)
  846. self.admin_api = client.TestOpenStackClient(
  847. 'admin', 'admin', self.auth_url, self.project_id)
  848. # Provide a way to access the wsgi application to tests using
  849. # the fixture.
  850. self.app = app
  851. class OSMetadataServer(fixtures.Fixture):
  852. """Create an OS Metadata API server as a fixture.
  853. This spawns an OS Metadata API server as a fixture in a new
  854. greenthread in the current test.
  855. TODO(sdague): ideally for testing we'd have something like the
  856. test client which acts like requests, but connects any of the
  857. interactions needed.
  858. """
  859. def setUp(self):
  860. super(OSMetadataServer, self).setUp()
  861. # in order to run these in tests we need to bind only to local
  862. # host, and dynamically allocate ports
  863. conf_overrides = {
  864. 'metadata_listen': '127.0.0.1',
  865. 'metadata_listen_port': 0,
  866. 'debug': True
  867. }
  868. self.useFixture(ConfPatcher(**conf_overrides))
  869. # NOTE(mikal): we don't have root to manipulate iptables, so just
  870. # zero that bit out.
  871. self.useFixture(fixtures.MonkeyPatch(
  872. 'nova.network.linux_net.IptablesManager._apply',
  873. lambda _: None))
  874. self.metadata = service.WSGIService("metadata")
  875. self.metadata.start()
  876. self.addCleanup(self.metadata.stop)
  877. self.md_url = "http://%s:%s/" % (
  878. conf_overrides['metadata_listen'],
  879. self.metadata.port)
  880. class PoisonFunctions(fixtures.Fixture):
  881. """Poison functions so they explode if we touch them.
  882. When running under a non full stack test harness there are parts
  883. of the code that you don't want to go anywhere near. These include
  884. things like code that spins up extra threads, which just
  885. introduces races.
  886. """
  887. def setUp(self):
  888. super(PoisonFunctions, self).setUp()
  889. # The nova libvirt driver starts an event thread which only
  890. # causes trouble in tests. Make sure that if tests don't
  891. # properly patch it the test explodes.
  892. def evloop(*args, **kwargs):
  893. import sys
  894. warnings.warn("Forgot to disable libvirt event thread")
  895. sys.exit(1)
  896. # Don't poison the function if it's already mocked
  897. import nova.virt.libvirt.host
  898. if not isinstance(nova.virt.libvirt.host.Host._init_events, mock.Mock):
  899. self.useFixture(fixtures.MockPatch(
  900. 'nova.virt.libvirt.host.Host._init_events',
  901. side_effect=evloop))
  902. class IndirectionAPIFixture(fixtures.Fixture):
  903. """Patch and restore the global NovaObject indirection api."""
  904. def __init__(self, indirection_api):
  905. """Constructor
  906. :param indirection_api: the indirection API to be used for tests.
  907. """
  908. super(IndirectionAPIFixture, self).__init__()
  909. self.indirection_api = indirection_api
  910. def cleanup(self):
  911. obj_base.NovaObject.indirection_api = self.orig_indirection_api
  912. def setUp(self):
  913. super(IndirectionAPIFixture, self).setUp()
  914. self.orig_indirection_api = obj_base.NovaObject.indirection_api
  915. obj_base.NovaObject.indirection_api = self.indirection_api
  916. self.addCleanup(self.cleanup)
  917. class _FakeGreenThread(object):
  918. def __init__(self, func, *args, **kwargs):
  919. self._result = func(*args, **kwargs)
  920. def cancel(self, *args, **kwargs):
  921. # This method doesn't make sense for a synchronous call, it's just
  922. # defined to satisfy the interface.
  923. pass
  924. def kill(self, *args, **kwargs):
  925. # This method doesn't make sense for a synchronous call, it's just
  926. # defined to satisfy the interface.
  927. pass
  928. def link(self, func, *args, **kwargs):
  929. func(self, *args, **kwargs)
  930. def unlink(self, func, *args, **kwargs):
  931. # This method doesn't make sense for a synchronous call, it's just
  932. # defined to satisfy the interface.
  933. pass
  934. def wait(self):
  935. return self._result
  936. class SpawnIsSynchronousFixture(fixtures.Fixture):
  937. """Patch and restore the spawn_n utility method to be synchronous"""
  938. def setUp(self):
  939. super(SpawnIsSynchronousFixture, self).setUp()
  940. self.useFixture(fixtures.MonkeyPatch(
  941. 'nova.utils.spawn_n', _FakeGreenThread))
  942. self.useFixture(fixtures.MonkeyPatch(
  943. 'nova.utils.spawn', _FakeGreenThread))
  944. class _FakeExecutor(futurist.SynchronousExecutor):
  945. def __init__(self, *args, **kwargs):
  946. # Ignore kwargs (example: max_workers) that SynchronousExecutor
  947. # does not support.
  948. super(_FakeExecutor, self).__init__()
  949. class SynchronousThreadPoolExecutorFixture(fixtures.Fixture):
  950. """Make GreenThreadPoolExecutor synchronous.
  951. Replace the GreenThreadPoolExecutor with the SynchronousExecutor.
  952. """
  953. def setUp(self):
  954. super(SynchronousThreadPoolExecutorFixture, self).setUp()
  955. self.useFixture(fixtures.MonkeyPatch(
  956. 'futurist.GreenThreadPoolExecutor', _FakeExecutor))
  957. class BannedDBSchemaOperations(fixtures.Fixture):
  958. """Ban some operations for migrations"""
  959. def __init__(self, banned_resources=None):
  960. super(BannedDBSchemaOperations, self).__init__()
  961. self._banned_resources = banned_resources or []
  962. @staticmethod
  963. def _explode(resource, op):
  964. raise exception.DBNotAllowed(
  965. 'Operation %s.%s() is not allowed in a database migration' % (
  966. resource, op))
  967. def setUp(self):
  968. super(BannedDBSchemaOperations, self).setUp()
  969. for thing in self._banned_resources:
  970. self.useFixture(fixtures.MonkeyPatch(
  971. 'sqlalchemy.%s.drop' % thing,
  972. lambda *a, **k: self._explode(thing, 'drop')))
  973. self.useFixture(fixtures.MonkeyPatch(
  974. 'sqlalchemy.%s.alter' % thing,
  975. lambda *a, **k: self._explode(thing, 'alter')))
  976. class ForbidNewLegacyNotificationFixture(fixtures.Fixture):
  977. """Make sure the test fails if new legacy notification is added"""
  978. def __init__(self):
  979. super(ForbidNewLegacyNotificationFixture, self).__init__()
  980. self.notifier = rpc.LegacyValidatingNotifier
  981. def setUp(self):
  982. super(ForbidNewLegacyNotificationFixture, self).setUp()
  983. self.notifier.fatal = True
  984. # allow the special test value used in
  985. # nova.tests.unit.test_notifications.NotificationsTestCase
  986. self.notifier.allowed_legacy_notification_event_types.append(
  987. '_decorated_function')
  988. self.addCleanup(self.cleanup)
  989. def cleanup(self):
  990. self.notifier.fatal = False
  991. self.notifier.allowed_legacy_notification_event_types.remove(
  992. '_decorated_function')
  993. class AllServicesCurrent(fixtures.Fixture):
  994. def setUp(self):
  995. super(AllServicesCurrent, self).setUp()
  996. self.useFixture(fixtures.MonkeyPatch(
  997. 'nova.objects.Service.get_minimum_version_multi',
  998. self._fake_minimum))
  999. self.useFixture(fixtures.MonkeyPatch(
  1000. 'nova.objects.service.get_minimum_version_all_cells',
  1001. lambda *a, **k: service_obj.SERVICE_VERSION))
  1002. compute_rpcapi.LAST_VERSION = None
  1003. def _fake_minimum(self, *args, **kwargs):
  1004. return service_obj.SERVICE_VERSION
  1005. class RegisterNetworkQuota(fixtures.Fixture):
  1006. def setUp(self):
  1007. super(RegisterNetworkQuota, self).setUp()
  1008. # Quota resource registration modifies the global QUOTAS engine, so
  1009. # this fixture registers and unregisters network quota for a test.
  1010. tenant_networks._register_network_quota()
  1011. self.addCleanup(self.cleanup)
  1012. def cleanup(self):
  1013. nova_quota.QUOTAS._resources.pop('networks', None)
  1014. class NeutronFixture(fixtures.Fixture):
  1015. """A fixture to boot instances with neutron ports"""
  1016. # the default project_id in OsaAPIFixtures
  1017. tenant_id = '6f70656e737461636b20342065766572'
  1018. network_1 = {
  1019. 'status': 'ACTIVE',
  1020. 'subnets': [],
  1021. 'name': 'private-network',
  1022. 'admin_state_up': True,
  1023. 'tenant_id': tenant_id,
  1024. 'id': '3cb9bc59-5699-4588-a4b1-b87f96708bc6',
  1025. 'shared': False,
  1026. }
  1027. subnet_1 = {
  1028. 'name': 'private-subnet',
  1029. 'enable_dhcp': True,
  1030. 'network_id': network_1['id'],
  1031. 'tenant_id': tenant_id,
  1032. 'dns_nameservers': [],
  1033. 'allocation_pools': [
  1034. {
  1035. 'start': '192.168.1.1',
  1036. 'end': '192.168.1.254'
  1037. }
  1038. ],
  1039. 'host_routes': [],
  1040. 'ip_version': 4,
  1041. 'gateway_ip': '192.168.1.1',
  1042. 'cidr': '192.168.1.1/24',
  1043. 'id': 'f8a6e8f8-c2ec-497c-9f23-da9616de54ef'
  1044. }
  1045. network_1['subnets'] = [subnet_1['id']]
  1046. port_1 = {
  1047. 'id': 'ce531f90-199f-48c0-816c-13e38010b442',
  1048. 'network_id': network_1['id'],
  1049. 'admin_state_up': True,
  1050. 'status': 'ACTIVE',
  1051. 'mac_address': 'fa:16:3e:4c:2c:30',
  1052. 'fixed_ips': [
  1053. {
  1054. # The IP on this port must be a prefix of the IP on port_2 to
  1055. # test listing servers with an ip filter regex.
  1056. 'ip_address': '192.168.1.3',
  1057. 'subnet_id': subnet_1['id']
  1058. }
  1059. ],
  1060. 'tenant_id': tenant_id,
  1061. 'binding:vif_type': 'ovs'
  1062. }
  1063. port_2 = {
  1064. 'id': '88dae9fa-0dc6-49e3-8c29-3abc41e99ac9',
  1065. 'network_id': network_1['id'],
  1066. 'admin_state_up': True,
  1067. 'status': 'ACTIVE',
  1068. 'mac_address': '00:0c:29:0d:11:74',
  1069. 'fixed_ips': [
  1070. {
  1071. 'ip_address': '192.168.1.30',
  1072. 'subnet_id': subnet_1['id']
  1073. }
  1074. ],
  1075. 'tenant_id': tenant_id,
  1076. 'binding:vif_type': 'ovs'
  1077. }
  1078. port_with_resource_request = {
  1079. 'id': '2f2613ce-95a9-490a-b3c4-5f1c28c1f886',
  1080. 'network_id': network_1['id'],
  1081. 'admin_state_up': True,
  1082. 'status': 'ACTIVE',
  1083. 'mac_address': '52:54:00:1e:59:c3',
  1084. 'fixed_ips': [
  1085. {
  1086. 'ip_address': '192.168.1.42',
  1087. 'subnet_id': subnet_1['id']
  1088. }
  1089. ],
  1090. 'tenant_id': tenant_id,
  1091. neutron_constants.RESOURCE_REQUEST: {
  1092. "resources": {
  1093. orc.NET_BW_IGR_KILOBIT_PER_SEC: 1000,
  1094. orc.NET_BW_EGR_KILOBIT_PER_SEC: 1000},
  1095. "required": ["CUSTOM_PHYSNET2", "CUSTOM_VNIC_TYPE_NORMAL"]
  1096. }
  1097. }
  1098. network_2 = {
  1099. 'status': 'ACTIVE',
  1100. 'subnets': [],
  1101. 'name': 'private-network',
  1102. 'admin_state_up': True,
  1103. 'tenant_id': tenant_id,
  1104. 'id': '1b70879f-fd00-411e-8ea9-143e7820e61d',
  1105. 'shared': False,
  1106. 'provider:physical_network': 'physnet2',
  1107. "provider:network_type": "vlan",
  1108. }
  1109. subnet_2 = {
  1110. 'name': 'private-subnet',
  1111. 'enable_dhcp': True,
  1112. 'network_id': network_2['id'],
  1113. 'tenant_id': tenant_id,
  1114. 'dns_nameservers': [],
  1115. 'allocation_pools': [
  1116. {
  1117. 'start': '192.168.13.1',
  1118. 'end': '192.168.1.254'
  1119. }
  1120. ],
  1121. 'host_routes': [],
  1122. 'ip_version': 4,
  1123. 'gateway_ip': '192.168.1.1',
  1124. 'cidr': '192.168.1.1/24',
  1125. 'id': 'c7ca1baf-f536-4849-89fe-9671318375ff'
  1126. }
  1127. network_2['subnets'] = [subnet_2['id']]
  1128. sriov_port = {
  1129. 'id': '5460ee0c-ffbb-4e45-8d58-37bfceabd084',
  1130. 'network_id': network_2['id'],
  1131. 'admin_state_up': True,
  1132. 'status': 'ACTIVE',
  1133. 'mac_address': '52:54:00:1e:59:c4',
  1134. 'fixed_ips': [
  1135. {
  1136. 'ip_address': '192.168.13.2',
  1137. 'subnet_id': subnet_2['id']
  1138. }
  1139. ],
  1140. 'tenant_id': tenant_id,
  1141. neutron_constants.RESOURCE_REQUEST: {},
  1142. 'binding:vnic_type': 'direct',
  1143. }
  1144. port_with_sriov_resource_request = {
  1145. 'id': '7059503b-a648-40fd-a561-5ca769304bee',
  1146. 'network_id': network_2['id'],
  1147. 'admin_state_up': True,
  1148. 'status': 'ACTIVE',
  1149. 'mac_address': '52:54:00:1e:59:c5',
  1150. # Do neutron really adds fixed_ips to an direct vnic_type port?
  1151. 'fixed_ips': [
  1152. {
  1153. 'ip_address': '192.168.13.3',
  1154. 'subnet_id': subnet_2['id']
  1155. }
  1156. ],
  1157. 'tenant_id': tenant_id,
  1158. neutron_constants.RESOURCE_REQUEST: {
  1159. "resources": {
  1160. orc.NET_BW_IGR_KILOBIT_PER_SEC: 10000,
  1161. orc.NET_BW_EGR_KILOBIT_PER_SEC: 10000},
  1162. "required": ["CUSTOM_PHYSNET2", "CUSTOM_VNIC_TYPE_DIRECT"]
  1163. },
  1164. 'binding:vnic_type': 'direct',
  1165. }
  1166. port_macvtap_with_resource_request = {
  1167. 'id': 'cbb9707f-3559-4675-a973-4ea89c747f02',
  1168. 'network_id': network_2['id'],
  1169. 'admin_state_up': True,
  1170. 'status': 'ACTIVE',
  1171. 'mac_address': '52:54:00:1e:59:c6',
  1172. # Do neutron really adds fixed_ips to an direct vnic_type port?
  1173. 'fixed_ips': [
  1174. {
  1175. 'ip_address': '192.168.13.4',
  1176. 'subnet_id': subnet_2['id']
  1177. }
  1178. ],
  1179. 'tenant_id': tenant_id,
  1180. neutron_constants.RESOURCE_REQUEST: {
  1181. "resources": {
  1182. orc.NET_BW_IGR_KILOBIT_PER_SEC: 10000,
  1183. orc.NET_BW_EGR_KILOBIT_PER_SEC: 10000},
  1184. "required": ["CUSTOM_PHYSNET2", "CUSTOM_VNIC_TYPE_MACVTAP"]
  1185. },
  1186. 'binding:vnic_type': 'macvtap',
  1187. }
  1188. nw_info = [{
  1189. "profile": {},
  1190. "ovs_interfaceid": "b71f1699-42be-4515-930a-f3ef01f94aa7",
  1191. "preserve_on_delete": False,
  1192. "network": {
  1193. "bridge": "br-int",
  1194. "subnets": [{
  1195. "ips": [{
  1196. "meta": {},
  1197. "version": 4,
  1198. "type": "fixed",
  1199. "floating_ips": [],
  1200. "address": "10.0.0.4"
  1201. }],
  1202. "version": 4,
  1203. "meta": {},
  1204. "dns": [],
  1205. "routes": [],
  1206. "cidr": "10.0.0.0/26",
  1207. "gateway": {
  1208. "meta": {},
  1209. "version": 4,
  1210. "type": "gateway",
  1211. "address": "10.0.0.1"
  1212. }
  1213. }],
  1214. "meta": {
  1215. "injected": False,
  1216. "tenant_id": tenant_id,
  1217. "mtu": 1500
  1218. },
  1219. "id": "e1882e38-38c2-4239-ade7-35d644cb963a",
  1220. "label": "public"
  1221. },
  1222. "devname": "tapb71f1699-42",
  1223. "vnic_type": "normal",
  1224. "qbh_params": None,
  1225. "meta": {},
  1226. "details": {
  1227. "port_filter": True,
  1228. "ovs_hybrid_plug": True
  1229. },
  1230. "address": "fa:16:3e:47:94:4a",
  1231. "active": True,
  1232. "type": "ovs",
  1233. "id": "b71f1699-42be-4515-930a-f3ef01f94aa7",
  1234. "qbg_params": None
  1235. }]
  1236. def __init__(self, test):
  1237. super(NeutronFixture, self).__init__()
  1238. self.test = test
  1239. # The fixture allows port update so we need to deepcopy the class
  1240. # variables to avoid test case interference.
  1241. self._ports = {
  1242. # NOTE(gibi)The port_with_sriov_resource_request cannot be added
  1243. # globally in this fixture as it adds a second network that makes
  1244. # auto allocation based test to fail due to ambiguous networks.
  1245. NeutronFixture.port_1['id']: copy.deepcopy(NeutronFixture.port_1),
  1246. NeutronFixture.port_with_resource_request['id']:
  1247. copy.deepcopy(NeutronFixture.port_with_resource_request)
  1248. }
  1249. # The fixture does not allow network update so we don't have to
  1250. # deepcopy here
  1251. self._networks = {
  1252. NeutronFixture.network_1['id']: NeutronFixture.network_1
  1253. }
  1254. # The fixture does not allow network update so we don't have to
  1255. # deepcopy here
  1256. self._subnets = {
  1257. NeutronFixture.subnet_1['id']: NeutronFixture.subnet_1
  1258. }
  1259. def setUp(self):
  1260. super(NeutronFixture, self).setUp()
  1261. self.test.stub_out(
  1262. 'nova.network.neutronv2.api.API.setup_networks_on_host',
  1263. lambda *args, **kwargs: None)
  1264. self.test.stub_out(
  1265. 'nova.network.neutronv2.api.API.migrate_instance_start',
  1266. lambda *args, **kwargs: None)
  1267. self.test.stub_out(
  1268. 'nova.network.neutronv2.api.API.add_fixed_ip_to_instance',
  1269. lambda *args, **kwargs: network_model.NetworkInfo.hydrate(
  1270. NeutronFixture.nw_info))
  1271. self.test.stub_out(
  1272. 'nova.network.neutronv2.api.API.remove_fixed_ip_from_instance',
  1273. lambda *args, **kwargs: network_model.NetworkInfo.hydrate(
  1274. NeutronFixture.nw_info))
  1275. # TODO(stephenfin): This is a rubbish mock. We should instead mock the
  1276. # methods for the neutron client, like 'list_security_groups'
  1277. self.test.stub_out(
  1278. 'nova.network.security_group.neutron_driver.SecurityGroupAPI.'
  1279. 'get_instances_security_groups_bindings',
  1280. self.fake_get_instance_security_group_bindings)
  1281. # Stub out port binding APIs which go through a KSA client Adapter
  1282. # rather than python-neutronclient.
  1283. self.test.stub_out(
  1284. 'nova.network.neutronv2.api._get_ksa_client',
  1285. lambda *args, **kwargs: mock.Mock(
  1286. spec=ksa_adap.Adapter))
  1287. self.test.stub_out(
  1288. 'nova.network.neutronv2.api.API._create_port_binding',
  1289. self.fake_create_port_binding)
  1290. self.test.stub_out(
  1291. 'nova.network.neutronv2.api.API._delete_port_binding',
  1292. self.fake_delete_port_binding)
  1293. self.test.stub_out('nova.network.neutronv2.api.get_client',
  1294. lambda *args, **kwargs: self)
  1295. @staticmethod
  1296. def fake_create_port_binding(context, client, port_id, data):
  1297. # TODO(mriedem): Make this smarter by keeping track of our bindings
  1298. # per port so we can reflect the status accurately.
  1299. return fake_requests.FakeResponse(200, content=jsonutils.dumps(data))
  1300. @staticmethod
  1301. def fake_delete_port_binding(context, client, port_id, host):
  1302. # TODO(mriedem): Make this smarter by keeping track of our bindings
  1303. # per port so we can reflect the status accurately.
  1304. return fake_requests.FakeResponse(204)
  1305. @staticmethod
  1306. def fake_get_instance_security_group_bindings(
  1307. _, context, servers, detailed=False):
  1308. if detailed:
  1309. raise Exception('We do not support detailed view')
  1310. return {server['id']: [{'name': 'default'}] for server in servers}
  1311. def _get_first_id_match(self, id, list):
  1312. filtered_list = [p for p in list if p['id'] == id]
  1313. if len(filtered_list) > 0:
  1314. return filtered_list[0]
  1315. else:
  1316. return None
  1317. def list_extensions(self, *args, **kwargs):
  1318. return {
  1319. 'extensions': [
  1320. {
  1321. # Copied from neutron-lib portbindings_extended.py
  1322. "updated": "2017-07-17T10:00:00-00:00",
  1323. "name": neutron_constants.PORT_BINDING_EXTENDED,
  1324. "links": [],
  1325. "alias": "binding-extended",
  1326. "description": "Expose port bindings of a virtual port to "
  1327. "external application"
  1328. }
  1329. ]
  1330. }
  1331. def show_port(self, port_id, **_params):
  1332. if port_id not in self._ports:
  1333. raise exception.PortNotFound(port_id=port_id)
  1334. return {'port': copy.deepcopy(self._ports[port_id])}
  1335. def delete_port(self, port_id, **_params):
  1336. if port_id in self._ports:
  1337. del self._ports[port_id]
  1338. def show_network(self, network_id, **_params):
  1339. if network_id not in self._networks:
  1340. raise neutron_client_exc.NetworkNotFoundClient()
  1341. return {'network': copy.deepcopy(self._networks[network_id])}
  1342. def list_networks(self, retrieve_all=True, **_params):
  1343. networks = self._networks.values()
  1344. if 'id' in _params:
  1345. networks = [x for x in networks if x['id'] in _params['id']]
  1346. _params.pop('id')
  1347. networks = [n for n in networks
  1348. if all(n.get(opt) == _params[opt] for opt in _params)]
  1349. return {'networks': copy.deepcopy(networks)}
  1350. def list_ports(self, retrieve_all=True, **_params):
  1351. # If 'fields' is passed we need to strip that out since it will mess
  1352. # up the filtering as 'fields' is not a filter parameter.
  1353. _params.pop('fields', None)
  1354. ports = [p for p in self._ports.values()
  1355. if all(p.get(opt) == _params[opt] for opt in _params)]
  1356. return {'ports': copy.deepcopy(ports)}
  1357. def list_subnets(self, retrieve_all=True, **_params):
  1358. # NOTE(gibi): The fixture does not support filtering for subnets
  1359. return {'subnets': copy.deepcopy(list(self._subnets.values()))}
  1360. def list_floatingips(self, retrieve_all=True, **_params):
  1361. return {'floatingips': []}
  1362. def create_port(self, body=None):
  1363. # Note(gibi): Some of the test expects that a pre-defined port is
  1364. # created. This is port_2. So if that port is not created yet then
  1365. # that is the one created here.
  1366. if NeutronFixture.port_2['id'] not in self._ports:
  1367. new_port = copy.deepcopy(NeutronFixture.port_2)
  1368. else:
  1369. # If port_2 is already created then create a new port based on
  1370. # the request body, the port_2 as a template, and assign new
  1371. # port_id and mac_address for the new port
  1372. new_port = copy.deepcopy(body)
  1373. new_port.update(copy.deepcopy(NeutronFixture.port_2))
  1374. # we need truly random uuids instead of named sentinels as some
  1375. # tests needs more than 3 ports
  1376. new_port.update({
  1377. 'id': str(uuidutils.generate_uuid()),
  1378. 'mac_address': '00:' + ':'.join(
  1379. ['%02x' % random.randint(0, 255) for _ in range(5)]),
  1380. })
  1381. self._ports[new_port['id']] = new_port
  1382. # we need to copy again what we return as nova might modify the
  1383. # returned port locally and we don't want that it effects the port in
  1384. # the self._ports dict.
  1385. return {'port': copy.deepcopy(new_port)}
  1386. def update_port(self, port_id, body=None):
  1387. port = self._ports[port_id]
  1388. # We need to deepcopy here as well as the body can have a nested dict
  1389. # which can be modified by the caller after this update_port call
  1390. port.update(copy.deepcopy(body['port']))
  1391. return {'port': copy.deepcopy(port)}
  1392. def show_quota(self, project_id):
  1393. # unlimited quota
  1394. return {'quota': {'port': -1}}
  1395. class _NoopConductor(object):
  1396. def __getattr__(self, key):
  1397. def _noop_rpc(*args, **kwargs):
  1398. return None
  1399. return _noop_rpc
  1400. class NoopConductorFixture(fixtures.Fixture):
  1401. """Stub out the conductor API to do nothing"""
  1402. def setUp(self):
  1403. super(NoopConductorFixture, self).setUp()
  1404. self.useFixture(fixtures.MonkeyPatch(
  1405. 'nova.conductor.ComputeTaskAPI', _NoopConductor))
  1406. self.useFixture(fixtures.MonkeyPatch(
  1407. 'nova.conductor.API', _NoopConductor))
  1408. class EventReporterStub(fixtures.Fixture):
  1409. def setUp(self):
  1410. super(EventReporterStub, self).setUp()
  1411. self.useFixture(fixtures.MonkeyPatch(
  1412. 'nova.compute.utils.EventReporter',
  1413. lambda *args, **kwargs: mock.MagicMock()))
  1414. class CinderFixture(fixtures.Fixture):
  1415. """A fixture to volume operations with the new Cinder attach/detach API"""
  1416. # the default project_id in OSAPIFixtures
  1417. tenant_id = '6f70656e737461636b20342065766572'
  1418. SWAP_OLD_VOL = 'a07f71dc-8151-4e7d-a0cc-cd24a3f11113'
  1419. SWAP_NEW_VOL = '227cc671-f30b-4488-96fd-7d0bf13648d8'
  1420. SWAP_ERR_OLD_VOL = '828419fa-3efb-4533-b458-4267ca5fe9b1'
  1421. SWAP_ERR_NEW_VOL = '9c6d9c2d-7a8f-4c80-938d-3bf062b8d489'
  1422. SWAP_ERR_ATTACH_ID = '4a3cd440-b9c2-11e1-afa6-0800200c9a66'
  1423. MULTIATTACH_VOL = '4757d51f-54eb-4442-8684-3399a6431f67'
  1424. # This represents a bootable image-backed volume to test
  1425. # boot-from-volume scenarios.
  1426. IMAGE_BACKED_VOL = '6ca404f3-d844-4169-bb96-bc792f37de98'
  1427. # This represents a bootable image-backed volume with required traits
  1428. # as part of volume image metadata
  1429. IMAGE_WITH_TRAITS_BACKED_VOL = '6194fc02-c60e-4a01-a8e5-600798208b5f'
  1430. def __init__(self, test, az='nova'):
  1431. """Initialize this instance of the CinderFixture.
  1432. :param test: The TestCase using this fixture.
  1433. :param az: The availability zone to return in volume GET responses.
  1434. Defaults to "nova" since that is the default we would see
  1435. from Cinder's storage_availability_zone config option.
  1436. """
  1437. super(CinderFixture, self).__init__()
  1438. self.test = test
  1439. self.swap_volume_instance_uuid = None
  1440. self.swap_volume_instance_error_uuid = None
  1441. self.attachment_error_id = None
  1442. self.az = az
  1443. # A dict, keyed by volume id, to a dict, keyed by attachment id,
  1444. # with keys:
  1445. # - id: the attachment id
  1446. # - instance_uuid: uuid of the instance attached to the volume
  1447. # - connector: host connector dict; None if not connected
  1448. # Note that a volume can have multiple attachments even without
  1449. # multi-attach, as some flows create a blank 'reservation' attachment
  1450. # before deleting another attachment. However, a non-multiattach volume
  1451. # can only have at most one attachment with a host connector at a time.
  1452. self.volume_to_attachment = collections.defaultdict(dict)
  1453. def volume_ids_for_instance(self, instance_uuid):
  1454. for volume_id, attachments in self.volume_to_attachment.items():
  1455. for attachment in attachments.values():
  1456. if attachment['instance_uuid'] == instance_uuid:
  1457. # we might have multiple volumes attached to this instance
  1458. # so yield rather than return
  1459. yield volume_id
  1460. break
  1461. def setUp(self):
  1462. super(CinderFixture, self).setUp()
  1463. def fake_get(self_api, context, volume_id, microversion=None):
  1464. # Check for the special swap volumes.
  1465. attachments = self.volume_to_attachment[volume_id]
  1466. if volume_id in (self.SWAP_OLD_VOL,
  1467. self.SWAP_ERR_OLD_VOL):
  1468. volume = {
  1469. 'status': 'available',
  1470. 'display_name': 'TEST1',
  1471. 'attach_status': 'detached',
  1472. 'id': volume_id,
  1473. 'multiattach': False,
  1474. 'size': 1
  1475. }
  1476. if ((self.swap_volume_instance_uuid and
  1477. volume_id == self.SWAP_OLD_VOL) or
  1478. (self.swap_volume_instance_error_uuid and
  1479. volume_id == self.SWAP_ERR_OLD_VOL)):
  1480. instance_uuid = (self.swap_volume_instance_uuid
  1481. if volume_id == self.SWAP_OLD_VOL
  1482. else self.swap_volume_instance_error_uuid)
  1483. if attachments:
  1484. attachment = list(attachments.values())[0]
  1485. volume.update({
  1486. 'status': 'in-use',
  1487. 'attachments': {
  1488. instance_uuid: {
  1489. 'mountpoint': '/dev/vdb',
  1490. 'attachment_id': attachment['id']
  1491. }
  1492. },
  1493. 'attach_status': 'attached'
  1494. })
  1495. return volume
  1496. # Check to see if the volume is attached.
  1497. if attachments:
  1498. # The volume is attached.
  1499. attachment = list(attachments.values())[0]
  1500. volume = {
  1501. 'status': 'in-use',
  1502. 'display_name': volume_id,
  1503. 'attach_status': 'attached',
  1504. 'id': volume_id,
  1505. 'multiattach': volume_id == self.MULTIATTACH_VOL,
  1506. 'size': 1,
  1507. 'attachments': {
  1508. attachment['instance_uuid']: {
  1509. 'attachment_id': attachment['id'],
  1510. 'mountpoint': '/dev/vdb'
  1511. }
  1512. }
  1513. }
  1514. else:
  1515. # This is a test that does not care about the actual details.
  1516. volume = {
  1517. 'status': 'available',
  1518. 'display_name': 'TEST2',
  1519. 'attach_status': 'detached',
  1520. 'id': volume_id,
  1521. 'multiattach': volume_id == self.MULTIATTACH_VOL,
  1522. 'size': 1
  1523. }
  1524. if 'availability_zone' not in volume:
  1525. volume['availability_zone'] = self.az
  1526. # Check for our special image-backed volume.
  1527. if volume_id in (self.IMAGE_BACKED_VOL,
  1528. self.IMAGE_WITH_TRAITS_BACKED_VOL):
  1529. # Make it a bootable volume.
  1530. volume['bootable'] = True
  1531. if volume_id == self.IMAGE_BACKED_VOL:
  1532. # Add the image_id metadata.
  1533. volume['volume_image_metadata'] = {
  1534. # There would normally be more image metadata in here.
  1535. 'image_id': '155d900f-4e14-4e4c-a73d-069cbf4541e6'
  1536. }
  1537. elif volume_id == self.IMAGE_WITH_TRAITS_BACKED_VOL:
  1538. # Add the image_id metadata with traits.
  1539. volume['volume_image_metadata'] = {
  1540. 'image_id': '155d900f-4e14-4e4c-a73d-069cbf4541e6',
  1541. "trait:HW_CPU_X86_SGX": "required",
  1542. }
  1543. return volume
  1544. def fake_migrate_volume_completion(_self, context, old_volume_id,
  1545. new_volume_id, error):
  1546. return {'save_volume_id': new_volume_id}
  1547. def _find_attachment(attachment_id):
  1548. """Find attachment corresponding to ``attachment_id``.
  1549. Returns:
  1550. A tuple of the volume ID, an attachment dict
  1551. for the given attachment ID, and a dict (keyed by attachment
  1552. id) of attachment dicts for the volume.
  1553. """
  1554. for volume_id, attachments in self.volume_to_attachment.items():
  1555. for attachment in attachments.values():
  1556. if attachment_id == attachment['id']:
  1557. return volume_id, attachment, attachments
  1558. raise exception.VolumeAttachmentNotFound(
  1559. attachment_id=attachment_id)
  1560. def fake_attachment_create(_self, context, volume_id, instance_uuid,
  1561. connector=None, mountpoint=None):
  1562. attachment_id = uuidutils.generate_uuid()
  1563. if self.attachment_error_id is not None:
  1564. attachment_id = self.attachment_error_id
  1565. attachment = {'id': attachment_id, 'connection_info': {'data': {}}}
  1566. self.volume_to_attachment[volume_id][attachment_id] = {
  1567. 'id': attachment_id,
  1568. 'instance_uuid': instance_uuid,
  1569. 'connector': connector}
  1570. LOG.info('Created attachment %s for volume %s. Total '
  1571. 'attachments for volume: %d', attachment_id, volume_id,
  1572. len(self.volume_to_attachment[volume_id]))
  1573. return attachment
  1574. def fake_attachment_delete(_self, context, attachment_id):
  1575. # 'attachment' is a tuple defining a attachment-instance mapping
  1576. volume_id, attachment, attachments = (
  1577. _find_attachment(attachment_id))
  1578. del attachments[attachment_id]
  1579. LOG.info('Deleted attachment %s for volume %s. Total attachments '
  1580. 'for volume: %d', attachment_id, volume_id,
  1581. len(attachments))
  1582. def fake_attachment_update(_self, context, attachment_id, connector,
  1583. mountpoint=None):
  1584. # Ensure the attachment exists
  1585. volume_id, attachment, attachments = (
  1586. _find_attachment(attachment_id))
  1587. # Cinder will only allow one "connected" attachment per
  1588. # non-multiattach volume at a time.
  1589. if volume_id != self.MULTIATTACH_VOL:
  1590. for _attachment in attachments.values():
  1591. if _attachment['connector'] is not None:
  1592. raise exception.InvalidInput(
  1593. 'Volume %s is already connected with attachment '
  1594. '%s on host %s' % (volume_id, _attachment['id'],
  1595. _attachment['connector'].get('host')))
  1596. attachment['connector'] = connector
  1597. LOG.info('Updating volume attachment: %s', attachment_id)
  1598. attachment_ref = {'driver_volume_type': 'fake_type',
  1599. 'id': attachment_id,
  1600. 'connection_info': {'data':
  1601. {'foo': 'bar',
  1602. 'target_lun': '1'}}}
  1603. if attachment_id == self.SWAP_ERR_ATTACH_ID:
  1604. # This intentionally triggers a TypeError for the
  1605. # instance.volume_swap.error versioned notification tests.
  1606. attachment_ref = {'connection_info': ()}
  1607. return attachment_ref
  1608. def fake_attachment_get(_self, context, attachment_id):
  1609. # Ensure the attachment exists
  1610. _find_attachment(attachment_id)
  1611. attachment_ref = {'driver_volume_type': 'fake_type',
  1612. 'id': attachment_id,
  1613. 'connection_info': {'data':
  1614. {'foo': 'bar',
  1615. 'target_lun': '1'}}}
  1616. return attachment_ref
  1617. def fake_get_all_volume_types(*args, **kwargs):
  1618. return [{
  1619. # This is used in the 2.67 API sample test.
  1620. 'id': '5f9204ec-3e94-4f27-9beb-fe7bb73b6eb9',
  1621. 'name': 'lvm-1'
  1622. }]
  1623. def fake_attachment_complete(_self, _context, attachment_id):
  1624. # Ensure the attachment exists
  1625. _find_attachment(attachment_id)
  1626. LOG.info('Completing volume attachment: %s', attachment_id)
  1627. self.test.stub_out('nova.volume.cinder.API.attachment_create',
  1628. fake_attachment_create)
  1629. self.test.stub_out('nova.volume.cinder.API.attachment_delete',
  1630. fake_attachment_delete)
  1631. self.test.stub_out('nova.volume.cinder.API.attachment_update',
  1632. fake_attachment_update)
  1633. self.test.stub_out('nova.volume.cinder.API.attachment_complete',
  1634. fake_attachment_complete)
  1635. self.test.stub_out('nova.volume.cinder.API.attachment_get',
  1636. fake_attachment_get)
  1637. self.test.stub_out('nova.volume.cinder.API.begin_detaching',
  1638. lambda *args, **kwargs: None)
  1639. self.test.stub_out('nova.volume.cinder.API.get',
  1640. fake_get)
  1641. self.test.stub_out(
  1642. 'nova.volume.cinder.API.migrate_volume_completion',
  1643. fake_migrate_volume_completion)
  1644. self.test.stub_out('nova.volume.cinder.API.roll_detaching',
  1645. lambda *args, **kwargs: None)
  1646. self.test.stub_out('nova.volume.cinder.is_microversion_supported',
  1647. lambda ctxt, microversion: None)
  1648. self.test.stub_out('nova.volume.cinder.API.check_attached',
  1649. lambda *args, **kwargs: None)
  1650. self.test.stub_out('nova.volume.cinder.API.get_all_volume_types',
  1651. fake_get_all_volume_types)
  1652. class UnHelperfulClientChannel(privsep_daemon._ClientChannel):
  1653. def __init__(self, context):
  1654. raise Exception('You have attempted to start a privsep helper. '
  1655. 'This is not allowed in the gate, and '
  1656. 'indicates a failure to have mocked your tests.')
  1657. class PrivsepNoHelperFixture(fixtures.Fixture):
  1658. """A fixture to catch failures to mock privsep's rootwrap helper.
  1659. If you fail to mock away a privsep'd method in a unit test, then
  1660. you may well end up accidentally running the privsep rootwrap
  1661. helper. This will fail in the gate, but it fails in a way which
  1662. doesn't identify which test is missing a mock. Instead, we
  1663. raise an exception so that you at least know where you've missed
  1664. something.
  1665. """
  1666. def setUp(self):
  1667. super(PrivsepNoHelperFixture, self).setUp()
  1668. self.useFixture(fixtures.MonkeyPatch(
  1669. 'oslo_privsep.daemon.RootwrapClientChannel',
  1670. UnHelperfulClientChannel))
  1671. class PrivsepFixture(fixtures.Fixture):
  1672. """Disable real privsep checking so we can test the guts of methods
  1673. decorated with sys_admin_pctxt.
  1674. """
  1675. def setUp(self):
  1676. super(PrivsepFixture, self).setUp()
  1677. self.useFixture(fixtures.MockPatchObject(
  1678. nova.privsep.sys_admin_pctxt, 'client_mode', False))
  1679. class NoopQuotaDriverFixture(fixtures.Fixture):
  1680. """A fixture to run tests using the NoopQuotaDriver.
  1681. We can't simply set self.flags to the NoopQuotaDriver in tests to use the
  1682. NoopQuotaDriver because the QuotaEngine object is global. Concurrently
  1683. running tests will fail intermittently because they might get the
  1684. NoopQuotaDriver globally when they expected the default DbQuotaDriver
  1685. behavior. So instead, we can patch the _driver property of the QuotaEngine
  1686. class on a per-test basis.
  1687. """
  1688. def setUp(self):
  1689. super(NoopQuotaDriverFixture, self).setUp()
  1690. self.useFixture(fixtures.MonkeyPatch('nova.quota.QuotaEngine._driver',
  1691. nova_quota.NoopQuotaDriver()))
  1692. # Set the config option just so that code checking for the presence of
  1693. # the NoopQuotaDriver setting will see it as expected.
  1694. # For some reason, this does *not* work when TestCase.flags is used.
  1695. # When using self.flags, the concurrent test failures returned.
  1696. CONF.set_override('driver', 'nova.quota.NoopQuotaDriver', 'quota')
  1697. self.addCleanup(CONF.clear_override, 'driver', 'quota')
  1698. class DownCellFixture(fixtures.Fixture):
  1699. """A fixture to simulate when a cell is down either due to error or timeout
  1700. This fixture will stub out the scatter_gather_cells routine and target_cell
  1701. used in various cells-related API operations like listing/showing server
  1702. details to return a ``oslo_db.exception.DBError`` per cell in the results.
  1703. Therefore it is best used with a test scenario like this:
  1704. 1. Create a server successfully.
  1705. 2. Using the fixture, list/show servers. Depending on the microversion
  1706. used, the API should either return minimal results or by default skip
  1707. the results from down cells.
  1708. Example usage::
  1709. with nova_fixtures.DownCellFixture():
  1710. # List servers with down cells.
  1711. self.api.get_servers()
  1712. # Show a server in a down cell.
  1713. self.api.get_server(server['id'])
  1714. # List services with down cells.
  1715. self.admin_api.api_get('/os-services')
  1716. """
  1717. def __init__(self, down_cell_mappings=None):
  1718. self.down_cell_mappings = down_cell_mappings
  1719. def setUp(self):
  1720. super(DownCellFixture, self).setUp()
  1721. def stub_scatter_gather_cells(ctxt, cell_mappings, timeout, fn, *args,
  1722. **kwargs):
  1723. # Return a dict with an entry per cell mapping where the results
  1724. # are some kind of exception.
  1725. up_cell_mappings = objects.CellMappingList()
  1726. if not self.down_cell_mappings:
  1727. # User has not passed any down cells explicitly, so all cells
  1728. # are considered as down cells.
  1729. self.down_cell_mappings = cell_mappings
  1730. else:
  1731. # User has passed down cell mappings, so the rest of the cells
  1732. # should be up meaning we should return the right results.
  1733. # We assume that down cells will be a subset of the
  1734. # cell_mappings.
  1735. down_cell_uuids = [cell.uuid
  1736. for cell in self.down_cell_mappings]
  1737. up_cell_mappings.objects = [cell
  1738. for cell in cell_mappings
  1739. if cell.uuid not in down_cell_uuids]
  1740. def wrap(cell_uuid, thing):
  1741. # We should embed the cell_uuid into the context before
  1742. # wrapping since its used to calcualte the cells_timed_out and
  1743. # cells_failed properties in the object.
  1744. ctxt.cell_uuid = cell_uuid
  1745. return multi_cell_list.RecordWrapper(ctxt, sort_ctx, thing)
  1746. if fn is multi_cell_list.query_wrapper:
  1747. # If the function called through scatter-gather utility is the
  1748. # multi_cell_list.query_wrapper, we should wrap the exception
  1749. # object into the multi_cell_list.RecordWrapper. This is
  1750. # because unlike the other functions where the exception object
  1751. # is returned directly, the query_wrapper wraps this into the
  1752. # RecordWrapper object format. So if we do not wrap it will
  1753. # blow up at the point of generating results from heapq further
  1754. # down the stack.
  1755. sort_ctx = multi_cell_list.RecordSortContext([], [])
  1756. ret1 = {
  1757. cell_mapping.uuid: [wrap(cell_mapping.uuid,
  1758. db_exc.DBError())]
  1759. for cell_mapping in self.down_cell_mappings
  1760. }
  1761. else:
  1762. ret1 = {
  1763. cell_mapping.uuid: db_exc.DBError()
  1764. for cell_mapping in self.down_cell_mappings
  1765. }
  1766. ret2 = {}
  1767. for cell in up_cell_mappings:
  1768. ctxt.cell_uuid = cell.uuid
  1769. cctxt = context.RequestContext.from_dict(ctxt.to_dict())
  1770. context.set_target_cell(cctxt, cell)
  1771. result = fn(cctxt, *args, **kwargs)
  1772. ret2[cell.uuid] = result
  1773. return dict(list(ret1.items()) + list(ret2.items()))
  1774. @contextmanager
  1775. def stub_target_cell(ctxt, cell_mapping):
  1776. # This is to give the freedom to simulate down cells for each
  1777. # individual cell targeted function calls.
  1778. if not self.down_cell_mappings:
  1779. # User has not passed any down cells explicitly, so all cells
  1780. # are considered as down cells.
  1781. self.down_cell_mappings = [cell_mapping]
  1782. raise db_exc.DBError()
  1783. else:
  1784. # if down_cell_mappings are passed, then check if this cell
  1785. # is down or up.
  1786. down_cell_uuids = [cell.uuid
  1787. for cell in self.down_cell_mappings]
  1788. if cell_mapping.uuid in down_cell_uuids:
  1789. # its a down cell raise the exception straight away
  1790. raise db_exc.DBError()
  1791. else:
  1792. # its an up cell, so yield its context
  1793. cctxt = context.RequestContext.from_dict(ctxt.to_dict())
  1794. context.set_target_cell(cctxt, cell_mapping)
  1795. yield cctxt
  1796. self.useFixture(fixtures.MonkeyPatch(
  1797. 'nova.context.scatter_gather_cells', stub_scatter_gather_cells))
  1798. self.useFixture(fixtures.MonkeyPatch(
  1799. 'nova.context.target_cell', stub_target_cell))
  1800. class AvailabilityZoneFixture(fixtures.Fixture):
  1801. """Fixture to stub out the nova.availability_zones module
  1802. The list of ``zones`` provided to the fixture are what get returned from
  1803. ``get_availability_zones``.
  1804. ``get_instance_availability_zone`` will return the availability_zone
  1805. requested when creating a server otherwise the instance.availabilty_zone
  1806. or default_availability_zone is returned.
  1807. """
  1808. def __init__(self, zones):
  1809. self.zones = zones
  1810. def setUp(self):
  1811. super(AvailabilityZoneFixture, self).setUp()
  1812. def fake_get_availability_zones(
  1813. ctxt, hostapi, get_only_available=False,
  1814. with_hosts=False, enabled_services=None):
  1815. # A 2-item tuple is returned if get_only_available=False.
  1816. if not get_only_available:
  1817. return self.zones, []
  1818. return self.zones
  1819. self.useFixture(fixtures.MonkeyPatch(
  1820. 'nova.availability_zones.get_availability_zones',
  1821. fake_get_availability_zones))
  1822. def fake_get_instance_availability_zone(ctxt, instance):
  1823. # If the server was created with a specific AZ, return it.
  1824. reqspec = objects.RequestSpec.get_by_instance_uuid(
  1825. ctxt, instance.uuid)
  1826. requested_az = reqspec.availability_zone
  1827. if requested_az:
  1828. return requested_az
  1829. # Otherwise return the instance.availability_zone if set else
  1830. # the default AZ.
  1831. return instance.availability_zone or CONF.default_availability_zone
  1832. self.useFixture(fixtures.MonkeyPatch(
  1833. 'nova.availability_zones.get_instance_availability_zone',
  1834. fake_get_instance_availability_zone))
  1835. class KSAFixture(fixtures.Fixture):
  1836. """Lets us initialize an openstack.connection.Connection by stubbing the
  1837. auth plugin.
  1838. """
  1839. def setUp(self):
  1840. super(KSAFixture, self).setUp()
  1841. self.mock_load_auth = self.useFixture(fixtures.MockPatch(
  1842. 'keystoneauth1.loading.load_auth_from_conf_options')).mock
  1843. self.mock_load_sess = self.useFixture(fixtures.MockPatch(
  1844. 'keystoneauth1.loading.load_session_from_conf_options')).mock
  1845. # For convenience, an attribute for the "Session" itself
  1846. self.mock_session = self.mock_load_sess.return_value
  1847. class OpenStackSDKFixture(fixtures.Fixture):
  1848. # This satisfies tests that happen to run through get_sdk_adapter but don't
  1849. # care about the adapter itself (default mocks are fine).
  1850. # TODO(efried): Get rid of this and use fixtures from openstacksdk once
  1851. # https://storyboard.openstack.org/#!/story/2005475 is resolved.
  1852. def setUp(self):
  1853. super(OpenStackSDKFixture, self).setUp()
  1854. self.useFixture(fixtures.MockPatch(
  1855. 'openstack.proxy.Proxy.get_endpoint'))
  1856. real_make_proxy = service_description.ServiceDescription._make_proxy
  1857. _stub_service_types = {'placement'}
  1858. def fake_make_proxy(self, instance):
  1859. if self.service_type in _stub_service_types:
  1860. return instance.config.get_session_client(
  1861. self.service_type,
  1862. allow_version_hack=True,
  1863. )
  1864. return real_make_proxy(self, instance)
  1865. self.useFixture(fixtures.MockPatchObject(
  1866. service_description.ServiceDescription, '_make_proxy',
  1867. fake_make_proxy))
  1868. class HostNameWeigher(weights.BaseHostWeigher):
  1869. """Weigher to make the scheduler host selection deterministic.
  1870. Note that this weigher is supposed to be used via
  1871. HostNameWeigherFixture and will fail to instantiate if used without that
  1872. fixture.
  1873. """
  1874. def __init__(self):
  1875. self.weights = self.get_weights()
  1876. def get_weights(self):
  1877. raise NotImplemented()
  1878. def _weigh_object(self, host_state, weight_properties):
  1879. # Any unspecified host gets no weight.
  1880. return self.weights.get(host_state.host, 0)
  1881. class HostNameWeigherFixture(fixtures.Fixture):
  1882. """Fixture to make the scheduler host selection deterministic.
  1883. Note that this fixture needs to be used before the scheduler service is
  1884. started as it changes the scheduler configuration.
  1885. """
  1886. def __init__(self, weights=None):
  1887. """Create the fixture
  1888. :param weights: A dict of weights keyed by host names. Defaulted to
  1889. {'host1': 100, 'host2': 50, 'host3': 10}"
  1890. """
  1891. if weights:
  1892. self.weights = weights
  1893. else:
  1894. # default weights good for most of the functional tests
  1895. self.weights = {'host1': 100, 'host2': 50, 'host3': 10}
  1896. def setUp(self):
  1897. super(HostNameWeigherFixture, self).setUp()
  1898. # Make sure that when the scheduler instantiate the HostNameWeigher it
  1899. # is initialized with the weights that is configured in this fixture
  1900. self.useFixture(fixtures.MockPatchObject(
  1901. HostNameWeigher, 'get_weights', return_value=self.weights))
  1902. # Make sure that the scheduler loads the HostNameWeigher and only that
  1903. self.useFixture(ConfPatcher(
  1904. weight_classes=[__name__ + '.HostNameWeigher'],
  1905. group='filter_scheduler'))