-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.py
70 lines (65 loc) · 2.36 KB
/
monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import json
import os
import util
class monitor:
def __init__(self, node):
self.dir = "monitor/%d/" % node
os.system("mkdir -p %s" % self.dir)
self.dblimit = 5
self.dbfile = self.dir + "db.mnc"
self.latest = {}
self.snapshots_cnt = 0
self.snapshots = {}
loaded = self.load()
if(loaded != {}):
self.latest = loaded[list(loaded)[:1][0]]
self.snapshots_cnt = len(loaded)
self.snapshots = list(loaded)
def store(self, dct):
dct = dict(sorted(dct.items()))
enc = ""
if(len(dct) > self.dblimit):
lst = sorted(dct.items())
cmd = "rm %s%s" % (self.dir, list(lst)[0][0])
os.system(cmd)
cut = dict(list(lst)[1:])
enc = json.dumps(cut, sort_keys=True)
self.snapshots_cnt = len(cut)
self.snapshots = cut
else:
dct = dict(sorted(dct.items()))
enc = json.dumps(dct, sort_keys=True)
self.snapshots_cnt = len(dct)
self.snapshots = dct
util.fwrite(self.dbfile, "w", enc)
def load(self):
try:
return json.loads(util.fread(self.dbfile, "r"))
except:
return {}
def update(self, imagefile, objects, timestamp):
dct = self.load()
key = round(timestamp)
cmd = "mv %s %s%s" % (imagefile, self.dir, key)
os.system(cmd)
self.latest = { "imagefile" : str(key), "objects" : objects }
dct[str(key)] = self.latest
self.store(dct)
def get_latest(self, snapshot):
if "imagefile" in self.latest and "objects" in self.latest:
if snapshot == 0:
return self.dir + self.latest["imagefile"],\
self.latest["objects"],\
self.latest["imagefile"],\
self.snapshots_cnt
else:
if snapshot >= 1 and snapshot <= len(self.snapshots):
itm = list(self.snapshots.items())[snapshot - 1]
return self.dir + itm[1]['imagefile'],\
itm[1]['objects'],\
itm[0],\
self.snapshots_cnt
else:
return "", 0, 0, self.snapshots_cnt
else:
return "", 0, 0, 0