package main
import (
"bufio"
"fmt"
"io"
"log"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
// ==========================================
// Data Structures
// ==========================================
// Pair represents a Key-Value pair emitted by the Map function
type Pair struct {
Key string
Value int
}
// ==========================================
// MapReduce System
// ==========================================
type MapReduceSystem struct {
MapWorkers int
ReduceWorkers int
}
func NewSystem(mapWorkers, reduceWorkers int) *MapReduceSystem {
return &MapReduceSystem{
MapWorkers: mapWorkers,
ReduceWorkers: reduceWorkers,
}
}
// Run orchestrates the entire flow
func (mrs *MapReduceSystem) Run(inputFile string) map[string]int {
fmt.Println("Starting MapReduce System...")
// 1. Split input into chunks for Mappers
chunks := mrs.splitFile(inputFile, mrs.MapWorkers)
// 2. Map Phase
fmt.Printf("Mapping with %d workers...\n", mrs.MapWorkers)
mapOutput := mrs.runMapPhase(chunks)
// 3. Shuffle Phase (Group by Key)
fmt.Println("Shuffling data...")
shuffledData := mrs.shuffle(mapOutput)
// 4. Reduce Phase
fmt.Printf("Reducing with %d workers...\n", mrs.ReduceWorkers)
finalResult := mrs.runReducePhase(shuffledData)
return finalResult
}
// splitFile reads the file and divides it roughly by line count
func (mrs *MapReduceSystem) splitFile(filename string, numChunks int) [][]string {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Simple logic: read all lines and split slice
// In a real distributed system, this would be byte offsets or blocks
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
chunkSize := (len(lines) + numChunks - 1) / numChunks
var chunks [][]string
for i := 0; i < len(lines); i += chunkSize {
end := i + chunkSize
if end > len(lines) {
end = len(lines)
}
chunks = append(chunks, lines[i:end])
}
return chunks
}
// runMapPhase launches goroutines to process chunks
func (mrs *MapReduceSystem) runMapPhase(chunks [][]string) []Pair {
var wg sync.WaitGroup
wg.Add(len(chunks))
// Channel to collect all intermediate pairs
// Buffer size helps prevent blocking if producers are fast
intermediateChan := make(chan []Pair, len(chunks))
for i, chunk := range chunks {
go func(id int, data []string) {
defer wg.Done()
fmt.Printf(" [Mapper %d] Processing %d lines...\n", id, len(data))
// User Defined Map Function logic goes here
pairs := mapFunction(data)
intermediateChan <- pairs
}(i, chunk)
}
// Close channel when all writers are done
go func() {
wg.Wait()
close(intermediateChan)
}()
// Collect results
var allPairs []Pair
for batch := range intermediateChan {
allPairs = append(allPairs, batch...)
}
return allPairs
}
// shuffle groups values by key (e.g., "200" -> [1, 1, 1])
func (mrs *MapReduceSystem) shuffle(pairs []Pair) map[string][]int {
groups := make(map[string][]int)
for _, p := range pairs {
groups[p.Key] = append(groups[p.Key], p.Value)
}
return groups
}
// runReducePhase launches goroutines to aggregate keys
func (mrs *MapReduceSystem) runReducePhase(groups map[string][]int) map[string]int {
var wg sync.WaitGroup
// We process keys concurrently.
// To keep it simple, we limit concurrency using a semaphore or just launching per key.
// Here we use a mutex to protect the final shared map result.
var mu sync.Mutex
finalResult := make(map[string]int)
// Limit concurrent reducers to configuration
sem := make(chan struct{}, mrs.ReduceWorkers)
for key, values := range groups {
sem <- struct{}{} // Acquire slot
wg.Add(1)
go func(k string, v []int) {
defer wg.Done()
defer func() { <-sem }() // Release slot
// User Defined Reduce Function logic
result := reduceFunction(k, v)
mu.Lock()
finalResult[k] = result
mu.Unlock()
}(key, values)
}
wg.Wait()
return finalResult
}
// ==========================================
// User Defined Functions (Business Logic)
// ==========================================
// Mock Log Regex: IP - - [Date] "Method URL Proto" Status Size
// Example: 127.0.0.1 - - [10/Oct] "GET /home HTTP/1.1" 200 1234
var logRegex = regexp.MustCompile(`" (\d{3}) `)
// mapFunction extracts the status code and emits (Code, 1)
func mapFunction(lines []string) []Pair {
var pairs []Pair
for _, line := range lines {
matches := logRegex.FindStringSubmatch(line)
if len(matches) > 1 {
statusCode := matches[1]
pairs = append(pairs, Pair{Key: statusCode, Value: 1})
}
}
return pairs
}
// reduceFunction sums up the counts
func reduceFunction(key string, values []int) int {
sum := 0
for _, v := range values {
sum += v
}
return sum
}
// ==========================================
// Main & Data Generation
// ==========================================
func main() {
const filename = "large_log.txt"
const numLines = 100000 // Simulate 100k lines
// 1. Generate Dummy Data
generateLogFile(filename, numLines)
// 2. Configure System
// 5 Mappers, 3 Reducers
mr := NewSystem(5, 3)
// 3. Execute
start := time.Now()
result := mr.Run(filename)
duration := time.Since(start)
// 4. Output
fmt.Println("\n--- Final Report ---")
for code, count := range result {
fmt.Printf("Status %s: %d requests\n", code, count)
}
fmt.Printf("Processing Time: %s\n", duration)
// Cleanup
os.Remove(filename)
}
// Helper to generate a large dummy log file
func generateLogFile(filename string, n int) {
fmt.Printf("Generating %d log lines...\n", n)
file, _ := os.Create(filename)
defer file.Close()
codes := []string{"200", "200", "200", "200", "200", "301", "404", "404", "500"}
rand.Seed(time.Now().UnixNano())
writer := bufio.NewWriter(file)
for i := 0; i < n; i++ {
code := codes[rand.Intn(len(codes))]
// Format: IP - - [Time] "GET / HTTP/1.1" Code 123
line := fmt.Sprintf("192.168.1.1 - - [01/Jan/2024] \"GET /api/data HTTP/1.1\" %s 1024\n", code)
writer.WriteString(line)
}
writer.Flush()
}