Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_serialization(self):
def check(ret):
if json is not None:
json.loads(json.dumps(ret))
a = pickle.dumps(ret)
b = pickle.loads(a)
self.assertEqual(ret, b)
check(psutil.Process().as_dict())
check(psutil.virtual_memory())
check(psutil.swap_memory())
check(psutil.cpu_times())
check(psutil.cpu_times_percent(interval=0))
check(psutil.net_io_counters())
if LINUX and not os.path.exists('/proc/diskstats'):
pass
else:
if not APPVEYOR:
check(psutil.disk_io_counters())
check(psutil.disk_partitions())
check(psutil.disk_usage(os.getcwd()))
check(psutil.users())
self.assertEqual(nt[2], nt.packets_sent)
self.assertEqual(nt[3], nt.packets_recv)
self.assertEqual(nt[4], nt.errin)
self.assertEqual(nt[5], nt.errout)
self.assertEqual(nt[6], nt.dropin)
self.assertEqual(nt[7], nt.dropout)
assert nt.bytes_sent >= 0, nt
assert nt.bytes_recv >= 0, nt
assert nt.packets_sent >= 0, nt
assert nt.packets_recv >= 0, nt
assert nt.errin >= 0, nt
assert nt.errout >= 0, nt
assert nt.dropin >= 0, nt
assert nt.dropout >= 0, nt
ret = psutil.net_io_counters(pernic=False)
check_ntuple(ret)
ret = psutil.net_io_counters(pernic=True)
self.assertNotEqual(ret, [])
for key in ret:
self.assertTrue(key)
self.assertIsInstance(key, str)
check_ntuple(ret[key])
print(str(e))
sys.exit()
except ibmiotf.UnsupportedAuthenticationMethod as e:
print(str(e))
sys.exit()
except ibmiotf.ConnectionException as e:
print(str(e))
sys.exit()
print("(Press Ctrl+C to disconnect)")
# Take initial reading
psutil.cpu_percent(percpu=False)
ioBefore_ts = time.time()
ioBefore = psutil.net_io_counters()
# Initiate DM action to update the geo location of the device, but don't wait (async) for it to complete
client.setLocation(longitude=100, latitude=78, accuracy=100)
# Initiate DM action to set error codes to 1, wait for it to be completed (sync) and then clear all error codes
client.setErrorCode(1).wait()
client.clearErrorCodes()
# Initiate DM action to add log, wait for it to be completed (sync) and then clear all error codes
client.addLog(msg="test",data="testdata",sensitivity=0).wait()
client.clearLog()
while True:
time.sleep(interval)
ioAfter_ts = time.time()
ioAfter = psutil.net_io_counters()
def networkStats():
logger.debug('Obtaining netstats')
nics = {}
for nic, addrs in psutil.net_if_addrs().items():
for addr in addrs:
try:
socket.inet_aton(addr.address)
nics.update({"net_"+str(nic): addr.address})
except Exception as ex:
# Dont bother, it just means ip address is ipv6
# or invalid
pass
recd_bytes = str(psutil.net_io_counters().bytes_recv).replace('L', '')
tx_bytes = str(psutil.net_io_counters().bytes_sent).replace('L', '')
network_stats = {
'net_rx_packets': recd_bytes,
'net_tx_packets': tx_bytes,
}
network_stats.update(nics)
return network_stats
def network_activity():
old_value = old_value2 = 0
while True:
new_value = psutil.net_io_counters().bytes_recv
new_value2 = psutil.net_io_counters().bytes_sent
if old_value:
rx = round((new_value - old_value) / 1024.0, 2)
tx = round((new_value2 - old_value2) / 1024.0, 2)
rx_tx = round((new_value - old_value + new_value2 - old_value2) / 1024.0, 2)
break
old_value = new_value
old_value2 = new_value2
time.sleep(1)
return [tx, rx, rx_tx]
def update(self):
"""Function to update the entire class information."""
self.cpu["percentage"] = psutil.cpu_percent(interval=0.7)
self.boot = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(
"%Y-%m-%d %H:%M:%S")
virtual_memory = psutil.virtual_memory()
self.memory["used"] = virtual_memory.used
self.memory["free"] = virtual_memory.free
self.memory["cached"] = virtual_memory.cached
net_io_counters = psutil.net_io_counters()
self.network["packet_sent"] = net_io_counters.packets_sent
self.network["packet_recv"] = net_io_counters.packets_recv
disk_usage = psutil.disk_usage('/')
self.disk["total"] = int(disk_usage.total/1024)
self.disk["used"] = int(disk_usage.used/1024)
self.disk["free"] = int(disk_usage.free/1024)
self.timestamp = time.time()
def get_variants(self):
return psutil.net_io_counters(pernic=True).keys()
def get_interface_node():
if_children = [make_if_nodes(x) for x in list(ps.net_io_counters(pernic=True).keys())]
return ParentNode('interface', children=if_children)
def _get_net_stats(self):
'''This will form network IO stats for the entire system'''
try:
try:
io = psutil.net_io_counters()
except AttributeError:
io = psutil.network_io_counters()
for i in range(len(io)):
title = "Component/Network/IO/%s[bytes]" % io._fields[i]
val = io[i] - self.buffers[io._fields[i]]
self.buffers[io._fields[i]] = io[i]
self.metric_data[title] = val
except Exception, e:
self.logger.exception(e)
pass
def get_network_info():
masks = list()
MaskResult = namedtuple('MaskResult', ['name', 'recv', 'sent', 'slug'])
for mask, data in OrderedDict(psutil.net_io_counters(pernic=True)).items():
if data.packets_recv > 0 or data.packets_sent > 0:
res = MaskResult(mask, SysInformation.pretty_size(data.packets_recv), SysInformation.pretty_size(data.packets_sent),
SysInformation.slugify(mask))
masks.append(res)
return masks