def main(
master_ip: str,
tig_worker_path: str,
download_wasms_folder: str,
num_workers: int,
slave_name: str,
master_port: int
):
if not os.path.exists(tig_worker_path):
raise FileNotFoundError(f"tig-worker not found at path: {tig_worker_path}")
os.makedirs(download_wasms_folder, exist_ok=True)
code
Assistant
User
Assistant
Этот код представляет собой скрипт для распределенной вычислительной системы, работающей в качестве "рабочего" (или узла-исполнителя) в сети, где есть основной сервер (мастер), который распределяет задачи. Основное предназначение этого кода заключается в следующем:
Получение и выполнение задач: Рабочий узел запрашивает задачи на выполнение у основного сервера. Этим задачам присваиваются определенные параметры для выполнения.
Загрузка необходимых файлов: В частности, скрипт загружает файлы WebAssembly (WASM), которые необходимы для выполнения переданных задач. Эти файлы обеспечивают возможность запускать алгоритмы на узле.
Выполнение задач: Используя загруженные WASM-файлы и полученные с сервера параметры, рабочий узел выполняет вычислительные задачи, задействуя указанное количество потоков.
Отправка результатов: После завершения выполнения задачи результаты отправляются обратно на основной сервер для дальнейшей обработки и получения следующей задачи.
headers = {
"User-Agent": slave_name
}
while True:
try:
# Step 1: Query for job
start = now()
get_batch_url = f"http://{master_ip}:{master_port}/get-batch"
logger.info(f"fetching job from {get_batch_url}")
resp = requests.get(get_batch_url, headers=headers)
if resp.status_code != 200:
raise Exception(f"status {resp.status_code} when fetching job: {resp.text}")
logger.debug(f"fetching job: took {now() - start}ms")
batch = resp.json()
batch_id = f"{batch['benchmark_id']}_{batch['start_nonce']}"
logger.debug(f"batch {batch_id}: {batch}")
# Step 2: Download WASM
wasm_path = os.path.join(download_wasms_folder, f"{batch['settings']['algorithm_id']}.wasm")
if not os.path.exists(wasm_path):
start = now()
logger.info(f"downloading WASM from {batch['download_url']}")
resp = requests.get(batch['download_url'])
if resp.status_code != 200:
raise Exception(f"status {resp.status_code} when downloading WASM: {resp.text}")
with open(wasm_path, 'wb') as f:
f.write(resp.content)
logger.debug(f"downloading WASM: took {now() - start}ms")
logger.debug(f"WASM Path: {wasm_path}")
# Step 3: Run tig-worker
start = now()
cmd = [
tig_worker_path, "compute_batch",
json.dumps(batch["settings"]),
batch["rand_hash"],
str(batch["start_nonce"]),
str(batch["num_nonces"]),
str(batch["batch_size"]),
wasm_path,
"--mem", str(batch["wasm_vm_config"]["max_memory"]),
"--fuel", str(batch["wasm_vm_config"]["max_fuel"]),
"--workers", str(num_workers),
]
if batch["sampled_nonces"]:
cmd += ["--sampled", *map(str, batch["sampled_nonces"])]
logger.info(f"computing batch: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
result = json.loads(result.stdout)
logger.info(f"computing batch took {now() - start}ms")
logger.debug(f"batch result: {result}")
# Step 4: Submit results
start = now()
submit_url = f"http://{master_ip}:{master_port}/submit-batch-result/{batch_id}"
logger.info(f"posting results to {submit_url}")
resp = requests.post(submit_url, json=result, headers=headers)
if resp.status_code != 200:
raise Exception(f"status {resp.status_code} when posting results to master: {resp.text}")
logger.debug(f"posting results took {now() - start} seconds")
except Exception as e:
logger.error(e)
time.sleep(5)
if name == "main":
parser = argparse.ArgumentParser(description="TIG Slave Benchmarker")
parser.add_argument("master_ip", help="IP address of the master")
parser.add_argument("tig_worker_path", help="Path to tig-worker executable")
parser.add_argument("--download", type=str, default="wasms", help="Folder to download WASMs to (default: wasms)")
parser.add_argument("--workers", type=int, default=8, help="Number of workers (default: 8)")
parser.add_argument("--name", type=str, default=randomname.get_name(), help="Name for the slave (default: randomly generated)")
parser.add_argument("--port", type=int, default=5115, help="Port for master (default: 5115)")
parser.add_argument("--verbose", action='store_true', help="Print debug logs")
This script is a Python application designed for distributed computing tasks, functioning as a "slave" or worker node. Here's a breakdown of its functionality:
High-Level Overview
Argument Parsing:
This script accepts command-line arguments using argparse to specify parameters like the master server's IP address, the path to the worker executable, download folder for WebAssembly (WASM) modules, number of worker threads, and other options.
Main Function:
Implements a loop that continuously queries a master server for computation jobs, downloads the necessary WASM files to execute those jobs, processes the task, and submits results back to the server.
Steps Inside the Loop:
Job Querying: A GET request is made to a /get-batch endpoint for retrieving computation jobs.
WASM Downloading: If the WASM file associated with the job is not already downloaded, it fetches it from a provided URL.
Processing: Runs a command-line process using the subprocess module with the tig-worker executable to carry out the computation.
Result Submission: Posts the computation results back to the master server.
Error Handling:
The script logs errors and waits before retrying if any step fails.
Detailed Components
Logging:
Utilizes Python's logging library to log information, warnings, and errors.
Includes both INFO and DEBUG level logs, controlled by the verbosity argument.
Random Name Generation:
Uses randomname to generate a default unique identifier for the worker.
Considerations & Improvements
Error and Exception Handling:
Although basic exception handling is implemented, more granular error processing could be beneficial.
Resource Management:
Ensure the workers and subprocesses are managed efficiently to prevent leaks or excessive resource consumption.
Scalability:
Consider distribution load balancing and handling large-scale task distribution efficiently.
Security:
Ensure secure communications with the master server, possibly over HTTPS.
Validate and sanitize inputs to prevent potential vulnerabilities.
Dependencies:
Ensure prerequisite tools like Python packages (requests, randomname) and the tig-worker are installed and configured correctly.
Testing:
Comprehensive testing is important, especially around network reliability and job execution correctness.
This script is a foundational piece for a larger distributed system, requiring careful integration with other system components to achieve an efficient compute environment.
import argparse
import json
import os
import logging
import randomname
import requests
import subprocess
import time
def main(
master_ip: str,
tig_worker_path: str,
download_wasms_folder: str,
num_workers: int,
slave_name: str,
master_port: int
):
if not os.path.exists(tig_worker_path):
raise FileNotFoundError(f"tig-worker not found at path: {tig_worker_path}")
os.makedirs(download_wasms_folder, exist_ok=True)
code
headers = {
"User-Agent": slave_name
}
while True:
try:
# Step 1: Query for job
start = now()
get_batch_url = f"http://{master_ip}:{master_port}/get-batch"
logger.info(f"fetching job from {get_batch_url}")
resp = requests.get(get_batch_url, headers=headers)
if resp.status_code != 200:
raise Exception(f"status {resp.status_code} when fetching job: {resp.text}")
logger.debug(f"fetching job: took {now() - start}ms")
batch = resp.json()
batch_id = f"{batch['benchmark_id']}_{batch['start_nonce']}"
logger.debug(f"batch {batch_id}: {batch}")
# Step 2: Download WASM
wasm_path = os.path.join(download_wasms_folder, f"{batch['settings']['algorithm_id']}.wasm")
if not os.path.exists(wasm_path):
start = now()
logger.info(f"downloading WASM from {batch['download_url']}")
resp = requests.get(batch['download_url'])
if resp.status_code != 200:
raise Exception(f"status {resp.status_code} when downloading WASM: {resp.text}")
with open(wasm_path, 'wb') as f:
f.write(resp.content)
logger.debug(f"downloading WASM: took {now() - start}ms")
logger.debug(f"WASM Path: {wasm_path}")
# Step 3: Run tig-worker
start = now()
cmd = [
tig_worker_path, "compute_batch",
json.dumps(batch["settings"]),
batch["rand_hash"],
str(batch["start_nonce"]),
str(batch["num_nonces"]),
str(batch["batch_size"]),
wasm_path,
"--mem", str(batch["wasm_vm_config"]["max_memory"]),
"--fuel", str(batch["wasm_vm_config"]["max_fuel"]),
"--workers", str(num_workers),
]
if batch["sampled_nonces"]:
cmd += ["--sampled", *map(str, batch["sampled_nonces"])]
logger.info(f"computing batch: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
result = json.loads(result.stdout)
logger.info(f"computing batch took {now() - start}ms")
logger.debug(f"batch result: {result}")
# Step 4: Submit results
start = now()
submit_url = f"http://{master_ip}:{master_port}/submit-batch-result/{batch_id}"
logger.info(f"posting results to {submit_url}")
resp = requests.post(submit_url, json=result, headers=headers)
if resp.status_code != 200:
raise Exception(f"status {resp.status_code} when posting results to master: {resp.text}")
logger.debug(f"posting results took {now() - start} seconds")
except Exception as e:
logger.error(e)
time.sleep(5)
if name == "main":
parser = argparse.ArgumentParser(description="TIG Slave Benchmarker")
parser.add_argument("master_ip", help="IP address of the master")
parser.add_argument("tig_worker_path", help="Path to tig-worker executable")
parser.add_argument("--download", type=str, default="wasms", help="Folder to download WASMs to (default: wasms)")
parser.add_argument("--workers", type=int, default=8, help="Number of workers (default: 8)")
parser.add_argument("--name", type=str, default=randomname.get_name(), help="Name for the slave (default: randomly generated)")
parser.add_argument("--port", type=int, default=5115, help="Port for master (default: 5115)")
parser.add_argument("--verbose", action='store_true', help="Print debug logs")
Таким образом, этот скрипт автоматизирует процесс запросов, загрузки, выполнения и передачи результатов вычислительных задач в распределенной системе. Это может быть полезно в случаях, когда требуется распределить нагрузку вычислений по нескольким узлам для повышения производительности и эффективности.