import os
import json
import time
import re
import boto3
from kubernetes import client, config, watch
from kubernetes.client.rest import ApiException
# Load K8s in-cluster config
config.load_incluster_config()
v1 = client.CoreV1Api()
batch_v1 = client.BatchV1Api()
ns = os.environ['NAMESPACE']
bucket = os.environ['BUCKET']
s3 = boto3.client('s3', region_name=os.environ.get('AWS_REGION', 'us-east-1'))
def parse_spec(spec_json):
return json.loads(spec_json)
def compute_partitions(input_prefix, num_mappers):
objs = s3.list_objects_v2(Bucket=bucket, Prefix=input_prefix)
files = [obj['Key'] for obj in objs.get('Contents', []) if not obj['Key'].endswith('/')]
files.sort()
partitions = [[] for _ in range(num_mappers)]
for i, f in enumerate(files):
partitions[i % num_mappers].append(f)
return [{'files': p} for p in partitions]
def create_configmap(job_id, data):
cm = client.V1ConfigMap(
metadata=client.V1ObjectMeta(name=f"{job_id}-config", namespace=ns),
data=data
)
v1.create_namespaced_config_map(ns, cm)
def delete_configmap(job_id):
try:
v1.delete_namespaced_config_map(f"{job_id}-config", ns)
except:
pass
def create_job(job_name, image, num_parallel, config_cm_name, extra_env=None):
pod_env = [
{"name": "BUCKET", "value": bucket},
{"name": "POD_NAME", "valueFrom": {"fieldRef": {"fieldPath": "metadata.name"}}},
]
if extra_env:
pod_env += extra_env
job = client.V1Job(
api_version="batch/v1",
kind="Job",
metadata=client.V1ObjectMeta(
name=job_name,
namespace=ns,
labels={"app": job_name}
),
spec=client.V1JobSpec(
parallelism=num_parallel,
completions=num_parallel,
backoff_limit=3,
ttl_seconds_after_finished=300, # Cleanup
template=client.V1PodTemplateSpec(
metadata=client.V1ObjectMeta(labels={"app": job_name}),
spec=client.V1PodSpec(
restart_policy="OnFailure",
containers=[
client.V1Container(
name="worker",
image=image,
env=pod_env,
volume_mounts=[{"name": "config", "mountPath": "/config"}],
resources={
"requests": {"cpu": "100m", "memory": "128Mi"},
"limits": {"cpu": "500m", "memory": "512Mi"}
}
)
],
volumes=[{"name": "config", "configMap": {"name": config_cm_name}}]
)
)
)
)
return batch_v1.create_namespaced_job(ns, job)
def wait_for_job(job_name, expected_succeeded, timeout=3600, max_retries=3):
start = time.time()
retries = 0
while time.time() - start < timeout:
try:
status = batch_v1.read_namespaced_job_status(job_name, ns)
succ = status.status.succeeded or 0
failed = status.status.failed or 0
if succ == expected_succeeded:
print(f"Job {job_name} succeeded")
return True
if failed > 0:
print(f"Job {job_name} failed, retry {retries+1}")
retries += 1
if retries >= max_retries:
batch_v1.delete_namespaced_job(job_name, ns)
raise Exception(f"Job {job_name} failed after retries")
time.sleep(30)
time.sleep(10)
except ApiException as e:
print(f"Error polling job: {e}")
time.sleep(10)
raise Exception(f"Job {job_name} timeout")
def process_job(cm):
name = cm.metadata.name
job_id = name # Use cm name as job_id
spec = parse_spec(cm.data['spec'])
input_prefix = spec['input_prefix']
num_mappers = spec['num_mappers']
num_reducers = spec['num_reducers']
mapper_image = spec['mapper_image']
reducer_image = spec['reducer_image']
print(f"Processing MR job {job_id}: {spec}")
# Mark as processing
cm.metadata.annotations = {"status": "processing"}
v1.patch_namespaced_config_map(name, ns, cm)
try:
# Partition input
partitions = compute_partitions(input_prefix, num_mappers)
mapper_config_data = {
"partitions": json.dumps({"partitions": partitions}),
"num_reducers": str(num_reducers),
"job_id": job_id
}
create_configmap(job_id, mapper_config_data)
# Launch mappers
mapper_job = create_job(f"{job_id}-mappers", mapper_image, num_mappers, f"{job_id}-config",
[{"name": "JOB_ID", "value": job_id}, {"name": "NUM_REDUCERS", "value": str(num_reducers)}])
wait_for_job(f"{job_id}-mappers", num_mappers)
# Reducer config
reducer_config_data = {
"num_mappers": str(num_mappers),
"job_id": job_id
}
create_configmap(job_id, reducer_config_data) # Overwrite
# Launch reducers
reducer_job = create_job(f"{job_id}-reducers", reducer_image, num_reducers, f"{job_id}-config",
[{"name": "JOB_ID", "value": job_id}, {"name": "NUM_MAPPERS", "value": str(num_mappers)}])
wait_for_job(f"{job_id}-reducers", num_reducers)
# Success
output_prefix = f"output/{job_id}/"
cm.metadata.annotations = {"status": "completed", "output": output_prefix}
print(f"MR job {job_id} completed, output: s3://{bucket}/{output_prefix}")
except Exception as e:
print(f"MR job {job_id} failed: {e}")
cm.metadata.annotations = {"status": "failed", "error": str(e)}
finally:
v1.patch_namespaced_config_map(name, ns, cm)
delete_configmap(job_id)
# Watch ConfigMaps
w = watch.Watch()
for event in w.stream(v1.list_namespaced_config_map, namespace=ns, label_selector="app=mapreduce-job"):
cm = event['object']
if cm.metadata.annotations and cm.metadata.annotations.get('processed', 'false') == 'true':
continue
if not cm.data.get('spec'):
continue
process_job(cm)
cm.metadata.annotations = {"processed": "true"}
v1.patch_namespaced_config_map(cm.metadata.name, ns, cm)