Skip to content

Commit

Permalink
Tests folder is added from AHC to this project
Browse files Browse the repository at this point in the history
  • Loading branch information
cengwins committed Jan 14, 2022
1 parent 5567e82 commit 1f65f96
Show file tree
Hide file tree
Showing 38 changed files with 2,992 additions and 0 deletions.
Empty file added AnonymousNetworks/__init__.py
Empty file.
80 changes: 80 additions & 0 deletions AnonymousNetworks/testIEEE1394.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env python

# the project root must be in PYTHONPATH for imports
# $ export PYTHONPATH=$(pwd); python tests/AnonymousNetworks/testItaiRodeh.py

import sys
import threading
from time import sleep

import matplotlib.pyplot as plt
import networkx as nx
from ahc.Ahc import Topology
from Channels.Channels import P2PFIFOPerfectChannel

from AnonymousNetworks.IEEE1394 import FireWireNode

ACTIVE_NODE_COLOUR = "#98971a"
PASSIVE_NODE_COLOUR = "#7c6f64"
LEADER_NODE_COLOUR = "#d79921"
CONTENDING_NODE_COLOUR = "#b16286"
EDGE_COLOUR = "#3c3836"

FPS = 0.4


def main():
n = int(sys.argv[1])
print(f"Creating a tree with size {n}")
G = nx.random_tree(n)

update = threading.Event()
draw_delay = threading.Event()
plt.ion()
fig = plt.figure(num=0)

topology = Topology()
topology.construct_from_graph(G, FireWireNode, P2PFIFOPerfectChannel)
topology.start()

FireWireNode.callback = update
FireWireNode.draw_delay = draw_delay

while True:
update.wait()
node_colours = list()

G = Topology().G
pos = nx.spectral_layout(G, center=(0, 0))

for nodeID in Topology().nodes:
node = Topology().nodes[nodeID]

if node.is_leader:
node_colours.append(LEADER_NODE_COLOUR)
elif node.in_root_contention:
node_colours.append(CONTENDING_NODE_COLOUR)
elif node.is_terminated:
node_colours.append(PASSIVE_NODE_COLOUR)
elif not node.is_terminated:
node_colours.append(ACTIVE_NODE_COLOUR)

nx.draw(
G,
pos,
node_color=node_colours,
edge_color=EDGE_COLOUR,
with_labels=True,
font_weight="bold",
)

fig.canvas.draw()
fig.canvas.flush_events()
fig.clear()
update.clear()
draw_delay.set()
sleep(1.0 / FPS)


if __name__ == "__main__":
main()
95 changes: 95 additions & 0 deletions AnonymousNetworks/testItaiRodeh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#!/usr/bin/env python

# the project root must be in PYTHONPATH for imports
# $ export PYTHONPATH=$(pwd); python tests/AnonymousNetworks/testItaiRodeh.py

import sys
import threading
from math import atan2, cos, radians, sin
from time import sleep

import matplotlib.pyplot as plt
import networkx as nx
from ahc.Ahc import Topology
from Channels.Channels import P2PFIFOPerfectChannel

from AnonymousNetworks.ItaiRodeh import ItaiRodehNode, State

ACTIVE_NODE_COLOUR = "#ff0000"
PASSIVE_NODE_COLOUR = "#e0e0e0"
LEADER_NODE_COLOUR = "#ff00ff"
EDGE_COLOUR = "#1a1c20"

FPS = 1


def main():
n = int(sys.argv[1])
print(f"Creating a ring with size {n}")
G = nx.cycle_graph(n)

plt.ion()
fig = plt.figure(num=0)

topology = Topology()
topology.construct_from_graph(G, ItaiRodehNode, P2PFIFOPerfectChannel)
topology.start()
ItaiRodehNode.ring_size = n

update = threading.Event()
draw_delay = threading.Event()
ItaiRodehNode.callback = update
ItaiRodehNode.draw_delay = draw_delay

while True:
update.wait()
assumed_ids = list()
node_colours = list()

G = Topology().G
pos = nx.circular_layout(G, center=(0, 0))

for nodeID in Topology().nodes:
node = Topology().nodes[nodeID]
G.nodes[nodeID]["id_p"] = node.id_p
assumed_ids.append(node.id_p)

if node.state == State.active:
node_colours.append(ACTIVE_NODE_COLOUR)
elif node.state == State.passive:
node_colours.append(PASSIVE_NODE_COLOUR)
elif node.state == State.leader:
node_colours.append(LEADER_NODE_COLOUR)

node_id_label_pos = {}
for key in pos:
x, y = pos[key]
theta = atan2(y, x) + radians(75)
d = 0.1
node_id_label_pos[key] = (x + d * cos(theta), y + d * sin(theta))

node_id_labels = nx.get_node_attributes(G, "id_p")

nx.draw(
G,
pos,
node_color=node_colours,
edge_color=EDGE_COLOUR,
with_labels=False,
font_weight="bold",
)

nx.draw_networkx_labels(G, node_id_label_pos, node_id_labels)

fig.text(0.2, 0.2, f"Round: {ItaiRodehNode.global_round}")

fig.canvas.draw()
fig.canvas.flush_events()
fig.clear()
update.clear()
draw_delay.set()
sleep(1.0 / FPS)


if __name__ == "__main__":
main()
65 changes: 65 additions & 0 deletions Broadcasting/testbroadcasting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import os
import sys
import random

sys.path.insert(0, os.getcwd())

import networkx as nx
import matplotlib.pyplot as plt

from ahc.Ahc import ComponentModel, Event, ConnectorTypes, Topology, EventTypes
from ahc.Ahc import ComponentRegistry
from Broadcasting.Broadcasting import ControlledFlooding
from Channels.Channels import P2PFIFOFairLossChannel
from LinkLayers.GenericLinkLayer import LinkLayer

registry = ComponentRegistry()

class AdHocNode(ComponentModel):
def on_message_from_top(self, eventobj: Event):
self.send_down(Event(self, EventTypes.MFRT, eventobj.eventcontent))

def on_message_from_bottom(self, eventobj: Event):
self.send_up(Event(self, EventTypes.MFRB, eventobj.eventcontent))

def __init__(self, componentname, componentid):
# SUBCOMPONENTS
self.broadcastservice = ControlledFlooding("SimpleFlooding", componentid)
self.linklayer = LinkLayer("LinkLayer", componentid)

# CONNECTIONS AMONG SUBCOMPONENTS
self.broadcastservice.connect_me_to_component(ConnectorTypes.DOWN, self.linklayer)
self.linklayer.connect_me_to_component(ConnectorTypes.UP, self.broadcastservice)

# Connect the bottom component to the composite component....
self.linklayer.connect_me_to_component(ConnectorTypes.DOWN, self)
self.connect_me_to_component(ConnectorTypes.UP, self.linklayer)

super().__init__(componentname, componentid)

# self.eventhandlers[EventTypes.MFRT] = self.onMessageFromTop
# self.eventhandlers["messagefromchannel"] = self.onMessageFromChannel

def main():
# G = nx.Graph()
# G.add_nodes_from([1, 2])
# G.add_edges_from([(1, 2)])
# nx.draw(G, with_labels=True, font_weight='bold')
# plt.draw()
G = nx.random_geometric_graph(19, 0.5)
topo = Topology()
topo.construct_from_graph(G, AdHocNode, P2PFIFOFairLossChannel)
for ch in topo.channels:
topo.channels[ch].setPacketLossProbability(random.random())
topo.channels[ch].setAverageNumberOfDuplicates(0)

ComponentRegistry().print_components()

topo.start()
topo.plot()
plt.show() # while (True): pass

print(topo.nodecolors)

if __name__ == "__main__":
main()
78 changes: 78 additions & 0 deletions Clocks/testlogicalclock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import random
import time
import os
import sys
sys.path.insert(0, os.getcwd())
import networkx as nx

from ahc.Ahc import ComponentModel, Event, ConnectorTypes, Topology
from ahc.Ahc import EventTypes
from Channels.Channels import P2PFIFOPerfectChannel
from LinkLayers.GenericLinkLayer import LinkLayer
from NetworkLayers.AllSeeingEyeNetworkLayer import AllSeingEyeNetworkLayer

from Clocks.LogicalClocks import VectorClock


class ApplicationLayerComponent(ComponentModel):

def on_init(self, eventobj: Event):
#print(f"Initializing {self.componentname}.{self.componentinstancenumber}")
if self.componentinstancenumber == 0:
self.send_down(Event(self, EventTypes.MFRT, None))

def on_message_from_bottom(self, eventobj: Event):
randdelay = random.randint(0, 2)
time.sleep(randdelay)
self.send_down(Event(self, EventTypes.MFRT, None))

def __init__(self, componentname, componentinstancenumber):
super().__init__(componentname, componentinstancenumber)


class AdHocNode(ComponentModel):

def on_init(self, eventobj: Event):
#print(f"Initializing {self.componentname}.{self.componentinstancenumber}")
pass
def on_message_from_top(self, eventobj: Event):
self.send_down(Event(self, EventTypes.MFRT, eventobj.eventcontent))

def on_message_from_bottom(self, eventobj: Event):
self.send_up(Event(self, EventTypes.MFRB, eventobj.eventcontent))

def __init__(self, componentname, componentid):
super().__init__(componentname, componentid)

# SUBCOMPONENTSc
self.appllayer = ApplicationLayerComponent("ApplicationLayer", componentid)
self.middleware = VectorClock("VectorClock ", componentid)
self.netlayer = AllSeingEyeNetworkLayer("NetworkLayer", componentid)
self.linklayer = LinkLayer("LinkLayer", componentid)

# CONNECTIONS AMONG SUBCOMPONENTS
self.appllayer.connect_me_to_component(ConnectorTypes.DOWN, self.middleware)
self.middleware.connect_me_to_component(ConnectorTypes.UP, self.appllayer)
self.middleware.connect_me_to_component(ConnectorTypes.DOWN, self.netlayer)
self.netlayer.connect_me_to_component(ConnectorTypes.UP, self.middleware)
self.netlayer.connect_me_to_component(ConnectorTypes.DOWN, self.linklayer)
self.linklayer.connect_me_to_component(ConnectorTypes.UP, self.netlayer)

# Connect the bottom component to the composite component....
self.linklayer.connect_me_to_component(ConnectorTypes.DOWN, self)
self.connect_me_to_component(ConnectorTypes.UP, self.linklayer)


def main():

G = nx.random_geometric_graph(3, 1)
topo = Topology()
topo.construct_from_graph(G, AdHocNode, P2PFIFOPerfectChannel)


topo.start()
time.sleep(20)


if __name__ == "__main__":
main()
49 changes: 49 additions & 0 deletions Consensus/testpaxosconsensus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@

import sys
import time
import os

sys.path.insert(0, os.getcwd())

import networkx as nx

from ahc.Ahc import Topology
from ahc.Ahc import ComponentRegistry
from Channels.Channels import BasicLossyChannel
from Consensus.Paxos.paxos_component import PaxosConsensusComponentModel, Resolution
from itertools import combinations
import logging
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

logger = logging.getLogger(__name__)

registry = ComponentRegistry()

class Client:

def send(self, message:Resolution):
logger.info("For client Resolution message is received from component %s",
message.from_uid.componentinstancenumber)
logger.info("Client received new set value %s", message.value)


def main():
nodes = ['A', 'B', 'C', 'D', 'E']

edges = combinations(nodes, 2)
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
topo = Topology()
topo.construct_from_graph(G, PaxosConsensusComponentModel, BasicLossyChannel)
client = Client()

topo.start()
time.sleep(2)
a_node: PaxosConsensusComponentModel = topo.nodes.get('A')
a_node.data_received_client(client, "Hello World!!!")
waitforit = input("hit something to exit...")


if __name__ == "__main__":
main()
Loading

0 comments on commit 1f65f96

Please sign in to comment.