Skip to content

分散式運算 Demo code

Concept

由老師的主機當成運算中心, 所有學生的 pc 當成分散式運算元. 此 demo 就是以這樣的概念去模擬運作的環境. code 分為學生 part 與老師 part. 實際內容如下

學生使用的 python code, worker_student.py

# 使用說明:
# 此服務走的是 port 5050, 不可以被佔用喔!
# 記得修改 STUDENT_ID 那邊帶入你的識別碼, 學號 + 名字

import json
import time
import zlib
from collections import Counter
from http.server import BaseHTTPRequestHandler, HTTPServer

# =========================================================
# 👉 請同學填入自己的學號或姓名
# =========================================================
STUDENT_ID = "B11200001_王小明"
PORT = 5050  # 避開 macOS AirPlay 的 5000 埠

class WorkerHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/ping':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            info = {'status': 'ready', 'worker_id': STUDENT_ID}
            self.wfile.write(json.dumps(info, ensure_ascii=False).encode('utf-8'))

    def do_POST(self):
        if self.path == '/map_task':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            payload = json.loads(post_data.decode('utf-8'))
            
            chunk_id = payload['chunk_id']
            log_chunk = payload['logs']
            
            print(f"\n📥 [收到任務] 區塊編號 #{chunk_id},共 {len(log_chunk):,} 筆 Log,開始本地深度解析與運算...")
            t0 = time.time()
            
            # 【Map 階段】1. 模擬真實巨量 Log 解析負荷 (每筆資料進行多次雜湊與完整性校驗)
            # 設計基準:約 20~30 萬筆資料耗時約 4~5 秒,人越多分攤越快!
            checksum_acc = 0
            for idx, status in enumerate(log_chunk):
                raw_bytes = f"{idx}:{status}".encode('utf-8')
                # 執行多輪 CRC32 校驗模擬複雜的特徵提取與正規表達式解析
                h = zlib.crc32(raw_bytes)
                h = zlib.crc32(raw_bytes, h)
                h = zlib.crc32(raw_bytes, h)
                checksum_acc ^= h

            # 2. 統計狀態碼出現次數
            local_summary = dict(Counter(log_chunk))
            
            elapsed = time.time() - t0
            print(f"✅ [運算完成] 耗時 {elapsed:.4f} 秒 | 校驗碼: {hex(checksum_acc)} | 摘要: {local_summary}")
            
            response = {
                'worker_id': STUDENT_ID,
                'chunk_id': chunk_id,
                'processed_count': len(log_chunk),
                'elapsed_sec': round(elapsed, 4),
                'summary': local_summary
            }
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response, ensure_ascii=False).encode('utf-8'))

    def log_message(self, format, *args):
        return

if __name__ == '__main__':
    server = HTTPServer(('0.0.0.0', PORT), WorkerHandler)
    print(f"🚀 Worker 節點 [{STUDENT_ID}] 已啟動!正在 Port {PORT} 等待老師探索與派發任務...")
    server.serve_forever()

老師的主程式, master_teacher.py

import random
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests

# =========================================================
# 👉 手動設定老師的本機區網 IP (程式會自動取前三碼掃描 1~254,並跳過自己)
# =========================================================
TEACHER_IP = "192.168.1.50"
WORKER_PORT = 5050  # 與學生端一致,避開 macOS AirPlay
TOTAL_LOGS = 1_000_000  # 產生 100 萬筆網站請求 Log

# =========================================================
# 步驟 1:自動掃描同網段 (1~254),建立線上學生 Worker 清單
# =========================================================
def discover_workers(teacher_ip, port):
    ip_prefix = ".".join(teacher_ip.split(".")[:3]) + "."
    candidate_ips = [
        f"{ip_prefix}{i}" for i in range(1, 255)
        if f"{ip_prefix}{i}" != teacher_ip
    ]
    
    print(f"🔍 正在掃描網段 {ip_prefix}1 ~ 254 (已自動排除老師本機 {teacher_ip})...")
    t_scan = time.time()
    active_workers = []

    def check_node(ip):
        try:
            res = requests.get(f"http://{ip}:{port}/ping", timeout=0.35)
            if res.status_code == 200:
                data = res.json()
                return {'ip': ip, 'worker_id': data.get('worker_id', ip)}
        except Exception:
            return None

    with ThreadPoolExecutor(max_workers=100) as scanner:
        for result in scanner.map(check_node, candidate_ips):
            if result:
                active_workers.append(result)

    print(f"✅ 網段掃描完成 (耗時 {time.time() - t_scan:.2f} 秒),共發現 {len(active_workers)} 台線上學生節點:")
    for w in active_workers:
        print(f"   - [{w['worker_id']}] ({w['ip']})")
    return active_workers

workers = discover_workers(TEACHER_IP, WORKER_PORT)

if not workers:
    print("\n⚠️ 目前網段內沒有偵測到任何已啟動的學生 Worker,請確認學生是否已執行 worker_student.py。")
    exit()

# =========================================================
# 步驟 2:Master 產生巨量資料並依「實際在線人數」動態切塊 (HDFS Block Splitting)
# =========================================================
print(f"\n📦 Master 正在產生 {TOTAL_LOGS:,} 筆全站 HTTP Log...")
status_pool = ['200'] * 80 + ['404'] * 15 + ['500'] * 5
all_logs = random.choices(status_pool, k=TOTAL_LOGS)

num_workers = len(workers)
chunk_size = TOTAL_LOGS // num_workers
chunks = [all_logs[i * chunk_size : (i + 1) * chunk_size] for i in range(num_workers)]
if TOTAL_LOGS % num_workers != 0:
    chunks[-1].extend(all_logs[num_workers * chunk_size:])

print(f"🔪 已將 {TOTAL_LOGS:,} 筆資料動態切分為 {num_workers} 塊 (每人約 {chunk_size:,} 筆),準備平行派發!\n")

# =========================================================
# 步驟 3:【Map 階段】平行派發任務給所有偵測到的學生 Worker
# =========================================================
def dispatch_to_worker(idx, worker_info, log_chunk):
    url = f"http://{worker_info['ip']}:{WORKER_PORT}/map_task"
    try:
        res = requests.post(url, json={'chunk_id': idx, 'logs': log_chunk}, timeout=60)
        return res.json()
    except Exception as e:
        return {'worker_id': f"{worker_info['worker_id']}({worker_info['ip']})", 'chunk_id': idx, 'error': str(e)}

t_start = time.time()
worker_reports = []

with ThreadPoolExecutor(max_workers=num_workers) as pool:
    futures = [
        pool.submit(dispatch_to_worker, idx + 1, workers[idx], chunks[idx])
        for idx in range(num_workers)
    ]
    for future in as_completed(futures):
        report = future.result()
        worker_reports.append(report)
        if 'error' in report:
            print(f"❌ 區塊 #{report['chunk_id']} 失敗 ({report['worker_id']}): {report['error']}")
        else:
            print(f"🎉 收到回報 | 區塊 #{report['chunk_id']} | 執行者: {report['worker_id']} "
                  f"| 處理 {report['processed_count']:,} 筆 | 耗時 {report['elapsed_sec']}s | 結果: {report['summary']}")

# =========================================================
# 步驟 4:【Reduce 階段】Master 彙整所有學生的局部統計結果
# =========================================================
final_total = {}
total_processed = 0

for report in worker_reports:
    if 'summary' in report:
        total_processed += report['processed_count']
        for status, count in report['summary'].items():
            final_total[status] = final_total.get(status, 0) + count

t_end = time.time()
print("\n" + "=" * 65)
print(f"🏆 [Reduce 階段完成] 全班叢集 ({num_workers} 節點) 總耗時: {t_end - t_start:.4f} 秒")
print(f"📊 成功彙整總筆數: {total_processed:,} / {TOTAL_LOGS:,} 筆")
print(f"📈 全站 HTTP 狀態碼最終統計: {final_total}")
print("=" * 65)

使用環境注意事項

無論你是 Server(老師)還是(Client)學生, 都請確認以下事項, 不然你的功能不 work 的原因很有可能就是這個

1. Student 的 python 使用的 port 是 5000, 因此你的 python 如過是在 VM 內跑, 
   Virtualbox 那邊需要將 Windows 的 5000 轉進去 VM 的 5000
2. Windows 的防火強如果有對於通訊進行阻擋, 請記得要關閉或是放行
3. 你的 python 如果是在 VM 內進行, Server 與 Client 都要確定是在同一個網域內進行.

Leave a comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *