Skip to content

About

Distributed MapReduce system supporting multiple workers, fault tolerance, and automatic job partitioning in Python.

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

76 Commits

Folders and files

Repository files navigation

Distributed MapReduce Framework

A distributed MapReduce framework implementation in Python, inspired by Google's original MapReduce paper. This framework enables distributed processing of large datasets across a cluster of worker nodes, with fault tolerance and automatic task distribution.

Overview

This project implements a complete MapReduce system consisting of:

  • Manager: Coordinates job execution, distributes tasks to workers, and handles fault tolerance
  • Worker: Executes map and reduce tasks assigned by the manager
  • Job Submission: Command-line interface for submitting MapReduce jobs

The framework supports distributed processing with automatic task partitioning, fault tolerance through heartbeat monitoring, and concurrent execution across multiple worker nodes.

Architecture

┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│   Manager   │    │   Worker 1  │    │   Worker 2  │
│             │    │             │    │             │
│ - Job Queue │◄──►│ - Map Tasks │    │ - Map Tasks │
│ - Task Dist │    │ - Reduce    │    │ - Reduce    │
│ - Fault Tol │    │ - Heartbeat │    │ - Heartbeat │
└─────────────┘    └─────────────┘    └─────────────┘
       ▲                   ▲                   ▲
       │                   │                   │
       └───────────────────┼───────────────────┘
                           │
                    ┌─────────────┐
                    │   Client    │
                    │             │
                    │ - Job Submit│
                    └─────────────┘

Features

  • Distributed Processing: Execute MapReduce jobs across multiple worker nodes
  • Fault Tolerance: Automatic detection and recovery from worker failures
  • Task Partitioning: Automatic input file partitioning and output merging
  • Concurrent Execution: Parallel map and reduce task execution
  • Heartbeat Monitoring: UDP-based worker health monitoring
  • Job Queuing: Support for multiple concurrent job submissions
  • Flexible Executables: Support for any language (Python, Shell, etc.)

Installation

Prerequisites

  • Python 3.8 or higher
  • Unix-like operating system (Linux, macOS, WSL)

Setup

  1. Clone the repository:

    git clone <repository-url>
    cd distributed-mapreduce-framework
  2. Create virtual environment:

    python3 -m venv env
    source env/bin/activate  # On Windows: env\Scripts\activate
  3. Install dependencies:

    pip install -r requirements.txt
    pip install -e .

Quick Start

1. Start the MapReduce Server

# Start manager and workers
./bin/mapreduce start

# Check server status
./bin/mapreduce status

2. Submit a MapReduce Job

# Submit a word count job with default settings
mapreduce-submit

# Or specify custom parameters
mapreduce-submit \
  --input tests/testdata/input_small \
  --output output \
  --mapper tests/testdata/exec/wc_map.sh \
  --reducer tests/testdata/exec/wc_reduce.sh \
  --nmappers 2 \
  --nreducers 2

3. View Results

# Check output files
ls output/
cat output/part-*

# Stop the server
./bin/mapreduce stop

Usage

Server Management

The bin/mapreduce script provides server management commands:

# Start server (manager + 2 workers)
./bin/mapreduce start

# Stop server gracefully
./bin/mapreduce stop

# Restart server
./bin/mapreduce restart

# Check server status
./bin/mapreduce status

Job Submission

Use mapreduce-submit to submit MapReduce jobs:

mapreduce-submit [OPTIONS]

Options:
  --input, -i PATH        Input directory (default: tests/testdata/input)
  --output, -o PATH       Output directory (default: output)
  --mapper, -m PATH       Mapper executable (default: tests/testdata/exec/wc_map.sh)
  --reducer, -r PATH      Reducer executable (default: tests/testdata/exec/wc_reduce.sh)
  --nmappers N            Number of mappers (default: 2)
  --nreducers N           Number of reducers (default: 2)
  --host, -h HOST         Manager host (default: localhost)
  --port, -p PORT         Manager port (default: 6000)

Manual Server Control

You can also run components manually:

# Start manager
mapreduce-manager --host localhost --port 6000 --loglevel=DEBUG

# Start workers (in separate terminals)
mapreduce-worker --host localhost --port 6001 --manager-host localhost --manager-port 6000 --loglevel=DEBUG
mapreduce-worker --host localhost --port 6002 --manager-host localhost --manager-port 6000 --loglevel=DEBUG

MapReduce Programming

Writing Mapper Programs

Mappers read from stdin and write key-value pairs to stdout:

#!/usr/bin/env python3
"""Word count mapper example."""
import sys

for line in sys.stdin:
    words = line.strip().split()
    for word in words:
        print(f"{word}\t1")

Writing Reducer Programs

Reducers read sorted key-value pairs from stdin and write results to stdout:

#!/usr/bin/env python3
"""Word count reducer example."""
import sys
import itertools

def reduce_one_group(key, group):
    """Reduce one group."""
    count = sum(1 for _ in group)
    print(f"{key}\t{count}")

def keyfunc(line):
    """Return the key from a TAB-delimited key-value pair."""
    return line.partition("\t")[0]

def main():
    """Divide sorted lines into groups that share a key."""
    for key, group in itertools.groupby(sys.stdin, keyfunc):
        reduce_one_group(key, group)

if __name__ == "__main__":
    main()

Example: Word Count

The project includes a complete word count example:

# Input files
head tests/testdata/input_small/*
# ==> tests/testdata/input_small/file01 <==
# hello world
# hello eecs485
# 
# ==> tests/testdata/input_small/file02 <==
# goodbye autograder
# hello autograder

# Run word count
mapreduce-submit --input tests/testdata/input_small

# Check results
cat output/part-*
# hello	3
# autograder	2
# eecs485	1
# goodbye	1
# world	1

Architecture Details

Manager

The Manager coordinates the entire MapReduce execution:

  • Job Management: Queues and executes MapReduce jobs sequentially
  • Task Distribution: Assigns map and reduce tasks to available workers
  • Fault Tolerance: Monitors worker health via UDP heartbeats
  • Input Partitioning: Divides input files into map tasks using round-robin
  • Output Coordination: Collects and organizes intermediate results

Worker

Workers execute individual map and reduce tasks:

  • Map Tasks:

    • Run mapper executable on assigned input files
    • Partition output by key hash (modulo num_reducers)
    • Sort intermediate files
    • Transfer results to shared directory
  • Reduce Tasks:

    • Merge sorted intermediate files using heapq.merge()
    • Run reducer executable on merged input
    • Write final output to specified directory

Communication Protocol

The framework uses JSON messages over TCP/UDP:

  • TCP: Job submission, task assignment, completion notifications
  • UDP: Heartbeat messages for fault tolerance

Key message types:

  • register: Worker registration
  • register_ack: Registration acknowledgment
  • new_manager_job: Job submission
  • new_map_task: Map task assignment
  • new_reduce_task: Reduce task assignment
  • finished: Task completion notification
  • heartbeat: Worker health check
  • shutdown: Graceful shutdown

Testing

Run Unit Tests

# Run all tests
pytest -vvsx --log-cli-level=INFO

# Run specific test categories
pytest -vvsx --log-cli-level=INFO tests/test_manager_*.py
pytest -vvsx --log-cli-level=INFO tests/test_worker_*.py
pytest -vvsx --log-cli-level=INFO tests/test_integration_*.py

Test Fault Tolerance

# Start server
./bin/mapreduce start

# Submit slow job
mapreduce-submit \
  --input tests/testdata/input_small \
  --mapper tests/testdata/exec/wc_map_slow.sh \
  --reducer tests/testdata/exec/wc_reduce_slow.sh

# Kill a worker while job is running
pgrep -f mapreduce-worker | head -n1 | xargs kill

# Check logs for task reassignment
tail -F var/log/*.log

Performance Testing

# Test with larger dataset
mapreduce-submit \
  --input tests/testdata/input_large \
  --nmappers 4 \
  --nreducers 4

# Monitor resource usage
top -p $(pgrep -f mapreduce)

Configuration

Logging

Configure logging levels and output:

# Debug logging
mapreduce-manager --loglevel=DEBUG
mapreduce-worker --loglevel=DEBUG

# Log to file
mapreduce-manager --logfile var/log/manager.log
mapreduce-worker --logfile var/log/worker.log

Network Configuration

# Custom host/port configuration
mapreduce-manager --host 0.0.0.0 --port 7000
mapreduce-worker --host 192.168.1.100 --port 7001 --manager-host 192.168.1.50 --manager-port 7000

Troubleshooting

Common Issues

  1. Port already in use:

    # Check for running processes
    pgrep -f mapreduce
    
    # Kill existing processes
    pkill -f mapreduce
  2. Worker not responding:

    # Check worker logs
    tail var/log/worker-*.log
    
    # Restart workers
    ./bin/mapreduce restart
  3. Job hanging:

    # Check manager logs
    tail var/log/manager.log
    
    # Verify worker status
    ./bin/mapreduce status

Debug Mode

Enable debug logging for detailed troubleshooting:

# Start with debug logging
mapreduce-manager --loglevel=DEBUG --logfile var/log/manager-debug.log
mapreduce-worker --loglevel=DEBUG --logfile var/log/worker-debug.log

Development

Project Structure

distributed-mapreduce-framework/
├── bin/
│   └── mapreduce              # Server management script
├── mapreduce/
│   ├── manager/
│   │   ├── __init__.py
│   │   └── __main__.py        # Manager implementation
│   ├── worker/
│   │   ├── __init__.py
│   │   └── __main__.py        # Worker implementation
│   ├── utils/
│   │   └── __init__.py        # Shared utilities
│   └── submit.py              # Job submission CLI
├── tests/
│   ├── testdata/              # Test data and executables
│   └── test_*.py              # Unit tests
├── requirements.txt           # Python dependencies
├── pyproject.toml            # Package configuration
└── README.md                 # This file

Code Style

The project follows Python style guidelines:

# Check code style
pylint mapreduce/
pycodestyle mapreduce/
pydocstyle mapreduce/

Adding Features

  1. New Message Types: Add to communication protocol in both Manager and Worker
  2. Custom Partitioning: Modify input partitioning logic in Manager
  3. Additional Fault Tolerance: Extend heartbeat monitoring system
  4. Performance Optimizations: Optimize task distribution and execution

License

This project is part of EECS 485 coursework at the University of Michigan.

Acknowledgments

  • Inspired by Google's original MapReduce paper
  • Built for educational purposes in distributed systems
  • Includes comprehensive test suite and examples

About

Distributed MapReduce system supporting multiple workers, fault tolerance, and automatic job partitioning in Python.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages