66 lines
2.1 KiB
Python
Raw Normal View History

2024-06-25 17:45:10 -05:00
from random import randint
2024-07-09 19:11:29 -05:00
from constants import *
2024-06-25 17:45:10 -05:00
2024-07-18 17:09:54 -05:00
def calculate_subnets(node_list, num_subnets, replication_factor):
"""
Calculate in which subnet(s) to place each node.
This PoC does NOT require this to be analyzed,
nor to find the best solution.
Hence, we just use a simple model here:
1. Iterate all nodes and place each node in the subsequent subnet
2. If the subnet list can not be filled, start again from the top of the list
3. If each subnet does NOT have at least up to REPLICATION_FACTOR nodes, then
fill up the list with nodes up to the factor.
NOTE: This might be incomplete and/or buggy, but should be sufficient for
the purpose of the PoC.
If however, you find a bug, please report.
"""
# key of dict is the subnet number
2024-07-09 19:11:29 -05:00
subnets = {}
for i, n in enumerate(node_list):
2024-07-10 18:41:50 -05:00
idx = i % num_subnets
2024-06-25 17:45:10 -05:00
# each key has an array, so multiple nodes can be filter
# into a subnet
2024-06-25 17:45:10 -05:00
if idx not in subnets:
subnets[idx] = []
subnets[idx].append(n)
listlen = len(node_list)
i = listlen
# if there are less nodes than subnets
2024-07-10 18:41:50 -05:00
while i < num_subnets:
2024-06-25 17:45:10 -05:00
subnets[i] = []
2024-07-09 19:11:29 -05:00
subnets[i].append(node_list[i % listlen])
2024-06-25 17:45:10 -05:00
i += 1
# if not each subnet has at least factor number of nodes, fill up
2024-07-18 17:09:54 -05:00
if listlen < replication_factor * num_subnets:
2024-06-25 17:45:10 -05:00
for subnet in subnets:
2024-07-09 19:11:29 -05:00
last = subnets[subnet][len(subnets[subnet]) - 1].get_id()
2024-06-25 17:45:10 -05:00
idx = -1
# what is the last filled index of a subnet row
2024-07-09 19:11:29 -05:00
for j, n in enumerate(node_list):
2024-06-25 17:45:10 -05:00
if n.get_id() == last:
2024-07-09 19:11:29 -05:00
idx = j + 1
# fill up until factor
2024-07-18 17:09:54 -05:00
while len(subnets[subnet]) < replication_factor:
# wrap index if at end
2024-07-09 19:11:29 -05:00
if idx > len(node_list) - 1:
2024-06-25 17:45:10 -05:00
idx = 0
# don't add same node multiple times
2024-06-25 17:45:10 -05:00
if node_list[idx] in subnets[subnet]:
idx += 1
continue
subnets[subnet].append(node_list[idx])
idx += 1
return subnets