-
Notifications
You must be signed in to change notification settings - Fork 10
/
7demo.py
1363 lines (1157 loc) · 47.6 KB
/
7demo.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import hashlib
import math
import random as r
import pandas as pd
import time
import os
import psutil
import heapq
import json
import requests
from threading import Thread
from mlxtend.frequent_patterns import fpgrowth
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
import socket
import wget
import subprocess as sp
import argparse
import config
import smtplib
from email.message import EmailMessage
import pickle
import paho.mqtt.client as mqtt
import re
class Record:
system = psutil.Process(os.getpid())
def __init__(self, window_size, title):
self.data_set = []
self.window_size = window_size
self.title = title
self.count = 0
def get_data(self):
return 1
def add_data(self):
data = self.get_data()
new_avg = self.calculate_mov_avg(data)
self.check_window_size()
self.data_set.append(new_avg)
def check_window_size(self):
if len(self.data_set) > self.window_size:
outfile = open(f'results/{self.title}/{self.count}.pickle', 'wb')
pickle.dump(self.data_set, outfile)
outfile.close()
self.data_set = self.data_set[-1:]
self.count += 1
def calculate_mov_avg(self, a1):
_count = len(self.data_set)
if _count == 0:
avg1 = 0
else:
avg1 = self.data_set[-1]
_count += 1
avg1 = ((_count - 1) * avg1 + a1) / _count # cumulative average formula μ_n=((n-1) μ_(n-1) + x_n)/n
return round(avg1, 4)
class CPU(Record):
def get_data(self):
cpu = psutil.cpu_percent(percpu=False)
try:
lst = self.data_set[-1]
except IndexError:
lst = psutil.cpu_percent(percpu=False)
return round(abs(cpu - lst), 4)
class Memory(Record):
def get_data(self):
return round(self.system.memory_percent(), 4)
class Delay:
def __init__(self, window_size):
self.data_set = []
self.window_size = window_size
self.count = 0
def add_data(self, data):
new_avg = self.calculate_mov_avg(data)
self.data_set.append(new_avg)
self.check_window_size()
def calculate_mov_avg(self, a1):
_count = len(self.data_set)
if _count == 0:
avg1 = 0
else:
avg1 = self.data_set[-1]
_count += 1
avg1 = ((_count - 1) * avg1 + a1) / _count # cumulative average formula μ_n=((n-1) μ_(n-1) + x_n)/n
return round(avg1, 4)
def check_window_size(self):
if len(self.data_set) > self.window_size:
outfile = open(f'results/delay/{self.count}.pickle', 'wb')
pickle.dump(self.data_set, outfile)
outfile.close()
self.data_set = self.data_set[-1:]
self.count += 1
class Heap:
def __init__(self):
self.heap = [] # delay
heapq.heapify(self.heap)
self.table = {} # delay : mec
def unique_delay(self, delay):
if delay in self.heap:
delay -= 0.00001
return self.unique_delay(delay)
else:
return delay
def push(self, delay, mec):
if mec not in self.table.values():
delay = self.unique_delay(delay)
heapq.heappush(self.heap, delay)
self.table[delay] = mec
def remove(self, mec):
if mec in self.table.values():
t_mec = dict(zip(self.table.values(), self.table.keys()))
delay_key = t_mec[mec]
self.heap.remove(delay_key)
heapq.heapify(self.heap)
self.table.pop(delay_key)
def list(self):
return [self.table[i] for i in self.heap]
def get_head(self):
if len(self.heap) != 0:
return self.table[self.heap[0]]
else:
return None
def __len__(self):
return len(self.heap)
def pop(self):
return heapq.heappop(self.heap)
def push_pop(self, item):
""":arg
Push item on the heap, then pop and return the smallest item from the heap
"""
return heapq.heappushpop(self.heap, item)
def replace(self, item):
""":arg
Pop and return the smallest item from the heap, and also push the new item
"""
return heapq.heapreplace(self.heap, item)
class CollaborativeCache:
def __init__(self, no_mec):
self.cache_store = {} # {cache_id: heap({mec1, mec2}), ..}
self.w = 0.1 # No of MEC that can store a cache in percentage
self.no_mec = no_mec
def cache_decision(self, length):
if length < math.ceil(self.w * self.no_mec):
return 1
else:
return 0
@staticmethod
def ping(host):
cmd = [f'ping -c 1 {host}']
try:
output = str(sp.check_output(cmd, shell=True), 'utf-8').split('\n')
except sp.CalledProcessError:
print(f'{host} -> destination unreachable..')
return None
try:
value = float(output[-2].split('=')[-1].split('/')[0])
except ValueError:
print(f"{output[-2].split('=')[-1].split('/')[0]} -> Ping Value Error")
value = None
return value
def get_delay(self, mec):
rtt = self.ping(mec)
if rtt:
return round(rtt, 4)
else:
return self.get_delay(mec)
def add_cache(self, cache_content_hash, mec): # multi-cast from mec
mec_delay = self.get_delay(mec)
if cache_content_hash not in self.cache_store:
self.cache_store[cache_content_hash] = Heap()
self.cache_store[cache_content_hash].push(mec_delay, mec)
def __getfile(self, mec, content_hash):
request_link = f"ftp://{mec}/cache/{content_hash}.html"
name = f'{content_hash}.html'
start = time.perf_counter()
filename = f'temp/{name}'
try:
wget.download(request_link, filename)
except Exception as e:
self.remove(mec, content_hash)
raise FileNotFoundError('cache not found on mec')
# wget.download(request_link, filename)
cost = round(time.perf_counter() - start, 5)
return cost
def find_cache(self, cache_content_hash):
try:
mec = self.cache_store[cache_content_hash].get_head()
return self.__getfile(mec, cache_content_hash), self.cache_decision(
len(self.cache_store[cache_content_hash]))
except KeyError:
return None
except FileNotFoundError:
return None
def table(self):
return {i: self.cache_store[i].list() for i in self.cache_store}
def remove(self, mec, old_cache):
self.cache_store[old_cache].remove(mec)
def replace(self, mec, old_cache, new_cache): # multi-cast from mec
self.cache_store[old_cache].remove(mec)
if len(self.cache_store[old_cache]) == 0:
self.cache_store.pop(old_cache)
self.add_cache(new_cache, mec)
# A linked list node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
self.id = self.get_hash()
self.count = 0
self.last_access = time.time()
self.retrieval_cost = 0
self.content_id = None
@property
def page_no(self):
return re.findall('[0-9]+', self.data.split('/')[-1])
def get_hash(self):
y = str.encode(str(self.data))
ha = hashlib.sha256(y)
hash_no = ha.hexdigest()
return hash_no
@property
def details(self):
d = lambda x: None if x is None else x.data
return {'data': self.data, 'next': d(self.next), 'prev': d(self.prev), 'count': self.count}
def reduce_count(self):
self.count = math.ceil(self.count / 2)
class FIFO:
def __init__(self, maxsize):
self.head = None
self.tail = None
self.length = 0
self.table = {}
self.maxsize = maxsize
# Given a reference to the head of a list and an
# integer, inserts a new node on the front of list
def push(self, new_node):
# 1. Allocates node
# 2. Put the data in it
self.table[new_node.id] = new_node
# 3. Make next of new node as head and
# previous as None (already None)
new_node.next = self.head
# 4. change prev of head node to new_node
if self.head is not None:
self.head.prev = new_node
# 5. move the head to point to the new node
self.head = new_node
if not self.tail:
self.tail = new_node
self.length += 1
self.maintain_size()
return new_node
def maintain_size(self):
if self.length > self.maxsize:
self.delete(self.tail)
def delete(self, node):
if node.id in self.table:
node = self.table.pop(node.id)
if node.prev:
if node.next: # delete a middle node
node.prev.next = node.next
node.next.prev = node.prev
else: # delete last node
node.prev.next = None
self.tail = node.prev
else: # delete head node
self.head = node.next
if node.next:
node.next.prev = None
else:
self.tail = None
self.length -= 1
return node
def list(self):
d_list = []
node = self.head
while node:
d_list.append(node.data)
node = node.next
return d_list
def reduce_count(self):
node = self.head
while node:
node.reduce_count()
node = node.next
# Class to create a Doubly Linked List
class LRUChain:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None
self.tail = None
self.length = 0
self.table = {}
# Given a reference to the head of a list and an
# integer, inserts a new node on the front of list
def push(self, new_node):
# 1. Allocates node
# 2. Put the data in it
if new_node.id in self.table:
new_node = self.delete_node(self.table[new_node.id])
new_node.next = None
new_node.prev = None
self.table[new_node.id] = new_node
# 3. Make next of new node as head and
# previous as None (already None)
new_node.next = self.head
# 4. change prev of head node to new_node
if self.head is not None:
self.head.prev = new_node
# 5. move the head to point to the new node
self.head = new_node
if not self.tail:
self.tail = new_node
self.length += 1
return new_node
def print_list(self, node):
print("\nTraversal in forward direction")
while node is not None:
print(node.data)
node = node.next
print("\nTraversal in reverse direction")
last = self.tail
while last is not None:
print(last.data)
last = last.prev
def find(self, id_):
node = self.head
while node:
if node.id == id_:
result = f'id: {id_} \nData: {node.data}'
print(result)
return node
node = node.next
return None
def remove_with_id(self, id_):
node = self.find(id_)
if node:
if node.prev:
if node.next: # delete a middle node
node.prev.next = node.next
node.next.prev = node.prev
else: # delete last node
node.prev.next = None
self.tail = node.prev
print(f'Deleted {id_}')
else: # delete head node
self.head = node.next
if node.next:
node.next.prev = None
else:
self.tail = None
print(f'Deleted {id_}')
self.length -= 1
return node
def remove_with_data(self, data):
node = self.head
while node:
if node.data == data:
if node.prev:
if node.next: # delete a middle node
node.prev.next = node.next
node.next.prev = node.prev
else: # delete last node
node.prev.next = None
self.tail = node.prev
print(f'Deleted {data}')
else: # delete head node
self.head = node.next
if node.next:
node.next.prev = None
else:
self.tail = None
print(f'Deleted {data}')
self.length -= 1
return node
node = node.next
return None
def delete_node(self, node):
if node.id in self.table:
node = self.table.pop(node.id)
if node.prev:
if node.next: # delete a middle node
node.prev.next = node.next
node.next.prev = node.prev
else: # delete last node
node.prev.next = None
self.tail = node.prev
else: # delete head node
self.head = node.next
if node.next:
node.next.prev = None
else:
self.tail = None
self.length -= 1
return node
def list(self):
d_list = []
node = self.head
while node:
d_list.append(node.data)
node = node.next
return d_list
def details(self):
d_list = []
node = self.head
while node:
d_list.append(node.details)
node = node.next
return d_list
def count_display(self):
d_list = []
node = self.head
while node:
d_list.append(node.count)
node = node.next
return d_list
def hash_table(self):
d_list = {}
node = self.head
while node:
d_list[node.id] = node.data
node = node.next
return d_list
class NameResolutionServer:
def __init__(self, content_name_server):
self.content_name_server = content_name_server
def get_json_data(self, endpoint, send=None):
url = f'http://{self.content_name_server}/'
if send:
response = requests.post(url + endpoint, json=json.dumps(send))
else:
response = requests.get(url + endpoint)
data = json.loads(response.content)
return data
def add_to_server(self, location_hash, content_hash, url):
self.get_json_data(endpoint='add/', send=[location_hash, content_hash, url])
def get_content_hash(self, location_hash):
return self.get_json_data(endpoint=f'read/hash/{location_hash}')['hash']
class Matches:
def __init__(self, size):
self.size = size
# [{match1: [0,0], match2: 1, ...}, {}] first value 0 means not precache, 1 means precache
# second value 0 means not used and 1 means not used
self.matches = []
self.right = 0
self.wrong = 0
self.right_cache = 0
self.wrong_cache = 0
@property
def total(self):
return self.right + self.wrong
def contains(self, item):
for match_dict in self.matches:
if item in match_dict:
self.right += 1
match_dict[item][1] = 1 # item has been used
if match_dict[item][0] == 1:
self.right_cache += 1
def push(self, match):
if len(self.matches) >= self.size:
self.check_wrong(self.matches.pop(0))
self.matches.append(match)
def check_wrong(self, match):
for key in match:
if match[key][1] == 0:
self.wrong += 1
if match[key][0] == 1:
self.wrong_cache += 1
def __len__(self):
return len(self.matches)
class LocalCache:
def __init__(self, cache_size, max_freq, avg_max, window_size, content_name_server, delay):
self.cache_size = cache_size
self.max_freq = max_freq
self.history = FIFO(cache_size * 8)
self.chain = {}
self.table = {}
self.length = 0
self.hit = 0
self.miss = 0
self.mec_hit = 0
self.avg_max = avg_max
self.min_freq = 1
self.content_name_server = content_name_server
self.delay = delay
self.cache_dir = '/srv/ftp/cache'
self.req_window = window_size ** 2
self.window_size = window_size
self.req = []
self.to_delete = ['test']
self.pre_cached = 0
self.no_rules = 6
self.rules = RuleStore(ant_max=4, max_length=20)
self.matches = Matches(5)
self.content_name_resolution = NameResolutionServer(content_name_server=content_name_server)
self.rule_matches = {'window_count': 0, 'window_size': int(self.window_size / 2), 'rule_count': 0}
@staticmethod
def web_page(request):
return f"https://competent-euler-834b51.netlify.app/pages/{request}.html"
@staticmethod
def get_hash(data):
y = str.encode(str(data))
ha = hashlib.sha256(y)
hash_no = ha.hexdigest()
return hash_no
@staticmethod
def mec_cache_link(content_hash, mec):
return f"ftp://{mec}/cache/{content_hash}.html"
def rename_to_content_hash(self, web_link, filename, temp=0):
file_ = open(filename, 'rb')
content_hash = hashlib.sha256(file_.read()).hexdigest()
file_.close()
self.content_name_resolution.add_to_server(content_hash=content_hash, url=web_link,
location_hash=self.get_hash(web_link))
if temp == 0:
os.system(f'mv {self.cache_dir}/temp {self.cache_dir}/{content_hash}.html')
return content_hash
def get_file(self, request_link, temp=0):
name = request_link.split('/')[-1]
start = time.perf_counter()
if temp == 1:
filename = f'temp/{name}'
try:
wget.download(request_link, filename)
except Exception as e:
wget.download(request_link, filename)
else:
filename = f'{self.cache_dir}/temp'
try:
wget.download(request_link, filename)
except Exception as e:
wget.download(request_link, filename)
cost = round(time.perf_counter() - start, 5)
content_hash = self.rename_to_content_hash(web_link=request_link, filename=filename, temp=temp)
return cost, content_hash
def association_match_count(self, req):
self.matches.contains(req)
def add_req_to_list(self, cache):
self.window_check()
self.req.append(cache)
def window_check(self):
if len(self.req) > self.req_window:
self.req.pop(0)
@property
def average_count(self):
return round(sum(self.chain.keys()) / len(self.chain), 2)
def maintain_count(self):
if self.average_count > self.avg_max:
# print('start: ', self.details_display())
new_chain = {}
event = 'maintaining count... ..'
display_event(kind='notify', event=event, origin='maintain_count')
def reduce_count(node):
while node:
node.reduce_count()
if node.count not in new_chain: new_chain[node.count] = LRUChain()
new_chain[node.count].push(node)
if node.count < self.min_freq: self.min_freq = node.count
node = node.prev
for chain in self.chain.values():
reduce_count(chain.tail)
self.history.reduce_count()
self.chain = new_chain
def increment_count_decision(self, node):
diff = 1
# event = f'loop list -> {list(range(node.count-1, 0, -1))}'
# display_event(kind='notify', event=event, origin='increment_count_decision')
for tf in range(node.count - 1, 0, -1):
try:
q = self.chain[tf]
print('in->', tf, q)
break
except KeyError:
diff += 1
if diff < self.max_freq:
return True, diff
else:
return False, diff
def request(self, page):
self.push(page)
self.association_match_count(page)
if self.rule_matches['window_count'] == self.rule_matches['window_size']:
self.get_association_rules()
self.apply_association()
self.rule_matches['window_count'] = 0
else:
if len(self.rules) > 0:
self.apply_association()
self.rule_matches['window_count'] += 1
def push(self, page, precache=0):
web_link = self.web_page(page)
new_node = Node(web_link)
if precache == 0:
self.add_req_to_list(page)
decision = [1, None] # 0 means don't cache, 1 means cache
if new_node.id in self.table:
if precache == 1:
decision[0] = 0
display_event(kind='notify', event='Association Precache already in store', origin='push')
else:
self.delay.add_data(0)
display_event(kind='notify', event=f'Cache Hit', origin='push from LocalCache')
new_node = self.table[new_node.id] # dont remove this, it is useful, even if you dont think it is
new_node = self.chain[new_node.count].delete_node(new_node) # self.table[new_node.id]
new_node.prev, new_node.next = None, None
new_node.last_access = time.time()
self.hit += 1
result = self.increment_count_decision(new_node)
if self.chain[new_node.count].length == 0:
self.chain.pop(new_node.count)
if result[0] and (self.min_freq == new_node.count):
self.min_freq += 1
if result[0]:
display_event(kind='notify', event=f'incrementing ->{result}', origin='push from LocalCache')
new_node.count += 1
else:
display_event(kind='notify', event=f'Not incrementing ->{result}', origin='push from LocalCache')
# print('hit')
else:
display_event(kind='notify', event='cache miss', origin='push from LocalCache')
reply = self.check_mec(new_node) # None or (decision, node) or (decision, node, replace)
if reply:
if precache == 0:
self.mec_hit += 1
decision = reply
#print(f'\n\nMEC cache -> {collaborative_cache.table()} \n\n')
new_node = decision[1]
# do if only cache is to be stored! maintain min freq
if (decision[0] == 1) and ((precache == 0) or (new_node.count == 0)):
new_node.count += 1
event = f'incrementing new ->{new_node.count} | {self.chain.keys()}' # incremented always for miss
display_event(kind='notify', event=event, origin='push from LocalCache')
if decision[0] == 1:
event = 'cached from mec'
display_event(kind='notify', event=event, origin='push from LocalCache')
self.table[new_node.id] = new_node
self.length += 1
if new_node.count < self.min_freq:
if self.min_freq - self.max_freq > new_node.count:
new_node.count = self.min_freq - self.max_freq
self.min_freq = new_node.count
else:
event = 'Obtained from mec, Not Cached'
display_event(kind='notify', event=event, origin='push from LocalCache')
event = f'Not stored | Not incrementing new ->{new_node.count} | {self.chain.keys()}'
display_event(kind='notify', event=event, origin='push from LocalCache')
if len(decision) == 3:
if decision[2]:
messenger.publish('cache/replace',
pickle.dumps([ip_address(), decision[2].content_id, new_node.content_id]))
elif (self.length < self.cache_size) and (decision[0] == 1):
messenger.publish('cache/add', pickle.dumps([new_node.content_id, ip_address()]))
else:
if precache == 0:
self.miss += 1
if self.length >= self.cache_size:
decision = self.maintain_cache_size(new_node)
if decision[0] == 1:
new_node = new_node if decision[1] is None else decision[1]
if (precache == 0) or (new_node.count == 0):
if new_node.count + 1 < self.min_freq:
if self.min_freq - self.max_freq > new_node.count + 1:
new_node.count = self.min_freq - self.max_freq
self.min_freq = new_node.count + 1
new_node.count += 1
event = f'incrementing new ->{new_node.count} | {self.chain.keys()}'
display_event(kind='notify', event=event, origin='push from LocalCache')
self.table[new_node.id] = new_node
self.length += 1
new_node.retrieval_cost, new_node.content_id = self.get_file(request_link=web_link, temp=0)
else:
if precache == 0:
new_node.count += 1
new_node.retrieval_cost, new_node.content_id = self.get_file(request_link=web_link, temp=1)
event = f'incrementing new ->{new_node.count} | {self.chain.keys()}'
display_event(kind='notify', event=event, origin='push from LocalCache')
if len(decision) == 3:
if decision[2]:
messenger.publish('cache/replace',
pickle.dumps([ip_address(), decision[2].content_id, new_node.content_id]))
elif (self.length < self.cache_size) and (decision[0] == 1):
messenger.publish('cache/add', pickle.dumps([new_node.content_id, ip_address()]))
if precache == 0:
self.delay.add_data(new_node.retrieval_cost)
if decision[0] == 1:
try:
self.chain[new_node.count].push(new_node)
except KeyError:
self.chain[new_node.count] = LRUChain()
self.chain[new_node.count].push(new_node)
self.maintain_count()
if len(os.listdir('temp/')) > 1:
os.system('rm temp/*.html')
if precache == 1:
return decision[0]
def mec_rename_temp(self, content_hash):
filename_full = rf'temp/{content_hash}.html'
os.system(f'mv {filename_full} {self.cache_dir}/{content_hash}.html')
def check_mec(self, new_node):
""":arg
This function returns one of the following:
1. None
2. (Decision, node) => node plus cost and time
3. (Decision, node, replace) => node plus cost and time
"""
def get_response(content_hash):
response = collaborative_cache.find_cache(content_hash)
new_node.content_id = content_hash
if response: # response = None or (cost, decision)
new_node.retrieval_cost = response[0]
if self.length < self.cache_size:
response = (response[0], 1)
if (response[1] == 1) and (self.length >= self.cache_size):
reply = self.maintain_cache_size(new_node) # result => cache_decision, node, replaced
if reply[0] == 1:
self.mec_rename_temp(content_hash)
return reply, 1
elif response[1] == 0:
return (response[1], new_node), 0
else:
self.mec_rename_temp(content_hash)
return (response[1], new_node), 1
else:
return None, 1
if new_node.id in self.history.table:
con_id = self.history.table[new_node.id].content_id
decision = get_response(con_id)
if (decision[0] != None) and (decision[1] == 0):
new_node = self.history.delete(new_node)
new_node.next, new_node.prev = None, None
self.history.push(new_node)
new_node.last_access = time.time()
return decision[0]
else:
content_id = self.content_name_resolution.get_content_hash(location_hash=new_node.id)
if content_id:
new_node.last_access = time.time()
return get_response(content_id)[0]
return None
def find_new_min_freq(self):
found = False
for i in range(self.min_freq, self.min_freq + self.max_freq + 1):
try:
tail_node = self.chain[i].tail
self.min_freq = tail_node.count
found = True
break
except KeyError:
pass
if found:
event = f'next min freq found -> {self.min_freq}'
display_event(kind='notify', event=event, origin='find_new_min_freq')
else:
event = f'next min freq not found-> {self.min_freq} | ' \
f'{list(range(self.min_freq, self.min_freq + self.max_freq + 1))}'
display_event(kind='notify', event=event, origin='find_new_min_freq')
def maintain_cache_size(self, node):
cache_decision = 0 # 0 means don't cache, 1 means cache
replaced = None
if node.id in self.history.table:
node = self.history.delete(node)
node.next, node.prev = None, None
min_queue = self.chain[self.min_freq]
victim = min_queue.tail
# print(self.sorted_freq.heap)
# print('comparing: ', node.data, victim.data, '->', self.data_display())
if (node.last_access > victim.last_access) or (node.retrieval_cost > victim.retrieval_cost):
# print('before eviction ++++', self.data_display() )
display_event(kind='notify', event=f'evicting {victim.content_id}', origin='maintain_cache_size')
self.evict(victim)
replaced = victim
victim.next, victim.prev = None, None
self.history.push(victim)
node.last_access = time.time()
cache_decision += 1
# print('evicted: ++++', victim.data, 'recap: ', self.data_display())
else:
node.last_access = time.time()
self.history.push(node)
else:
self.history.push(node)
return cache_decision, node, replaced
def evict(self, victim):
os.system(f'rm {self.cache_dir}/{self.to_delete.pop(0)}.html')
self.to_delete.append(victim.content_id)
self.chain[victim.count].delete_node(victim)
self.length -= 1
self.table.pop(victim.id)
if self.chain[victim.count].length == 0:
self.chain.pop(victim.count)
self.find_new_min_freq()
return victim
def apply_association(self):
match = 0
match_dict = {}
for i in range(1, self.rules.ant_max + 1):
try:
cons = self.rules.rules[i][tuple(self.req[-i:])]
# [{match1: [0,0], match2: 1, ...}, {}]
display_event(kind='notify', event=f'association match {cons}', origin='apply_association')
for page in cons:
match_dict[page] = [self.push(page, precache=1), 0]
match += 1
except KeyError:
pass
if match == 0:
display_event(kind='notify', event=f'No association Match', origin='apply_association')
else:
self.matches.push(match_dict)
def get_association_rules(self):
if len(self.req) >= self.window_size:
group_no = len(set(self.req[-self.window_size:]))
data_len = group_no ** 2
if len(self.req) >= data_len:
data = self.req[-data_len:]
print(f'Generating Association rules for data {group_no}x{len(data)}')
t1 = time.time()
rules = AssociateCache(data=data, rule_no=self.no_rules, group_no=group_no).gen_rules()
self.rules.add_rules(rules)
self.rule_matches['rule_count'] += 1
t2 = time.time()
display_event(kind=f'Association Rules | Time: {round(t2-t1, 5)}', event=rules,
origin='get_association_rules')
def total_hit_ratio(self):
return round((((self.hit + self.mec_hit) / (self.hit + self.mec_hit + self.miss)) * 100), 2)
def mec_hit_ratio(self):
return round((self.mec_hit / (self.hit + self.mec_hit)) * 100, 2)
def hit_ratio(self):
return round((self.hit / (self.hit + self.mec_hit + self.miss)) * 100, 2)
def right_predictions(self):
return round((self.matches.right / (self.matches.right + self.matches.wrong)) * 100)
def data_display(self):
return {i: self.chain[i].list() for i in self.chain}
def details_display(self):
return {i: self.chain[i].details() for i in self.chain}
def outcome_details(self):
text = {'right_match': self.matches.right,
'Wrong_match': self.matches.wrong,
'right_pre_cache': self.matches.right_cache,
'wrong_pre_cache': self.matches.wrong_cache,
'total_hit_ratio': self.total_hit_ratio(),
'mec_hit_ratio': self.mec_hit_ratio(),
'hit_ratio': self.hit_ratio()
}
return text
def experiment_details(self):
print('Total Hit ratio: ', self.total_hit_ratio(), '%')
print('mec hit ratio: ', self.mec_hit_ratio(), '%')
print('hit ratio: ', self.hit_ratio(), '%')
print('Pre-cached: ', self.pre_cached)
total_matches = (self.matches.right + self.matches.wrong)
if total_matches != 0:
pred = round((self.matches.right / total_matches) * 100)
else:
pred = 0
print('Right Predictions: ', pred, '%')
print(f"Generated {self.rule_matches['rule_count']} rules ")
print(f"No of association matches: ", self.matches.total)