Skip to content

Commit f832b85

Browse files
committed
Add RAM_TOTAL, Change monitor.sql
1 parent 69bf193 commit f832b85

File tree

6 files changed

+93
-92
lines changed

6 files changed

+93
-92
lines changed

lb.py

+51-45
Original file line numberDiff line numberDiff line change
@@ -22,59 +22,65 @@ def leastLoadServer(server_repo, ssample_repo, pred_repo):
2222
# Total cpu
2323
server_dict[server] = server_cpu + sum_avg_cpu
2424

25-
# Print the server with the lowest load
26-
print(min(server_dict, key=server_dict.get))
25+
return min(server_dict, key=server_dict.get)
2726

2827

2928
def loadBalance(uid, server_repo, ssample_repo, pred_repo):
30-
if pred_repo.exist(uid):
31-
# Prediction Record of UID
32-
pred = pred_repo.get(uid)
33-
last_hour = pred.last_login - datetime.timedelta(hours=1)
34-
min_disk_in, max_disk_in \
35-
= ssample_repo.getMinAndMaxDiskInLaterThan(
36-
pred.last_used_server,
37-
last_hour)
38-
39-
disk_difference = max_disk_in - min_disk_in
40-
ram_cached = ssample_repo.getRamCachedWithDiskInGequal(
41-
pred.last_used_server,
42-
max_disk_in)
43-
44-
# See if cache is still available
45-
cache_available = cacheAvailable(
46-
disk_difference, pred.avg_ram, ram_cached)
47-
48-
# if there is still cache available,
49-
# we check if the server has enough memory CPU
50-
# to support the user
51-
if cache_available:
52-
server_cpu, latest_time = \
53-
ssample_repo.getLatestServerCPUAndTime(
54-
pred.last_used_server)
55-
56-
sum_avg_cpu = \
57-
pred_repo.getSumAvgCPUFromServerLaterThan(
29+
# if not exist user
30+
if not pred_repo.exist(uid):
31+
return leastLoadServer(server_repo,
32+
ssample_repo, pred_repo)
33+
34+
# Prediction Record of UID
35+
pred = pred_repo.get(uid)
36+
last_hour = pred.last_login - datetime.timedelta(hours=1)
37+
38+
min_disk_in, max_disk_in \
39+
= ssample_repo.getMinAndMaxDiskInLaterThan(
5840
pred.last_used_server,
59-
latest_time - datetime.timedelta(hours=1))
60-
61-
if server_cpu < sum_avg_cpu:
62-
server_cpu = sum_avg_cpu
63-
64-
total_cpu = server_cpu + pred.avg_cpu
65-
if total_cpu < 100:
66-
print(pred.last_used_server)
67-
else:
68-
leastLoadServer(server_repo, ssample_repo, pred_repo)
69-
else:
70-
leastLoadServer(server_repo, ssample_repo, pred_repo)
41+
last_hour)
42+
43+
disk_difference = max_disk_in - min_disk_in
44+
ram_cached = ssample_repo.getRamCachedWithDiskInGequal(
45+
pred.last_used_server,
46+
max_disk_in)
47+
ram_total = ssample_repo.getServerTotalRam(pred.last_used_server)
48+
49+
# See if cache is still available
50+
cache_available = cacheAvailable(
51+
disk_difference,
52+
pred.avg_ram / 100 * ram_total,
53+
ram_cached
54+
)
55+
56+
if not cache_available:
57+
return leastLoadServer(server_repo,
58+
ssample_repo, pred_repo)
59+
60+
server_cpu, latest_time = \
61+
ssample_repo.getLatestServerCPUAndTime(
62+
pred.last_used_server
63+
)
64+
65+
sum_avg_cpu = \
66+
pred_repo.getSumAvgCPUFromServerLaterThan(
67+
pred.last_used_server,
68+
latest_time - datetime.timedelta(hours=1)
69+
)
70+
71+
if server_cpu < sum_avg_cpu:
72+
server_cpu = sum_avg_cpu
73+
74+
total_cpu = server_cpu + pred.avg_cpu
75+
if total_cpu < 100:
76+
return pred.last_used_server
7177
else:
7278
leastLoadServer(server_repo, ssample_repo, pred_repo)
7379

7480

75-
def cacheAvailable(disk_diff, user_avg_ram, cache):
81+
def cacheAvailable(disk_diff, user_avg_ram_in_MB, cache):
7682
cache_not_replace = cache - disk_diff
77-
if cache_not_replace > user_avg_ram:
83+
if cache_not_replace > user_avg_ram_in_MB:
7884
return True
7985
else:
8086
return False
@@ -94,4 +100,4 @@ def cacheAvailable(disk_diff, user_avg_ram, cache):
94100

95101
uid = int(sys.argv[1])
96102

97-
loadBalance(uid, server_repo, ssample_repo, pred_repo)
103+
print(loadBalance(uid, server_repo, ssample_repo, pred_repo))

monitor.sql

+12-11
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ CREATE TABLE IF NOT EXISTS `MONITOR`.`USER` (
2121
CONSTRAINT `USER_SERVER_FK`
2222
FOREIGN KEY (`SERVER`)
2323
REFERENCES `MONITOR`.`SERVER` (`NAME`)
24-
ON DELETE NO ACTION
25-
ON UPDATE NO ACTION)
24+
ON DELETE CASCADE
25+
ON UPDATE CASCADE)
2626
ENGINE = InnoDB;
2727

2828

@@ -32,7 +32,7 @@ CREATE TABLE IF NOT EXISTS `MONITOR`.`JOB` (
3232
`UID` INT NULL,
3333
`START_TIME` DATETIME NULL,
3434
`CMD_NAME` VARCHAR(45) NULL,
35-
`COMMAND` TINYTEXT NULL,
35+
`COMMAND` LONGTEXT NULL,
3636
`SERVER` VARCHAR(45) NULL,
3737
PRIMARY KEY (`id`) ,
3838
UNIQUE INDEX `P_IDX` (`PID` ASC, `UID` ASC, `START_TIME` ASC) ,
@@ -41,13 +41,13 @@ CREATE TABLE IF NOT EXISTS `MONITOR`.`JOB` (
4141
CONSTRAINT `JOB_UID_FK`
4242
FOREIGN KEY (`UID`)
4343
REFERENCES `MONITOR`.`USER` (`UID`)
44-
ON DELETE NO ACTION
45-
ON UPDATE NO ACTION,
44+
ON DELETE CASCADE
45+
ON UPDATE CASCADE,
4646
CONSTRAINT `JOB_SERVER_FK`
4747
FOREIGN KEY (`SERVER`)
4848
REFERENCES `MONITOR`.`SERVER` (`NAME`)
49-
ON DELETE NO ACTION
50-
ON UPDATE NO ACTION)
49+
ON DELETE CASCADE
50+
ON UPDATE CASCADE)
5151
ENGINE = InnoDB;
5252

5353

@@ -68,8 +68,8 @@ CREATE TABLE IF NOT EXISTS `MONITOR`.`jSAMPLE` (
6868
CONSTRAINT `P_FK`
6969
FOREIGN KEY (`PID`, `UID` , `START_TIME`)
7070
REFERENCES `MONITOR`.`JOB` (`PID`, `UID`, `START_TIME`)
71-
ON DELETE NO ACTION
72-
ON UPDATE NO ACTION)
71+
ON DELETE CASCADE
72+
ON UPDATE CASCADE)
7373
ENGINE = InnoDB;
7474

7575

@@ -81,15 +81,16 @@ CREATE TABLE IF NOT EXISTS `MONITOR`.`sSAMPLE` (
8181
`RAM` DECIMAL(6, 3) NULL,
8282
`RAM_AVAILABLE` INT NULL,
8383
`RAM_CACHED` INT NULL,
84+
`RAM_TOTAL` INT NULL,
8485
`DISK_IN` INT NULL,
8586
`DISK_OUT` INT NULL,
8687
PRIMARY KEY (`id`) ,
8788
INDEX `SERVER_FK_IDX` (`NAME` ASC),
8889
CONSTRAINT `sSAMPLE_SERVER_FK`
8990
FOREIGN KEY (`NAME`)
9091
REFERENCES `MONITOR`.`SERVER` (`NAME`)
91-
ON DELETE NO ACTION
92-
ON UPDATE NO ACTION)
92+
ON DELETE CASCADE
93+
ON UPDATE CASCADE)
9394
ENGINE = InnoDB;
9495

9596
CREATE TABLE IF NOT EXISTS `MONITOR`.`PREDICTION` (

process.log

-22
Original file line numberDiff line numberDiff line change
@@ -1,23 +1 @@
11

2-
ERROR:root:Error:
3-
Traceback (most recent call last):
4-
File "process_monitor.py", line 31, in <module>
5-
processes = ProcessService.getAll(excludeProcess, minUID=1000)
6-
File "/home/tung/Desktop/ktlt/utils.py", line 96, in getAll
7-
p = Process(proc)
8-
File "/home/tung/Desktop/ktlt/utils.py", line 38, in __init__
9-
self.__getProcessResources(process)
10-
File "/home/tung/Desktop/ktlt/utils.py", line 42, in __getProcessResources
11-
= process.io_counters()
12-
File "/usr/local/lib/python2.7/dist-packages/psutil/__init__.py", line 787, in io_counters
13-
return self._proc.io_counters()
14-
File "/usr/local/lib/python2.7/dist-packages/psutil/_pslinux.py", line 1322, in wrapper
15-
raise AccessDenied(self.pid, self._name)
16-
AccessDenied: psutil.AccessDenied (pid=1497, name='(sd-pam)')
17-
ERROR:root:Error:
18-
Traceback (most recent call last):
19-
File "process_monitor.py", line 40, in <module>
20-
jsampleRepo.add(jSample(proc))
21-
File "/home/tung/Desktop/ktlt/utils.py", line 331, in add
22-
self.db.commit()
23-
KeyboardInterrupt

process_monitor.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
if __name__ == '__main__':
99
try:
10-
db = MySQLdb.connect(host="10.0.2.2", user="lb",
10+
db = MySQLdb.connect(host="localhost", user="lb",
1111
passwd="lb", db="MONITOR")
1212
except Exception as e:
1313
print("Can't connect to DB")

server_monitor.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
if __name__ == '__main__':
99
logging.basicConfig(level=logging.DEBUG, filename="server.log")
1010
try:
11-
db = MySQLdb.connect(host="10.0.2.2", user="lb",
11+
db = MySQLdb.connect(host="localhost", user="lb",
1212
passwd="lb", db="MONITOR")
1313
except Exception as e:
1414
print("Can't connect to database")

utils.py

+28-12
Original file line numberDiff line numberDiff line change
@@ -303,10 +303,10 @@ def __init__(self, proc):
303303

304304
class jSampleStatistic:
305305
def __init__(self, avg_cpu, max_cpu, avg_ram, max_ram, run_time):
306-
self.avg_cpu = avg_cpu
307-
self.max_cpu = max_cpu
308-
self.avg_ram = avg_ram
309-
self.max_ram = max_ram
306+
self.avg_cpu = round(avg_cpu, 3)
307+
self.max_cpu = round(max_cpu, 3)
308+
self.avg_ram = round(avg_ram, 3)
309+
self.max_ram = round(max_ram, 3)
310310
self.run_time = run_time
311311

312312

@@ -361,12 +361,14 @@ def deleteUidsEarlierThan(self, uid, time):
361361
##############################
362362
class sSample:
363363
def __init__(self, name, cpu, ram,
364-
ram_available, ram_cached, disk_in, disk_out):
364+
ram_available, ram_cached, ram_total,
365+
disk_in, disk_out):
365366
self.name = name
366367
self.cpu = cpu
367368
self.ram = ram
368369
self.ram_available = ram_available
369370
self.ram_cached = ram_cached
371+
self.ram_total = ram_total
370372
self.disk_in = disk_in
371373
self.disk_out = disk_out
372374

@@ -383,6 +385,7 @@ def getServerInfo():
383385
ram = round(percent, 3)
384386
ram_available = bytesToMegabytes(available)
385387
ram_cached = bytesToMegabytes(cache)
388+
ram_total = bytesToMegabytes(total)
386389

387390
# IO usage
388391
read_count, write_count, read_bytes, write_bytes, \
@@ -394,7 +397,7 @@ def getServerInfo():
394397

395398
hostname = socket.gethostname()
396399
return sSample(hostname, cpu, ram, ram_available,
397-
ram_cached, disk_in, disk_out)
400+
ram_cached, ram_total, disk_in, disk_out)
398401

399402

400403
class sSampleRepository:
@@ -405,11 +408,12 @@ def add(self, ssample):
405408
cursor = self.db.cursor()
406409
try:
407410
cursor.execute("INSERT INTO sSAMPLE(NAME, CPU, RAM, "
408-
"RAM_AVAILABLE, RAM_CACHED, DISK_IN, "
409-
"DISK_OUT) VALUES"
410-
"(%s, %s, %s, %s, %s, %s, %s)",
411+
"RAM_AVAILABLE, RAM_CACHED, RAM_TOTAL, "
412+
"DISK_IN, DISK_OUT) VALUES"
413+
"(%s, %s, %s, %s, %s, %s, %s, %s)",
411414
(ssample.name, ssample.cpu, ssample.ram,
412-
ssample.ram_available, ssample.ram_cached,
415+
ssample.ram_available,
416+
ssample.ram_cached, ssample.ram_total,
413417
ssample.disk_in, ssample.disk_out))
414418
self.db.commit()
415419
cursor.close()
@@ -463,7 +467,19 @@ def getLatestServerCPUAndTime(self, server_name):
463467
except Exception as e:
464468
print("sSampleRepository: getLatestServerCPUAndTime()")
465469
print(e)
466-
return cpu, timestamp
470+
return float(cpu), timestamp
471+
472+
def getServerTotalRam(self, server_name):
473+
cursor = self.db.cursor()
474+
try:
475+
cursor.execute("SELECT RAM_TOTAL FROM sSAMPLE "
476+
"WHERE NAME = %s", (server_name, ))
477+
for row in cursor:
478+
return row[0]
479+
except Exception as e:
480+
print("sSampleRepository: getServerTotalRam()")
481+
print(e)
482+
return None
467483

468484

469485
##############################
@@ -570,4 +586,4 @@ def getSumAvgCPUFromServerLaterThan(self, server_name, timestamp):
570586
except Exception as e:
571587
print("PredictionRepository: getListAvgCPUFromServerLaterThan()")
572588
print(e)
573-
return sum(avgs_cpu)
589+
return float(sum(avgs_cpu))

0 commit comments

Comments
 (0)