class Resource:
def __init__(self, id, capacity_cpu, capacity_ram, labels=None):
self.id = id
self.capacity_cpu = capacity_cpu
self.capacity_ram = capacity_ram
self.labels = labels if labels else {}
# Current usage
self.used_cpu = 0
self.used_ram = 0
self.allocated_tasks = []
def available_cpu(self):
return self.capacity_cpu - self.used_cpu
def available_ram(self):
return self.capacity_ram - self.used_ram
def can_fit(self, task):
# Constraint 1: Capacity Check
if task.req_cpu > self.available_cpu():
return False
if task.req_ram > self.available_ram():
return False
# Constraint 2: Label/Attribute Matching (Affinity)
# All required labels in the task must exist on the resource with matching values
for key, value in task.req_labels.items():
if self.labels.get(key) != value:
return False
# Constraint 3: Anti-Affinity (Conflict Check)
# This task cannot run on this resource if it conflicts with an already running task
for allocated_task in self.allocated_tasks:
if task.conflicts_with(allocated_task):
return False
return True
def allocate(self, task):
if not self.can_fit(task):
return False
self.used_cpu += task.req_cpu
self.used_ram += task.req_ram
self.allocated_tasks.append(task)
task.assigned_resource = self.id
return True
def __repr__(self):
return f"[Node {self.id} | CPU: {self.used_cpu}/{self.capacity_cpu} | RAM: {self.used_ram}/{self.capacity_ram}]"
class Task:
def __init__(self, id, req_cpu, req_ram, req_labels=None, conflicts=None):
self.id = id
self.req_cpu = req_cpu
self.req_ram = req_ram
self.req_labels = req_labels if req_labels else {}
self.conflicts = conflicts if conflicts else [] # List of task IDs it cannot share a node with
self.assigned_resource = None
def conflicts_with(self, other_task):
return other_task.id in self.conflicts
def __repr__(self):
return f"Task({self.id})"
class Allocator:
def __init__(self, resources):
self.resources = resources
def attempt_allocation(self, tasks):
"""
Greedy Best-Fit Algorithm:
Iterate through tasks and assign them to the first valid resource.
"""
unallocated = []
for task in tasks:
allocated = False
# Sort resources by available capacity (tries to fill smaller nodes first or balance load)
# Here we just iterate linearly, but sorting is possible.
for resource in self.resources:
if resource.can_fit(task):
resource.allocate(task)
allocated = True
print(f"✅ Allocated {task.id} to {resource.id}")
break
if not allocated:
unallocated.append(task)
print(f"❌ Failed to allocate {task.id} (Constraints not met)")
return unallocated
# ==========================================
# Simulation / Usage Example
# ==========================================
# 1. Define Resources (Nodes)
r1 = Resource("Node-1", capacity_cpu=4, capacity_ram=16, labels={"zone": "us-east", "gpu": "true"})
r2 = Resource("Node-2", capacity_cpu=8, capacity_ram=32, labels={"zone": "us-west"})
r3 = Resource("Node-3", capacity_cpu=2, capacity_ram=8, labels={"zone": "us-east"})
resources = [r1, r2, r3]
# 2. Define Tasks (Workloads)
# Task A: Needs GPU, 2 CPU
tA = Task("Web-Server", req_cpu=2, req_ram=4, req_labels={"gpu": "true"})
# Task B: Needs to be in US-East, 2 CPU
tB = Task("Analytics", req_cpu=2, req_ram=8, req_labels={"zone": "us-east"})
# Task C: Heavy load, 8 CPU
tC = Task("Database", req_cpu=8, req_ram=16)
# Task D: Small task, but CONFLICTS with Task A (e.g., they use the same port)
tD = Task("Monitor", req_cpu=1, req_ram=1, conflicts=["Web-Server"])
tasks = [tA, tB, tC, tD]
# 3. Run Allocation
print("--- Starting Allocation ---")
allocator = Allocator(resources)
failed_tasks = allocator.attempt_allocation(tasks)
print("\n--- Final Cluster State ---")
for r in resources:
print(f"{r} runs: {[t.id for t in r.allocated_tasks]}")
print("\n--- Summary ---")
print(f"Failed Tasks: {[t.id for t in failed_tasks]}")