diff --git a/nova/context.py b/nova/context.py index f66fcfd1e493..f97f54c4b20b 100644 --- a/nova/context.py +++ b/nova/context.py @@ -286,7 +286,25 @@ class RequestContext(context.RequestContext): return "" % self.to_dict() +def get_context(): + """A helper method to get a blank context. + + Note that overwrite is False here so this context will not update the + greenthread-local stored context that is used when logging. + """ + return RequestContext(user_id=None, + project_id=None, + is_admin=False, + overwrite=False) + + def get_admin_context(read_deleted="no"): + # NOTE(alaski): This method should only be used when an admin context is + # necessary for the entirety of the context lifetime. If that's not the + # case please use get_context(), or create the RequestContext manually, and + # use context.elevated() where necessary. Some periodic tasks may use + # get_admin_context so that their database calls are not filtered on + # project_id. return RequestContext(user_id=None, project_id=None, is_admin=True, diff --git a/nova/tests/unit/test_context.py b/nova/tests/unit/test_context.py index f406ccf5c0e3..5b6e7ecafa48 100644 --- a/nova/tests/unit/test_context.py +++ b/nova/tests/unit/test_context.py @@ -146,6 +146,15 @@ class ContextTestCase(test.NoDBTestCase): overwrite=False) self.assertIs(o_context.get_current(), ctx1) + def test_get_context_no_overwrite(self): + # If there is already a context in the cache creating another context + # should not overwrite it. + ctx1 = context.RequestContext('111', + '222', + overwrite=True) + context.get_context() + self.assertIs(ctx1, o_context.get_current()) + def test_admin_no_overwrite(self): # If there is already a context in the cache creating an admin # context will not overwrite it. @@ -290,3 +299,9 @@ class ContextTestCase(test.NoDBTestCase): with context.target_cell(ctxt, mapping): self.assertEqual(ctxt.db_connection, mock.sentinel.cm) self.assertEqual(mock.sentinel.db_conn, ctxt.db_connection) + + def test_get_context(self): + ctxt = context.get_context() + self.assertIsNone(ctxt.user_id) + self.assertIsNone(ctxt.project_id) + self.assertFalse(ctxt.is_admin)