Fill This Form To Receive Instant Help
Homework answers / question archive / In this exercise, I want to write few classes to simulate a server that's taking connections from the outside and then a load balancer that ensures that there are enough servers to serve those connections
In this exercise, I want to write few classes to simulate a server that's taking connections from the outside and then a load balancer that ensures that there are enough servers to serve those connections.
I am done with the Server class but have problem trying to write the LoadBalancing class
This is the server class
#Begin Portion 1# import random class Server: def __init__(self): """Creates a new server instance, with no active connections.""" self.connections = {} def add_connection(self, connection_id): """Adds a new connection to this server.""" connection_load = random.random()*10+1 # Add the connection to the dictionary with the calculated load self.connections[connection_id] = connection_load def close_connection(self, connection_id): """Closes a connection on this server.""" # Remove the connection from the dictionary del self.connections[connection_id] def load(self): """Calculates the current load for all connections.""" total = 0 # Add up the load for each of the connections for load_val in self.connections.values(): total += load_val return total def __str__(self): """Returns a string with the current load of the server""" return "{:.2f}%".format(self.load())
This is a Server instance and i'm adding a connection to it, and then check the load:
server = Server() server.add_connection("192.168.1.1") print(server.load()) Then I closed the connection with this code
server.close_connection("192.168.1.1") print(server.load())
This is the LoadBalancing class. This class starts with only one server available. When a connection gets added, it will randomly select a server to serve that connection, and then pass on the connection to the server. The LoadBalancing class also needs to keep track of the ongoing connections to be able to close them.
#Begin Portion 2# class LoadBalancing: def __init__(self): """Initialize the load balancing system with one server""" self.connections = {} self.servers = [Server()] def add_connection(self, connection_id): """Randomly selects a server and adds a connection to it.""" server = random.choice(self.servers) # Add the connection to the dictionary with the selected server # Add the connection to the server self.connections[connection_id] = server def close_connection(self, connection_id): """Closes the connection on the the server corresponding to connection_id.""" # Find out the right server # Close the connection on the server # Remove the connection from the load balancer def avg_load(self): """Calculates the average load of all servers""" # Sum the load of each server and divide by the amount of servers sum = 0 for load in self.server return sum / len(self.server) def ensure_availability(self): """If the average load is higher than 50, spin up a new server""" pass def __str__(self): """Returns a string with the load for each server.""" loads = [str(server) for server in self.servers] return "[{}]".format(",".join(loads)) #End Portion 2#
As with the Server class, this class is currently incomplete. You need to fill in the gaps to make it work correctly. For example, in this snippet i am to add a connection in the load balancer, assign it to a running server and then the load should be more than zero:
l = LoadBalancing() l.add_connection("fdca:83d2::f20d") print(l.avg_load())
This is the error i get when trying to run the above code
Please help me out with the Loadbalancing part of the code
TypeError Traceback (most recent call last) <ipython-input-19-6ac6d0eb4c11> in <module> 1 l = LoadBalancing() 2 l.add_connection("fdca:83d2::f20d") > 3 print(l.avg_load()) <ipython-input-18-ab03a6c80330> in avg_load(self) 26 sum = 0 27 for load in self.connections.values(): > 28 sum += load 29 return sum / len(self.connections) 30 TypeError: unsupported operand type(s) for +=: 'int' and 'Server'
What if we add a new server?
l.servers.append(Server()) print(l.avg_load())
The average load should now be half of what it was before. If it's not, make sure you correctly fill in the missing gaps for the add_connection and avg_load methods so that this code works correctly.
Hint: You can iterate through the all servers in the self.servers list to get the total server load amount and then divide by the length of the self.servers list to compute the average load amount.
Fantastic! Now what about closing the connection?
l.close_connection("fdca:83d2::f20d") print(l.avg_load())
Fill in the code of the LoadBalancing class to make the load go back to zero once the connection is closed.
Great job! Before, we added a server manually. But we want this to happen automatically when the average load is more than 50%. To make this possible, fill in the missing code for the ensure_availability method and call it from the add_connection method after a connection has been added. You can test it with the following code:
for connection in range(20): l.add_connection(connection) print(l)
The code above adds 20 new connections and then prints the loads for each server in the load balancer. If you coded correctly, new servers should have been added automatically to ensure that the average load of all servers is not more than 50%.
Run the following code to verify that the average load of the load balancer is not more than 50%.
print(l.avg_load())
Answer:
Server class
import random class Server: def __init__(self): """Creates a new server instance, with no active connections.""" self.connections = {} def add_connection(self, connection_id): """Adds a new connection to this server.""" connection_load = random.random()*10+1 # Add the connection to the dictionary with the calculated load self.connections[connection_id] = connection_load def close_connection(self, connection_id): """Closes a connection on this server.""" # Remove the connection from the dictionary del self.connections[connection_id] def load(self): """Calculates the current load for all connections.""" total = 0 # Add up the load for each of the connections for load_val in self.connections.values(): total += load_val return total def __str__(self): """Returns a string with the current load of the server""" return "{:.2f}%".format(self.load())
Load Balancing class
class LoadBalancing: def __init__(self): """Initialize the load balancing system with one server""" self.connections = {} self.servers = [Server()] def add_connection(self, connection_id): """Randomly selects a server and adds a connection to it.""" server = random.choice(self.servers) # Add the connection to the dictionary with the selected server self.connections[connection_id] = server # Add the connection to the server server.add_connection(connection_id) # Check if the average load is high, and add server to ensure availability self.ensure_availability() def close_connection(self, connection_id): """Closes the connection on the the server corresponding to connection_id.""" # Find out the right server server = self.connections[connection_id] # Close the connection on the server server.close_connection(connection_id) # Remove the connection from the load balancer del self.connections[connection_id] def avg_load(self): """Calculates the average load of all servers""" # Sum the load of each server and divide by the amount of servers sum = 0 for server in self.servers: sum += server.load() return sum / len(self.servers) def ensure_availability(self): """If the average load is higher than 50, spin up a new server""" if self.avg_load() > 50: self.servers.append(Server()) def __str__(self): """Returns a string with the load for each server.""" loads = [str(server) for server in self.servers] return "[{}]".format(",".join(loads))
Step-by-step explanation
Please find the driver code to test the program. I have added additional print methods for readability.
# Creating a new server and verifyin the load. print("") print("Creating a new server.") server = Server() print("Adding connection 192.168.1.1 to the server") server.add_connection("192.168.1.1") print("Checking server load.") print(server.load()) # Closing the connection and verifyin the load is 0 print("") print("Closing connection 192.168.1.1") server.close_connection("192.168.1.1") print("Checking server load (should be 0 now).") print(server.load()) # Creating a load balancer and adding connection # Verifying the average load print("") print("Creating a load balancer.") l = LoadBalancing() print("Adding connection fdca:83d2::f20d") l.add_connection("fdca:83d2::f20d") print("Checking average load for the balancer.") print(l.avg_load()) # Adding a new server and checking average load. print("") print("Adding a new server to the balancer.") l.servers.append(Server()) print("Checking average load (should be half now)") print(l.avg_load()) # Closing the connection and verifying the average load. print("") print("Closing connection fdca:83d2::f20d") l.close_connection("fdca:83d2::f20d") print("Checking average load (should be 0 now)") print(l.avg_load()) # Adding 20 connections and verifying that new servers are added # so that the average load is less than 50% print("") print("Adding 20 new connections.") for connection in range(20): l.add_connection(connection) print(l) print("Checking average load (should be less than 50%)") print(l.avg_load())
please use this google drive link to download the answer file.
https://drive.google.com/file/d/1op3M1FAowmRqOuJjHIYFIf9JNjnlSd2p/view?usp=sharing
note: if you have any trouble in viewing/downloading the answer from the given link, please use this below guide to understand the whole process.
https://helpinhomework.org/blog/how-to-obtain-answer-through-googledrive-link