Repository navigation
Expand file tree
/
Copy pathDistributedStorageClient.py
More file actions
180 lines (150 loc) · 9.02 KB
/
Copy pathDistributedStorageClient.py
File metadata and controls
180 lines (150 loc) · 9.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import json
import logging
import socket
import time
from typing import List
class DistributedStorageClient:
"""Client interface for interacting with the distributed storage system."""
def __init__(self, server_hosts: List[str], base_port: int = 9000):
# List of (host, port) tuples for all potential servers
self.servers = [(host, base_port + i) for i, host in enumerate(server_hosts)]
self.logger = logging.getLogger("StorageClient")
# Hint for the current leader's ID. None initially.
self.leader_hint = None # MODIFICATION: Renamed from leader_id for clarity
# --- Public API Methods ---
def write_file(self, filename: str, content: str) -> dict:
command = {"operation": "write_file", "filename": filename, "content": content}
return self._send_command_with_retry(command)
def read_file(self, filename: str) -> str: # Returns content or raises Exception
command = {"operation": "read_file", "filename": filename}
result = self._send_command_with_retry(command)
if result.get("success"):
return result.get("result", "") # Return file content
else:
raise IOError(f"Failed to read file '{filename}': {result.get('error', 'Unknown error')}")
def delete_file(self, filename: str) -> dict:
command = {"operation": "delete_file", "filename": filename}
return self._send_command_with_retry(command)
def create_directory(self, dirname: str) -> dict:
command = {"operation": "create_directory", "dirname": dirname}
return self._send_command_with_retry(command)
def list_directory(self, dirname: str = "") -> List[str]: # Returns list or raises Exception
command = {"operation": "list_directory", "dirname": dirname}
result = self._send_command_with_retry(command)
if result.get("success"):
# Ensure result is a list, default to empty list
return result.get("result") if isinstance(result.get("result"), list) else []
else:
raise IOError(f"Failed to list directory '{dirname}': {result.get('error', 'Unknown error')}")
def rename_file(self, old_name: str, new_name: str) -> dict:
command = {"operation": "rename_file", "old_name": old_name, "new_name": new_name}
return self._send_command_with_retry(command)
# --- Internal Helper Methods ---
def _send_command_with_retry(self, command: dict, max_retries: int = 5) -> dict:
"""Sends a command, handling leader redirection and retries."""
# MODIFICATION: Implemented robust client-side redirection loop
# Determine initial target server(s)
target_servers = list(range(len(self.servers)))
if self.leader_hint is not None and 0 <= self.leader_hint < len(self.servers):
# Prioritize known leader hint
target_servers.insert(0, target_servers.pop(self.leader_hint))
last_error = "No servers available"
for attempt in range(max_retries):
if not target_servers:
self.logger.error("No more servers to try.")
break # Exit retry loop if no servers left to try
# Try servers in the current order
current_target_id = target_servers.pop(0) # Try first server in list
host, port = self.servers[current_target_id]
self.logger.debug(f"Attempt {attempt+1}: Sending command {command.get('operation')} to server {current_target_id} ({host}:{port})")
try:
response = self._send_to_server(current_target_id, command)
# Process response
if response.get("success"):
self.logger.info(f"Command '{command.get('operation')}' successful via server {current_target_id}.")
self.leader_hint = current_target_id # Update hint on success
return response # Success!
# Handle "Not the leader" error
elif response.get("error") == "Not the leader":
self.logger.info(f"Server {current_target_id} is not the leader.")
# Check if response contains a new leader hint (optional)
new_hint = response.get("leader_hint") # RaftNode doesn't reliably provide this
if new_hint is not None and 0 <= new_hint < len(self.servers):
self.leader_hint = new_hint
# Prioritize the new hint for the next attempt
if new_hint in target_servers: target_servers.remove(new_hint)
target_servers.insert(0, new_hint)
self.logger.debug(f"Received leader hint: {new_hint}")
else:
# No hint, just try the next server in the list
pass
# Add the failed server back to the end of the list to retry later if needed
target_servers.append(current_target_id)
last_error = "Not the leader"
continue # Try next server
# Handle other errors reported by the server
else:
last_error = response.get("error", "Unknown server error")
self.logger.warning(f"Server {current_target_id} returned error: {last_error}")
# Treat as potentially transient, try next server
target_servers.append(current_target_id) # Add back to end
# Optionally add a small delay before retrying
time.sleep(0.1 * (attempt + 1))
except (socket.timeout, ConnectionRefusedError, ConnectionResetError, OSError) as e:
self.logger.warning(f"Network error contacting server {current_target_id} ({host}:{port}): {e}")
last_error = f"Network error: {e}"
# Assume node is down, try next server
target_servers.append(current_target_id) # Add back to end
# Clear leader hint if it was this server
if self.leader_hint == current_target_id:
self.leader_hint = None
# Optionally add a small delay
time.sleep(0.1 * (attempt + 1))
except Exception as e:
# Catch other unexpected errors during send/receive
self.logger.error(f"Unexpected client error with server {current_target_id}: {e}", exc_info=True)
last_error = f"Unexpected client error: {e}"
target_servers.append(current_target_id)
time.sleep(0.1 * (attempt + 1))
# If loop finishes without success
self.logger.error(f"Command '{command.get('operation')}' failed after {max_retries} attempts. Last error: {last_error}")
return {"success": False, "error": f"Command failed after retries: {last_error}"}
def _send_to_server(self, server_id: int, command: dict) -> dict:
"""Sends a command JSON to a specific server and returns the response JSON."""
# Raises exceptions on network errors or decode errors
host, port = self.servers[server_id]
sock = None
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# MODIFICATION: Client-side timeout for RPCs
sock.settimeout(3.0) # Allow reasonable time for server processing + network
sock.connect((host, port))
request = {"type": "client_command", "command": command}
sock.sendall((json.dumps(request) + "\n").encode('utf-8'))
# Receive response
response_data = b""
while True:
chunk = sock.recv(4096) # Read larger chunks
if not chunk:
# Connection closed unexpectedly
raise ConnectionResetError(f"Connection closed by server {server_id} before full response.")
response_data += chunk
# Check for newline delimiter
if b"\n" in response_data:
response_message, _, response_data = response_data.partition(b"\n")
break # Got complete message
# Decode and return
response = json.loads(response_message.decode('utf-8'))
return response
except (socket.timeout, ConnectionRefusedError, ConnectionResetError, OSError) as e:
# Let caller handle network errors for retry logic
# self.logger.warning(f"Network error in _send_to_server {server_id}: {e}") # DEBUG
raise # Re-raise network errors
except (json.JSONDecodeError, UnicodeDecodeError) as e:
self.logger.error(f"Failed to decode response from server {server_id}: {e}, data: {response_data[:100]}")
raise ValueError(f"Invalid response from server {server_id}: {e}") # Raise specific error type
finally:
if sock:
try: sock.shutdown(socket.SHUT_RDWR)
except OSError: pass
finally: sock.close()