def test_storage_volume_get_all_by_filters_throw_exception(self): self.mock.StubOutWithMock(session, 'get_session') session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.storage_volume_get_all_by_filters, self.admin_context, {}, 'id', 'asc')
def test_vm_host_delete_throw_exception(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.vm_host_delete_by_ids, get_admin_context(), ['test1'])
def test_subnet_delete_exc(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.subnet_delete_by_ids, self.admin_context, ['test1'])
def test_vm_host_get_all_by_filters_throw_exception(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.vm_host_get_all_by_filters, get_admin_context(), {}, 'id', 'asc')
def test_virtual_switch_get_all_by_filters_throw_exception(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, api.virtual_switch_get_all_by_filters, self.admin_context, {}, 'id', 'asc')
def test_storage_delete_throw_exception(self): self.mock.StubOutWithMock(session, 'get_session') session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.storage_volume_delete_by_ids, self.admin_context, ['test1'])
def test_get_all_volume_types(self): """Ensures that all volume types can be retrieved""" session = get_session() total_volume_types = session.query(models.VolumeTypes).\ count() vol_types = volume_types.get_all_types(self.ctxt) self.assertEqual(total_volume_types, len(vol_types))
def subscription_extend(context, subscription_id, datetime_to): print "[DB]", subscription_id, "extend to", datetime_to session = get_session() with session.begin(): session.query(models.Subscription).\ filter_by(id=subscription_id).\ update({'expires_at': datetime_to})
def index(self, req): # This has been revised so that it is less coupled with # the implementation of the Servers API, which is in flux # KLUDGE to make this extension working with different nova branches # in a soon future there will be only: if hasattr(self, '_items'): servers = self._items(req, is_detail=True) else: servers = self._get_servers(req, is_detail=True) # The 'id' attribute here is actually the uuid of the server ids = [server['id'] for server in servers['servers']] context = req.environ['nova.context'] session = get_session() instance_map = {} for i in session.query(models.Instance).filter( models.Instance.uuid.in_(ids)).all(): instance_map[i.uuid] = i for s in servers['servers']: s['attrs'] = self._build_extended_attributes(instance_map[s['id']]) return servers
def setUp(self): super(QuantumNovaTestCase, self).setUp() # Create an actual project -- with this we will touch more of # the code in QuantumManager (related to fetching networks, etc) for x in ["fake_project1", "fake_project2"]: values = {"id": x, "name": x} project = db.project_create(context.get_admin_context(), values) self.net_man = quantum_manager.QuantumManager( ipam_lib="nova.network.quantum.nova_ipam_lib", q_conn=FakeQuantumClientConnection() ) # Tests seem to create some networks by default, which # we don't want. So we delete them. ctx = context.RequestContext("user1", "fake_project1").elevated() for n in db.network_get_all(ctx): db.network_delete_safe(ctx, n["id"]) # Other unit tests (e.g., test_compute.py) have a nasty # habit of of creating fixed IPs and not cleaning up, which # can confuse these tests, so we remove all existing fixed # ips before starting. session = get_session() result = session.query(models.FixedIp).all() with session.begin(): for fip_ref in result: session.delete(fip_ref)
def test_get_all_instance_types(self): """Ensures that all instance types can be retrieved""" session = get_session() total_instance_types = session.query(models.InstanceTypes).\ count() inst_types = instance_types.get_all_types() self.assertEqual(total_instance_types, len(inst_types))
def subscription_extend(context, subscription_id, datetime_to): session = get_session() with session.begin(): session.query(models.Subscription).\ filter_by(id=subscription_id).\ update({'expires_at': datetime_to, 'updated_at': literal_column('updated_at')})
def subscription_error(context, subscription_id): session = get_session() with session.begin(): session.query(models.Subscription).\ filter_by(id=subscription_id).\ update({'status': 'error', 'updated_at': literal_column('updated_at')})
def index(self, req): # This has been revised so that it is less coupled with # the implementation of the Servers API, which is in flux try: # KLUDGE to make this extension working with different nova branches # in a soon future there will be only: # servers = self._get_servers(req, is_detail=True) servers = getattr(self,'_get_servers',self._items)(req, is_detail=True) except exception.Invalid as err: return exc.HTTPBadRequest(explanation=str(err)) ids = [server['id'] for server in servers['servers']] context = req.environ['nova.context'] session = get_session() instance_map = {} for i in session.query(models.Instance).filter( models.Instance.id.in_(ids)).all(): instance_map[i.id] = i for s in servers['servers']: s['attrs'] = self._build_extended_attributes(instance_map[s['id']]) return servers
def setUp(self): super(InstanceTypeTestCase, self).setUp() session = get_session() max_flavorid = session.query(models.InstanceTypes).\ order_by("flavorid desc").\ first() self.flavorid = max_flavorid["flavorid"] + 1 self.name = str(int(time.time()))
def item_type_destroy(context, item_type_id): session = get_session() with session.begin(): session.query(models.ItemType).\ filter_by(id=item_type_id).\ update({'deleted': True, 'deleted_at': utils.utcnow(), 'updated_at': literal_column('updated_at')})
def purchase_destroy(context, purchase_id): session = get_session() with session.begin(): session.query(models.Purchase).\ filter_by(id=purchase_id).\ update({'deleted': True, 'deleted_at': utils.utcnow(), 'updated_at': literal_column('updated_at')})
def purchase_get_all_by_subscription_and_timeframe(context, subscription_id, datetime_from, datetime_to): session = get_session() return session.query(models.Purchase).\ filter_by(subscription_id=subscription_id).\ filter(models.Purchase.created_at >= datetime_from).\ filter(models.Purchase.created_at < datetime_to).\ all()
def region_destroy(context, region_id): session = get_session() with session.begin(): session.query(models.Region).\ filter_by(id=region_id).\ update({'deleted': True, 'deleted_at': utils.utcnow(), 'updated_at': literal_column('updated_at')})
def subscription_delete(context, subscription_id): session = get_session() with session.begin(): session.query(models.Subscription).\ filter_by(id=subscription_id).\ update({'deleted': True, 'deleted_at': utils.utcnow(), 'status': 'deleted', 'updated_at': literal_column('updated_at')})
def host_capability_destroy(context, host_capability_id): """Marks specific host as deleted""" session = get_session() with session.begin(): session.query(HostCapability).\ filter_by(id=host_capability_id).\ update({'deleted': True, 'deleted_at': timeutils.utcnow(), 'updated_at': literal_column('updated_at')})
def get_host_capability_by_id(context, host_id): """Returns a dict describing specific host_id""" session = get_session() result = model_query(context, HostCapability, session=session).filter_by(id=host_id).first() if not result: raise exception.NotFound("No host capability found by id %s" % id) return result
def subscription_terminate(context, subscription_id): session = get_session() with session.begin(): session.query(models.Subscription).filter_by(id=subscription_id).update( { "deleted": True, "deleted_at": utils.utcnow(), "status": "terminated", "updated_at": literal_column("updated_at"), } )
def save(self, session=None): """Save this object.""" if not session: session = get_session() session.add(self) try: session.flush() except IntegrityError, e: if str(e).endswith('is not unique'): raise exception.Duplicate(str(e)) else: raise
def test_execute_wrapper(self): _session = session.get_session() with _session.begin(): for i in [10, 20]: tbl = TmpTable() tbl.update({'foo': i}) tbl.save(session=_session) method = _session.query(TmpTable).\ filter_by(foo=10).\ update self.assertRaises(exception.DBDuplicateEntry, method, {'foo': 20})
def service_get_all_compute(context): topic = 'compute' session = get_session() result = session.query(models.Service).\ options(joinedload('compute_node')).\ filter_by(deleted=False).\ filter_by(topic=topic).\ all() if not result: raise exception.ComputeHostNotFound(host=host) return result
def save(self, session=None): """Save this object.""" if not session: session = get_session() # NOTE(boris-42): This part of code should be look like: # sesssion.add(self) # session.flush() # But there is a bug in sqlalchemy and eventlet that # raises NoneType exception if there is no running # transaction and rollback is called. As long as # sqlalchemy has this bug we have to create transaction # explicity. with session.begin(subtransactions=True): session.add(self) session.flush()
def setUp(self): super(QuantumNovaTestCase, self).setUp() self.flags(quantum_use_dhcp=True) self.flags(l3_lib="nova.network.l3.LinuxNetL3") linuxdrv = "nova.network.linux_net.LinuxOVSInterfaceDriver" self.flags(linuxnet_interface_driver=linuxdrv) fc = fake_client.FakeClient(LOG) qc = quantum_connection.QuantumClientConnection(client=fc) self.net_man = quantum_manager.QuantumManager( ipam_lib="nova.network.quantum.nova_ipam_lib", q_conn=qc) def func(arg1, arg2): pass def func2(arg1, arg2, arg3): pass def func1(arg1): pass self.net_man.driver.update_dhcp_hostfile_with_text = func self.net_man.driver.restart_dhcp = func2 self.net_man.driver.kill_dhcp = func1 # Tests seem to create some networks by default, which # we don't want. So we delete them. ctx = context.RequestContext('user1', 'fake_project1').elevated() for n in db.network_get_all(ctx): db.network_delete_safe(ctx, n['id']) # Other unit tests (e.g., test_compute.py) have a nasty # habit of of creating fixed IPs and not cleaning up, which # can confuse these tests, so we remove all existing fixed # ips before starting. session = sql_session.get_session() result = session.query(models.FixedIp).all() with session.begin(): for fip_ref in result: session.delete(fip_ref) self.net_man.init_host()
def host_capability_create(context, values): session = get_session() with session.begin(): host_capability_ref = HostCapability() try: host_capability_get_by_host(context, values['host'], session) # if the host already exists, then return an empty host object return host_capability_ref except exception.NotFound: pass values["deleted"] = False try: host_capability_ref.update(values) host_capability_ref.save(session=session) except Exception, e: raise exception.DBError(e) return host_capability_ref
def setUp(self): super(QuantumNovaTestCase, self).setUp() self.flags(quantum_use_dhcp=True) self.flags(l3_lib="nova.network.l3.LinuxNetL3") linuxdrv = "nova.network.linux_net.LinuxOVSInterfaceDriver" self.flags(linuxnet_interface_driver=linuxdrv) fc = fake_client.FakeClient(LOG) qc = quantum_connection.QuantumClientConnection(client=fc) self.net_man = quantum_manager.QuantumManager( ipam_lib="nova.network.quantum.nova_ipam_lib", q_conn=qc) def func(arg1, arg2): pass def func2(arg1, arg2, arg3): pass def func1(arg1): pass self.net_man.driver.update_dhcp_hostfile_with_text = func self.net_man.driver.restart_dhcp = func2 self.net_man.driver.kill_dhcp = func1 # Tests seem to create some networks by default, which # we don't want. So we delete them. ctx = context.RequestContext('user1', 'fake_project1').elevated() for n in db.network_get_all(ctx): db.network_delete_safe(ctx, n['id']) # Other unit tests (e.g., test_compute.py) have a nasty # habit of of creating fixed IPs and not cleaning up, which # can confuse these tests, so we remove all existing fixed # ips before starting. session = get_session() result = session.query(models.FixedIp).all() with session.begin(): for fip_ref in result: session.delete(fip_ref) self.net_man.init_host()
def _associate(self, req, network_id, body): context = req.environ['nova.context'] authorize(context) if not body: raise exc.HTTPUnprocessableEntity() project_id = body["associate"] LOG.debug(_("Associating network %s with project %s") % (network_id, project_id)) session = get_session() count = session.query(models.Network).filter_by( uuid=network_id, project_id=None).update({ "project_id": project_id }) if count: return webob.Response(status_int=202) raise exc.HTTPBadRequest( explanation=_("Cannot associate network %s with project %s") % (network_id, project_id))
def _associate(self, req, network_id, body): context = req.environ['nova.context'] authorize(context) if not body: raise exc.HTTPUnprocessableEntity() project_id = body["associate"] LOG.debug( _("Associating network %s with project %s") % (network_id, project_id)) session = get_session() count = session.query(models.Network).filter_by( uuid=network_id, project_id=None).update({"project_id": project_id}) if count: return webob.Response(status_int=202) raise exc.HTTPBadRequest( explanation=_("Cannot associate network %s with project %s") % (network_id, project_id))
def setUp(self): super(QuantumNovaTestCase, self).setUp() self.net_man = quantum_manager.QuantumManager( ipam_lib="nova.network.quantum.nova_ipam_lib", q_conn=FakeQuantumClientConnection()) # Tests seem to create some networks by default, which # we don't want. So we delete them. ctx = context.RequestContext('user1', 'fake_project1').elevated() for n in db.network_get_all(ctx): db.network_delete_safe(ctx, n['id']) # Other unit tests (e.g., test_compute.py) have a nasty # habit of of creating fixed IPs and not cleaning up, which # can confuse these tests, so we remove all existing fixed # ips before starting. session = get_session() result = session.query(models.FixedIp).all() with session.begin(): for fip_ref in result: session.delete(fip_ref)
def index(self, req): # This has been revised so that it is less coupled with # the implementation of the Servers API, which is in flux # KLUDGE to make this extension working with different nova branches # in a soon future there will be only: if hasattr(self, '_items'): servers = self._items(req, is_detail=True) else: servers = self._get_servers(req, is_detail=True) ids = [server['id'] for server in servers['servers']] context = req.environ['nova.context'] session = get_session() instance_map = {} for i in session.query(models.Instance).filter( models.Instance.id.in_(ids)).all(): instance_map[i.id] = i for s in servers['servers']: s['attrs'] = self._build_extended_attributes(instance_map[s['id']]) return servers
def test_virtual_switch_delete_throw_exception(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, api.virtual_switch_delete_by_ids, self.admin_context, ['test1'])
def test_virtual_switch_get_all_by_filters_throw_exception(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, api.virtual_switch_get_all_by_filters, self.admin_context, {}, 'id', 'asc')
def test_vm_get_all_by_filters_throw_exception(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.vm_get_all_by_filters, get_admin_context(), {}, 'id', 'asc')
def setUp(self): super(CommonDbApiTestCase, self).setUp() self.mock = mox.Mox() self.admin_context = get_admin_context() self.db_session = nova_session.get_session()
def setUp(self): super(InstanceTypeTestCase, self).setUp() session = get_session()
def test_get_all_instance_types(self): """Ensures that all instance types can be retrieved""" session = sql_session.get_session() total_instance_types = session.query(models.InstanceTypes).count() inst_types = instance_types.get_all_types() self.assertEqual(total_instance_types, len(inst_types))
def subscription_destroy(context, subscription_id): session = get_session() with session.begin(): session.query(models.Subscription).\ filter_by(id=subscription_id).\ update({'status': 'deleting'})
def subscription_error(context, subscription_id): session = get_session() with session.begin(): session.query(models.Subscription).\ filter_by(id=subscription_id).\ update({'status': 'error'})
def test_storage_get_all_throw_exception(self): self.mock.StubOutWithMock(session, 'get_session') session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.storage_volume_get_all, self.admin_context)
def test_vm_host_delete_throw_exception(self): self.mock.StubOutWithMock(db_session, 'get_session') db_session.get_session().AndRaise(Exception()) self.mock.ReplayAll() self.assertRaises(Exception, healthnmon_db_api.vm_host_delete_by_ids, get_admin_context(), ['test1'])
def save(self, session=None): """Save this object.""" if not session: session = get_session() session.add(self) session.flush()
def _usage_for_period(self, context, period_start, period_stop, tenant_id=None): fields = ['id', 'image_ref', 'project_id', 'user_id', 'vcpus', 'hostname', 'display_name', 'host', 'vm_state', 'instance_type_id', 'launched_at', 'terminated_at'] tenant_clause = '' if tenant_id: tenant_clause = " and project_id='%s'" % tenant_id connection = get_session().connection() rows = connection.execute("select %s from instances where \ (terminated_at is NULL or terminated_at > '%s') \ and (launched_at < '%s') %s" %\ (','.join(fields), period_start.isoformat(' '),\ period_stop.isoformat(' '), tenant_clause )).fetchall() rval = {} flavors = {} for row in rows: o = {} for i in range(len(fields)): o[fields[i]] = row[i] o['hours'] = self._hours_for(o, period_start, period_stop) flavor_type = o['instance_type_id'] try: flavors[flavor_type] = \ db.instance_type_get_by_id(context, flavor_type) except AttributeError: # The most recent version of nova renamed this function flavors[flavor_type] = \ db.instance_type_get(context, flavor_type) except exception.InstanceTypeNotFound: # can't bill if there is no instance type continue flavor = flavors[flavor_type] o['name'] = o['display_name'] del(o['display_name']) o['ram_size'] = flavor['memory_mb'] o['disk_size'] = flavor['local_gb'] o['tenant_id'] = o['project_id'] del(o['project_id']) o['flavor'] = flavor['name'] del(o['instance_type_id']) o['started_at'] = o['launched_at'] del(o['launched_at']) o['ended_at'] = o['terminated_at'] del(o['terminated_at']) if o['ended_at']: o['state'] = 'terminated' else: o['state'] = o['vm_state'] del(o['vm_state']) now = datetime.utcnow() if o['state'] == 'terminated': delta = self._parse_datetime(o['ended_at'])\ - self._parse_datetime(o['started_at']) else: delta = now - self._parse_datetime(o['started_at']) o['uptime'] = delta.days * 24 * 60 + delta.seconds if not o['tenant_id'] in rval: summary = {} summary['tenant_id'] = o['tenant_id'] summary['instances'] = [] summary['total_disk_usage'] = 0 summary['total_cpu_usage'] = 0 summary['total_ram_usage'] = 0 summary['total_active_ram_size'] = 0 summary['total_active_disk_size'] = 0 summary['total_active_vcpus'] = 0 summary['total_active_instances'] = 0 summary['total_hours'] = 0 summary['begin'] = period_start summary['stop'] = period_stop rval[o['tenant_id']] = summary rval[o['tenant_id']]['total_disk_usage'] += o['disk_size'] * o['hours'] rval[o['tenant_id']]['total_cpu_usage'] += o['vcpus'] * o['hours'] rval[o['tenant_id']]['total_ram_usage'] += o['ram_size'] * o['hours'] if o['state'] is not 'terminated': rval[o['tenant_id']]['total_active_ram_size'] += o['ram_size'] rval[o['tenant_id']]['total_active_vcpus'] += o['vcpus'] rval[o['tenant_id']]['total_active_disk_size'] += o['disk_size'] rval[o['tenant_id']]['total_active_instances'] += 1 rval[o['tenant_id']]['total_hours'] += o['hours'] rval[o['tenant_id']]['instances'].append(o) return rval.values()
def test_get_all_volume_types(self): """Ensures that all volume types can be retrieved""" session = sql_session.get_session() total_volume_types = session.query(models.VolumeTypes).count() vol_types = volume_types.get_all_types(self.ctxt) self.assertEqual(total_volume_types, len(vol_types))
def subscription_extend(context, subscription_id, datetime_to): session = get_session() with session.begin(): session.query(models.Subscription).\ filter_by(id=subscription_id).\ update({'expires_at': datetime_to})