MixGuard.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import simpy
  2. import random
  3. class MixGuard(object):
  4. __slots__ = ['env', 'conf', 'net', 'logger', 'layer', 'id', 'resource_queue', 'queue', 'resource_queue', 'max_capacity']
  5. def __init__(self, env, conf, net, id=None, layer=None, logger=None):
  6. self.env = env
  7. self.conf = conf
  8. self.layer = layer
  9. self.net = net
  10. self.logger = logger
  11. self.id = id or random_string(self.conf["misc"]["id_len"])
  12. self.max_capacity = 100
  13. # Resource queue to model congestion
  14. self.resource_queue = simpy.PriorityResource(self.env, capacity=self.max_capacity)
  15. self.queue = []
  16. def start(self):
  17. print("> %s started" % self.id)
  18. yield self.env.timeout(0)
  19. self.env.process(self.flush_packets())
  20. def set_network(self, topology):
  21. ''' Function sets a given network topology.
  22. Keyword arguments:
  23. topology - a topology of the network.
  24. '''
  25. self.topology = topology
  26. def process_packet(self, packet):
  27. yield self.env.timeout(0)
  28. self.add_packet_to_queue(packet)
  29. def add_packet_to_queue(self, packet):
  30. ''' Adding packet to the internal queue.
  31. Check whether the queue is not too large.
  32. '''
  33. self.queue.append(packet)
  34. self.manage_queue()
  35. def flush_packets(self):
  36. ''' Continusly check whether there are any packets
  37. to send.
  38. '''
  39. while True:
  40. if len(self.queue) > 1:
  41. packet = self.queue.pop()
  42. self.env.process(self.handel_packet(packet))
  43. # yield self.env.timeout(1)
  44. else:
  45. yield self.env.timeout(1)
  46. def manage_queue(self):
  47. if len(self.queue) > self.max_capacity:
  48. self.queue = []
  49. def handel_packet(self, packet):
  50. with self.resource_queue.request() as req:
  51. yield req
  52. yield self.env.timeout(1)
  53. self.forward_packet(packet)
  54. def forward_packet(self, packet):
  55. self.env.process(self.net.forward_packet(packet))
  56. def __hash__(self):
  57. return self.id.__hash__()
  58. def __repr__(self):
  59. return self.id