def inspect_memory_usage(self, instance, duration=None): instance_name = util.instance_name(instance) domain = self._get_domain_not_shut_off_or_raise(instance) try: memory_stats = domain.memoryStats() if (memory_stats and memory_stats.get('available') and memory_stats.get('unused')): memory_used = (memory_stats.get('available') - memory_stats.get('unused')) # Stat provided from libvirt is in KB, converting it to MB. memory_used = memory_used / units.Ki return virt_inspector.MemoryUsageStats(usage=memory_used) else: msg = _('Failed to inspect memory usage of instance ' '<name=%(name)s, id=%(id)s>, ' 'can not get info from libvirt.') % { 'name': instance_name, 'id': instance.id } raise virt_inspector.InstanceNoDataException(msg) # memoryStats might launch an exception if the method is not supported # by the underlying hypervisor being used by libvirt. except libvirt.libvirtError as e: msg = _('Failed to inspect memory usage of %(instance_uuid)s, ' 'can not get info from libvirt: %(error)s') % { 'instance_uuid': instance.id, 'error': e } raise virt_inspector.NoDataException(msg)
def test_get_samples(self): next_value = iter(( virt_inspector.MemoryUsageStats(usage=1.0), virt_inspector.MemoryUsageStats(usage=2.0), virt_inspector.InstanceNoDataException(), virt_inspector.InstanceShutOffException(), )) def inspect_memory_usage(instance, duration): value = next(next_value) if isinstance(value, virt_inspector.MemoryUsageStats): return value else: raise value self.inspector.inspect_memory_usage = mock.Mock( side_effect=inspect_memory_usage) mgr = manager.AgentManager(0, self.CONF) pollster = memory.MemoryUsagePollster(self.CONF) @mock.patch('ceilometer.compute.pollsters.memory.LOG') def _verify_memory_metering(expected_count, expected_memory_mb, expected_warnings, mylog): samples = list(pollster.get_samples(mgr, {}, [self.instance])) self.assertEqual(expected_count, len(samples)) if expected_count > 0: self.assertEqual(set(['memory.usage']), set([s.name for s in samples])) self.assertEqual(expected_memory_mb, samples[0].volume) else: self.assertEqual(expected_warnings, mylog.warning.call_count) self.assertEqual(0, mylog.exception.call_count) _verify_memory_metering(1, 1.0, 0) _verify_memory_metering(1, 2.0, 0) _verify_memory_metering(0, 0, 1) _verify_memory_metering(0, 0, 0)