Commit 6eb84817 authored by Bryton Lacquement's avatar Bryton Lacquement 🚪

wip

parent 5ceae36b
...@@ -100,6 +100,7 @@ def main(): ...@@ -100,6 +100,7 @@ def main():
process_handler = subprocess.Popen(argument_list, process_handler = subprocess.Popen(argument_list,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True,
) )
stdout, stderr = process_handler.communicate() stdout, stderr = process_handler.communicate()
...@@ -108,7 +109,8 @@ def main(): ...@@ -108,7 +109,8 @@ def main():
print(stderr) print(stderr)
return 1 return 1
with open(output_file, 'r') as f: # Check that output_file is a readable file.
with open(output_file, 'r'):
print(base_url + '/ApacheDex-%s.html' % today) print(base_url + '/ApacheDex-%s.html' % today)
return 0 return 0
......
...@@ -81,9 +81,9 @@ class EqueueServer(socketserver.ThreadingUnixStreamServer): ...@@ -81,9 +81,9 @@ class EqueueServer(socketserver.ThreadingUnixStreamServer):
def __init__(self, *args, **kw): def __init__(self, *args, **kw):
self.options = kw.pop('equeue_options') self.options = kw.pop('equeue_options')
socketserver.ThreadingUnixStreamServer.__init__(self, super(EqueueServer, self).__init__(self,
RequestHandlerClass=None, RequestHandlerClass=None,
*args, **kw) *args, **kw)
# Equeue Specific elements # Equeue Specific elements
self.setLogger(self.options.logfile[0], self.options.loglevel[0]) self.setLogger(self.options.logfile[0], self.options.loglevel[0])
self.setDB(self.options.database[0]) self.setDB(self.options.database[0])
......
...@@ -27,8 +27,6 @@ ...@@ -27,8 +27,6 @@
# #
############################################################################## ##############################################################################
from six.moves import zip
import sqlite3 import sqlite3
import os import os
import pwd import pwd
...@@ -82,10 +80,8 @@ class ResourceCollect: ...@@ -82,10 +80,8 @@ class ResourceCollect:
table="sqlite_master", table="sqlite_master",
columns='name', columns='name',
where="type='table' AND name='%s'" % name) where="type='table' AND name='%s'" % name)
table_exists_result = list(zip(*check_result_cursor)) r = check_result_cursor.fetchone()
if not len(table_exists_result) or table_exists_result[0][0] is None: return r and r[0] is not None
return False
return True
def getPartitionCPULoadAverage(self, partition_id, date_scope): def getPartitionCPULoadAverage(self, partition_id, date_scope):
return self.consumption_utils.getPartitionCPULoadAverage(partition_id, date_scope) return self.consumption_utils.getPartitionCPULoadAverage(partition_id, date_scope)
...@@ -161,38 +157,35 @@ class ResourceCollect: ...@@ -161,38 +157,35 @@ class ResourceCollect:
query_result = self.db.select('user', date_scope, colums, query_result = self.db.select('user', date_scope, colums,
where="partition='%s' and (time between '%s' and '%s') %s" % where="partition='%s' and (time between '%s' and '%s') %s" %
(partition_id, min_time, max_time, where)) (partition_id, min_time, max_time, where))
result_list = list(zip(*query_result)) result = query_result.fetchone()
process_dict = memory_dict = io_dict = {} process_dict = {'total_process': result[0],
if len(result_list): 'cpu_percent': round((result[1] or 0), 2),
result = result_list 'cpu_time': round((result[2] or 0)/(60.0), 2),
process_dict = {'total_process': result[0][0], 'cpu_num_threads': round((result[3] or 0), 2),
'cpu_percent': round((result[1][0] or 0), 2), 'date': '%s %s' % (date_scope, min_time)
'cpu_time': round((result[2][0] or 0)/(60.0), 2), }
'cpu_num_threads': round((result[3][0] or 0), 2), memory_dict = {'memory_percent': round((result[4] or 0), 2),
'date': '%s %s' % (date_scope, min_time) 'memory_rss': round((result[5] or 0)/(1024*1024.0), 2),
} 'date': '%s %s' % (date_scope, min_time)
memory_dict = {'memory_percent': round((result[4][0] or 0), 2), }
'memory_rss': round((result[5][0] or 0)/(1024*1024.0), 2), io_dict = {'io_rw_counter': round((result[6] or 0), 2),
'date': '%s %s' % (date_scope, min_time) 'io_cycles_counter': round((result[7] or 0), 2),
} 'disk_used': 0,
io_dict = {'io_rw_counter': round((result[6][0] or 0), 2), 'date': '%s %s' % (date_scope, min_time)
'io_cycles_counter': round((result[7][0] or 0), 2), }
'disk_used': 0, if self.has_table('folder'):
'date': '%s %s' % (date_scope, min_time) disk_result_cursor = self.db.select(
} "folder", date_scope,
if self.has_table('folder'): columns="SUM(disk_used)",
disk_result_cursor = self.db.select( where="partition='%s' and (time between '%s' and '%s') %s" % (
"folder", date_scope, partition_id, min_time, max_time, where
columns="SUM(disk_used)",
where="partition='%s' and (time between '%s' and '%s') %s" % (
partition_id, min_time, max_time, where
)
) )
)
disk_used_sum = list(zip(*disk_result_cursor))
if len(disk_used_sum) and disk_used_sum[0][0] is not None: disk_used_sum, = disk_result_cursor.fetchone()
io_dict['disk_used'] = round(disk_used_sum[0][0]/1024.0, 2) if disk_used_sum is not None:
io_dict['disk_used'] = round(disk_used_sum/1024.0, 2)
self.db.close() self.db.close()
return (process_dict, memory_dict, io_dict) return (process_dict, memory_dict, io_dict)
......
...@@ -133,7 +133,7 @@ class Monitoring(object): ...@@ -133,7 +133,7 @@ class Monitoring(object):
with open(config_list[2]) as cfile: with open(config_list[2]) as cfile:
param_value = cfile.read() param_value = cfile.read()
except OSError as e: except OSError as e:
print('Cannot read file %s, Error is: %s' % (config_list[2], str(e))) print('Cannot read file %s, Error is: %s' % (config_list[2], e))
pass pass
else: else:
param_value = "" param_value = ""
...@@ -180,7 +180,7 @@ class Monitoring(object): ...@@ -180,7 +180,7 @@ class Monitoring(object):
) )
configuration_list.append(parameter) configuration_list.append(parameter)
except OSError as e: except OSError as e:
print('Cannot read file at %s, Error is: %s' % (old_cors_file, str(e))) print('Cannot read file at %s, Error is: %s' % (old_cors_file, e))
pass pass
return configuration_list return configuration_list
...@@ -213,9 +213,9 @@ class Monitoring(object): ...@@ -213,9 +213,9 @@ class Monitoring(object):
# XXX - working here with public url # XXX - working here with public url
if hasattr(ssl, '_create_unverified_context'): if hasattr(ssl, '_create_unverified_context'):
context = ssl._create_unverified_context() context = ssl._create_unverified_context()
response = urllib.urlopen(url, context=context, timeout=timeout) response = urllib.request.urlopen(url, context=context, timeout=timeout)
else: else:
response = urllib.urlopen(url, timeout=timeout) response = urllib.request.urlopen(url, timeout=timeout)
except urllib.HTTPError: except urllib.HTTPError:
print("ERROR: Failed to get Monitor configuration file at %s " % url) print("ERROR: Failed to get Monitor configuration file at %s " % url)
except socket.timeout as e: except socket.timeout as e:
......
...@@ -16,8 +16,6 @@ import datetime ...@@ -16,8 +16,6 @@ import datetime
from slapos.collect.db import Database from slapos.collect.db import Database
from six.moves import zip
def getMemoryInfo(database, time, date): def getMemoryInfo(database, time, date):
memory_info = {} memory_info = {}
...@@ -25,21 +23,21 @@ def getMemoryInfo(database, time, date): ...@@ -25,21 +23,21 @@ def getMemoryInfo(database, time, date):
try: try:
database.connect() database.connect()
query_result = database.select("computer", date, "memory_size", limit=1) query_result = database.select("computer", date, "memory_size", limit=1)
result = list(zip(*query_result)) r = query_result.fetchone()
if not result or not result[0][0]: if not r or not r[0]:
return (None, "couldn't fetch total memory, collectordb is empty?") return (None, "couldn't fetch total memory, collectordb is empty?")
memory_info['total'] = int(result[0][0]) # in byte memory_info['total'] = int(r[0]) # in byte
# fetch free and used memory # fetch free and used memory
where_query = "time between '%s:00' and '%s:30' " % (time, time) where_query = "time between '%s:00' and '%s:30' " % (time, time)
query_result = database.select("system", date, "memory_free, memory_used", where=where_query) query_result = database.select("system", date, "memory_free, memory_used", where=where_query)
result = list(zip(*query_result)) r = query_result.fetchone()
if not result or not result[0][0]: if not r or not r[0]:
return (None, "couldn't fetch free memory") return (None, "couldn't fetch free memory")
memory_info['free'] = int(result[0][0]) # in byte memory_info['free'] = int(r[0]) # in byte
if not result or not result[1][0]: if not r or not r[1]:
return (None, "couldn't fetch used memory") return (None, "couldn't fetch used memory")
memory_info['used'] = int(result[1][0]) # in byte memory_info['used'] = int(r[1]) # in byte
finally: finally:
database.close() database.close()
......
...@@ -7,7 +7,7 @@ import gzip ...@@ -7,7 +7,7 @@ import gzip
import argparse import argparse
import os import os
r = re.compile("^(\[[^\]]+\]) (\[[^\]]+\]) (.*)$") r = re.compile(b"^(\[[^\]]+\]) (\[[^\]]+\]) (.*)$")
def test(log_file, maximum_delay): def test(log_file, maximum_delay):
error_amount = 0 error_amount = 0
...@@ -19,11 +19,11 @@ def test(log_file, maximum_delay): ...@@ -19,11 +19,11 @@ def test(log_file, maximum_delay):
# file don't exist, nothing to check # file don't exist, nothing to check
return "OK" return "OK"
with open(log_file) as f: with open(log_file, "rb") as f:
f.seek(0, 2) f.seek(0, 2)
block_end_byte = f.tell() block_end_byte = f.tell()
f.seek(block_end_byte - min(block_end_byte, 4096), 0) f.seek(-min(block_end_byte, 4096), 1)
data = f.read() data = f.read()
for line in reversed(data.splitlines()): for line in reversed(data.splitlines()):
...@@ -50,7 +50,7 @@ def test(log_file, maximum_delay): ...@@ -50,7 +50,7 @@ def test(log_file, maximum_delay):
# no result in the latest hour # no result in the latest hour
break break
if level != "[error]": if level != b"[error]":
continue continue
# Classify the types of errors # Classify the types of errors
......
...@@ -561,7 +561,7 @@ class QemuQMPWrapper(object): ...@@ -561,7 +561,7 @@ class QemuQMPWrapper(object):
if (mem_size / slot_size) > slot_amount: if (mem_size / slot_size) > slot_amount:
raise ValueError("No enough slots available to add %sMB of RAM" % mem_size) raise ValueError("No enough slots available to add %sMB of RAM" % mem_size)
current_size = current_size // (1024 * 1024) current_size //= (1024 * 1024)
if current_size == mem_size: if current_size == mem_size:
print("Hotplug Memory size is up to date.") print("Hotplug Memory size is up to date.")
return return
......
...@@ -98,7 +98,8 @@ def shred(options): ...@@ -98,7 +98,8 @@ def shred(options):
arg_list.extend(getFileList(options.file_list, options.check_exist)) arg_list.extend(getFileList(options.file_list, options.check_exist))
pshred = subprocess.Popen(arg_list, stdout=subprocess.PIPE, pshred = subprocess.Popen(arg_list, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) stderr=subprocess.STDOUT,
universal_newlines=True)
result, stderr = pshred.communicate() result, stderr = pshred.communicate()
if pshred.returncode is None: if pshred.returncode is None:
pshred.kill() pshred.kill()
......
...@@ -106,7 +106,7 @@ echo "htpasswd $@" > %s/monitor-htpasswd ...@@ -106,7 +106,7 @@ echo "htpasswd $@" > %s/monitor-htpasswd
for config in config_json: for config in config_json:
if config["key"]: if config["key"]:
self.assertTrue(config["key"] in config_parameter_json) self.assertIn(config["key"], config_parameter_json)
parameter = config_parameter_json[config["key"]] parameter = config_parameter_json[config["key"]]
else: else:
continue continue
......
...@@ -58,32 +58,32 @@ class TestSecureDelete(unittest.TestCase): ...@@ -58,32 +58,32 @@ class TestSecureDelete(unittest.TestCase):
passes = 2 + 1 # Option -z is used, plus one more pass passes = 2 + 1 # Option -z is used, plus one more pass
result = shred(options) result = shred(options)
self.assertFalse(os.path.exists(self.remove_file)) self.assertFalse(os.path.exists(self.remove_file))
self.assertTrue(b"pass %d/%d" % (passes, passes) in result) self.assertIn("pass %d/%d" % (passes, passes), result)
self.assertTrue(b"%s: removed" % os.path.basename(self.remove_file).encode('utf-8') in result) self.assertIn("%s: removed" % os.path.basename(self.remove_file), result)
def test_secure_remove_file_keep_file(self): def test_secure_remove_file_keep_file(self):
options = getAgumentParser().parse_args(['-n', '2', '-z', '--file', self.remove_file]) options = getAgumentParser().parse_args(['-n', '2', '-z', '--file', self.remove_file])
passes = 2 + 1 # Option -z is used, plus one more pass passes = 2 + 1 # Option -z is used, plus one more pass
result = shred(options) result = shred(options)
self.assertTrue(os.path.exists(self.remove_file)) self.assertTrue(os.path.exists(self.remove_file))
self.assertTrue(b"pass %d/%d" % (passes, passes) in result) self.assertIn("pass %d/%d" % (passes, passes), result)
self.assertFalse(b"%s: removed" % os.path.basename(self.remove_file).encode('utf-8') in result) self.assertNotIn("%s: removed" % os.path.basename(self.remove_file), result)
def test_secure_remove_file_non_zero(self): def test_secure_remove_file_non_zero(self):
options = getAgumentParser().parse_args(['-n', '2', '-u', '--file', self.remove_file]) options = getAgumentParser().parse_args(['-n', '2', '-u', '--file', self.remove_file])
passes = 2 passes = 2
result = shred(options) result = shred(options)
self.assertFalse(os.path.exists(self.remove_file)) self.assertFalse(os.path.exists(self.remove_file))
self.assertTrue(b"pass %d/%d" % (passes, passes) in result) self.assertIn("pass %d/%d" % (passes, passes), result)
self.assertTrue(b"%s: removed" % os.path.basename(self.remove_file).encode('utf-8') in result) self.assertIn("%s: removed" % os.path.basename(self.remove_file), result)
def test_secure_remove_file_check_exist(self): def test_secure_remove_file_check_exist(self):
options = getAgumentParser().parse_args(['-n', '2', '-u', '-s', '--file', 'random.txt', self.remove_file]) options = getAgumentParser().parse_args(['-n', '2', '-u', '-s', '--file', 'random.txt', self.remove_file])
passes = 2 passes = 2
result = shred(options) result = shred(options)
self.assertFalse(os.path.exists(self.remove_file)) self.assertFalse(os.path.exists(self.remove_file))
self.assertTrue(b"pass %d/%d" % (passes, passes) in result) self.assertIn("pass %d/%d" % (passes, passes), result)
self.assertTrue(b"%s: removed" % os.path.basename(self.remove_file).encode('utf-8') in result) self.assertIn("%s: removed" % os.path.basename(self.remove_file), result)
def test_secure_remove_file_check_exist_false(self): def test_secure_remove_file_check_exist_false(self):
options = getAgumentParser().parse_args(['-n', '2', '-u', '--file', 'random.txt']) options = getAgumentParser().parse_args(['-n', '2', '-u', '--file', 'random.txt'])
...@@ -99,19 +99,19 @@ class TestSecureDelete(unittest.TestCase): ...@@ -99,19 +99,19 @@ class TestSecureDelete(unittest.TestCase):
# shred removed link and target file # shred removed link and target file
self.assertFalse(os.path.exists(self.remove_file)) self.assertFalse(os.path.exists(self.remove_file))
self.assertFalse(os.path.exists(self.link_name)) self.assertFalse(os.path.exists(self.link_name))
self.assertTrue(b"pass %d/%d" % (passes, passes) in result) self.assertIn("pass %d/%d" % (passes, passes), result)
self.assertTrue(b"%s: removed" % os.path.basename(self.remove_file).encode('utf-8') in result) self.assertIn("%s: removed" % os.path.basename(self.remove_file), result)
def test_secure_remove_file_multiple_files(self): def test_secure_remove_file_multiple_files(self):
options = getAgumentParser().parse_args(['-n', '2', '-u', '-z', '--file', self.remove_file, self.remove_file2]) options = getAgumentParser().parse_args(['-n', '2', '-u', '-z', '--file', self.remove_file, self.remove_file2])
passes = 2 + 1 # Option -z is used, plus one more pass passes = 2 + 1 # Option -z is used, plus one more pass
result = shred(options) result = shred(options)
self.assertFalse(os.path.exists(self.remove_file)) self.assertFalse(os.path.exists(self.remove_file))
self.assertTrue(b"pass %d/%d" % (passes, passes) in result) self.assertIn("pass %d/%d" % (passes, passes), result)
self.assertTrue(b"%s: removed" % os.path.basename(self.remove_file).encode('utf-8') in result) self.assertIn("%s: removed" % os.path.basename(self.remove_file), result)
self.assertFalse(os.path.exists(self.remove_file2)) self.assertFalse(os.path.exists(self.remove_file2))
self.assertTrue(b"%s: removed" % os.path.basename(self.remove_file2).encode('utf-8') in result) self.assertIn("%s: removed" % os.path.basename(self.remove_file2), result)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment