Fill This Form To Receive Instant Help

Help in Homework
trustpilot ratings
google ratings


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

Computer Science

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())

 

Option 1

Low Cost Option
Download this past answer in few clicks

3.87 USD

PURCHASE SOLUTION

Already member?


Option 2

Custom new solution created by our subject matter experts

GET A QUOTE