fix(file-manager): repair uploads and shared SFTP access
Build and publish Docker image / build-and-publish (push) Successful in 12s
Build and publish Docker image / build-and-publish (push) Successful in 12s
This commit is contained in:
1 parent
4c2f5f2c01
commit
2fcd0c3ef9
6 files changed
+275
-9
No files matched your search
@@ -36,6 +36,11 @@ jobs:
|
|||||||
--tag "$DOCKER_IMAGE:main-${COMMIT_SHA:0:12}" \
|
--tag "$DOCKER_IMAGE:main-${COMMIT_SHA:0:12}" \
|
||||||
.
|
.
|
||||||
|
|
||||||
|
- name: Run backend upload tests
|
||||||
|
env:
|
||||||
|
DOCKER_IMAGE: git.anchorhost.eu/anchorhost.eu/anchorhost-backend
|
||||||
|
run: docker run --rm "$DOCKER_IMAGE:backend" python -m unittest discover -s tests -v
|
||||||
|
|
||||||
- name: Push image
|
- name: Push image
|
||||||
env:
|
env:
|
||||||
COMMIT_SHA: ${{ gitea.sha }}
|
COMMIT_SHA: ${{ gitea.sha }}
|
||||||
|
|||||||
@@ -877,7 +877,9 @@ class KubernetesManager:
|
|||||||
# Ensure directory exists
|
# Ensure directory exists
|
||||||
dir_path = '/'.join(file_path.split('/')[:-1]) if '/' in file_path else '.'
|
dir_path = '/'.join(file_path.split('/')[:-1]) if '/' in file_path else '.'
|
||||||
if dir_path and dir_path != '.':
|
if dir_path and dir_path != '.':
|
||||||
self.create_directory(namespace, pod_name, dir_path, container_name=container_name)
|
if not self.create_directory(namespace, pod_name, dir_path, container_name=container_name):
|
||||||
|
logger.error("Failed to create parent directory for upload: %s", dir_path)
|
||||||
|
return False
|
||||||
|
|
||||||
escaped_path = file_path.replace("'", "'\\''")
|
escaped_path = file_path.replace("'", "'\\''")
|
||||||
temp_file = f"/tmp/upload_{int(time.time() * 1000000)}.b64"
|
temp_file = f"/tmp/upload_{int(time.time() * 1000000)}.b64"
|
||||||
@@ -906,7 +908,7 @@ class KubernetesManager:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
# Verify file was created and has content
|
# Verify file was created and has content
|
||||||
check_cmd = ["sh", "-c", f"test -f '{escaped_path}' && test -s '{escaped_path}' && echo 'exists' || echo 'missing'"]
|
check_cmd = ["sh", "-c", f"test -f '{escaped_path}' && echo 'exists' || echo 'missing'"]
|
||||||
result = self.exec_command(namespace, pod_name, check_cmd, container_name=container_name)
|
result = self.exec_command(namespace, pod_name, check_cmd, container_name=container_name)
|
||||||
|
|
||||||
if 'exists' not in result:
|
if 'exists' not in result:
|
||||||
@@ -930,7 +932,9 @@ class KubernetesManager:
|
|||||||
# Ensure directory exists
|
# Ensure directory exists
|
||||||
dir_path = '/'.join(file_path.split('/')[:-1]) if '/' in file_path else '.'
|
dir_path = '/'.join(file_path.split('/')[:-1]) if '/' in file_path else '.'
|
||||||
if dir_path and dir_path != '.':
|
if dir_path and dir_path != '.':
|
||||||
self.create_directory(namespace, pod_name, dir_path, container_name=container_name)
|
if not self.create_directory(namespace, pod_name, dir_path, container_name=container_name):
|
||||||
|
logger.error("Failed to create parent directory for upload: %s", dir_path)
|
||||||
|
return False
|
||||||
|
|
||||||
escaped_path = file_path.replace("'", "'\\''")
|
escaped_path = file_path.replace("'", "'\\''")
|
||||||
temp_file = f"/tmp/upload_{int(time.time() * 1000000)}.b64"
|
temp_file = f"/tmp/upload_{int(time.time() * 1000000)}.b64"
|
||||||
@@ -961,7 +965,7 @@ class KubernetesManager:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
# Verify file was created and has content
|
# Verify file was created and has content
|
||||||
check_cmd = ["sh", "-c", f"test -f '{escaped_path}' && test -s '{escaped_path}' && echo 'exists' || echo 'missing'"]
|
check_cmd = ["sh", "-c", f"test -f '{escaped_path}' && echo 'exists' || echo 'missing'"]
|
||||||
result = self.exec_command(namespace, pod_name, check_cmd, container_name=container_name)
|
result = self.exec_command(namespace, pod_name, check_cmd, container_name=container_name)
|
||||||
|
|
||||||
if 'exists' not in result:
|
if 'exists' not in result:
|
||||||
|
|||||||
@@ -338,6 +338,36 @@ def reconcile_sftp(server_id: str, user_id: str) -> bool:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error reconciling SFTP sidecar for {server_id}: {e}")
|
logger.error(f"Error reconciling SFTP sidecar for {server_id}: {e}")
|
||||||
|
|
||||||
|
# Longhorn may mount a new website volume as root:root 0755. Keep the
|
||||||
|
# SFTP chroot root-owned, but make only the shared data directory
|
||||||
|
# writable by ftp-user. The setgid bit makes new entries inherit gid
|
||||||
|
# 1000; existing files are deliberately left untouched.
|
||||||
|
try:
|
||||||
|
pods = k8s_manager.get_pods_for_server(namespace, server_id)
|
||||||
|
if pods:
|
||||||
|
permission_result = k8s_manager.exec_command(
|
||||||
|
namespace,
|
||||||
|
pods[0],
|
||||||
|
[
|
||||||
|
"sh",
|
||||||
|
"-c",
|
||||||
|
"chgrp 1000 /home/ftp-user/data && chmod 2775 /home/ftp-user/data "
|
||||||
|
"&& echo sftp_data_permissions_ready",
|
||||||
|
],
|
||||||
|
container_name="sftp",
|
||||||
|
)
|
||||||
|
if "sftp_data_permissions_ready" not in str(permission_result):
|
||||||
|
logger.warning(
|
||||||
|
"Could not confirm SFTP data permissions for server %s",
|
||||||
|
server_id,
|
||||||
|
)
|
||||||
|
except Exception as permission_error:
|
||||||
|
logger.warning(
|
||||||
|
"Could not set SFTP data permissions for server %s: %s",
|
||||||
|
server_id,
|
||||||
|
permission_error,
|
||||||
|
)
|
||||||
|
|
||||||
# 3. Ensure port in Service
|
# 3. Ensure port in Service
|
||||||
try:
|
try:
|
||||||
service_name = f"{server_id}-service"
|
service_name = f"{server_id}-service"
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import AsyncMock, patch
|
||||||
|
|
||||||
|
import websocket_service
|
||||||
|
|
||||||
|
|
||||||
|
class ChunkedUploadTests(unittest.TestCase):
|
||||||
|
def _upload(
|
||||||
|
self,
|
||||||
|
content: bytes,
|
||||||
|
write_success: bool = True,
|
||||||
|
chunk_data: str | None = None,
|
||||||
|
) -> tuple[list[dict], bytes]:
|
||||||
|
client_id = "upload-test-client"
|
||||||
|
server_id = "upload-test-server"
|
||||||
|
file_path = "/data/upload-check.bin"
|
||||||
|
captured_content = b""
|
||||||
|
messages: list[dict] = []
|
||||||
|
|
||||||
|
async def capture_message(_client_id: str, message: dict) -> None:
|
||||||
|
messages.append(message)
|
||||||
|
|
||||||
|
def capture_upload(_namespace: str, _pod: str, _path: str, local_path: str, **kwargs: str) -> bool:
|
||||||
|
nonlocal captured_content
|
||||||
|
self.assertEqual(kwargs.get("container_name"), server_id)
|
||||||
|
with open(local_path, "rb") as uploaded_file:
|
||||||
|
captured_content = uploaded_file.read()
|
||||||
|
return write_success
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as upload_dir:
|
||||||
|
old_upload_dir = websocket_service.CHUNK_UPLOAD_DIR
|
||||||
|
websocket_service.CHUNK_UPLOAD_DIR = upload_dir
|
||||||
|
websocket_service.chunked_uploads.clear()
|
||||||
|
websocket_service.connected_clients[client_id] = {
|
||||||
|
"authenticated": True,
|
||||||
|
"user_id": "upload-test-user",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
with (
|
||||||
|
patch.object(websocket_service, "send_message", new=AsyncMock(side_effect=capture_message)),
|
||||||
|
patch.object(websocket_service, "validate_path_for_server", side_effect=lambda _server, path: path),
|
||||||
|
patch.object(
|
||||||
|
websocket_service,
|
||||||
|
"get_server_access_and_namespace",
|
||||||
|
return_value=("upload-test-namespace", {}),
|
||||||
|
),
|
||||||
|
patch.object(websocket_service.k8s_manager, "get_pods_for_server", return_value=["upload-test-pod"]),
|
||||||
|
patch.object(
|
||||||
|
websocket_service.k8s_manager,
|
||||||
|
"write_file_binary_from_disk",
|
||||||
|
side_effect=capture_upload,
|
||||||
|
) as write_file,
|
||||||
|
):
|
||||||
|
asyncio.run(
|
||||||
|
websocket_service.handle_start_chunked_upload(
|
||||||
|
client_id,
|
||||||
|
{
|
||||||
|
"serverId": server_id,
|
||||||
|
"filePath": file_path,
|
||||||
|
"totalChunks": 1,
|
||||||
|
"totalSize": len(content),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
asyncio.run(
|
||||||
|
websocket_service.handle_upload_file_chunk(
|
||||||
|
client_id,
|
||||||
|
{
|
||||||
|
"serverId": server_id,
|
||||||
|
"filePath": file_path,
|
||||||
|
"chunkIndex": 0,
|
||||||
|
"chunkData": chunk_data if chunk_data is not None else base64.b64encode(content).decode("ascii"),
|
||||||
|
"totalChunks": 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if write_success and chunk_data is None:
|
||||||
|
write_file.assert_called_once()
|
||||||
|
elif chunk_data is not None:
|
||||||
|
write_file.assert_not_called()
|
||||||
|
finally:
|
||||||
|
websocket_service.connected_clients.pop(client_id, None)
|
||||||
|
websocket_service.chunked_uploads.clear()
|
||||||
|
websocket_service.CHUNK_UPLOAD_DIR = old_upload_dir
|
||||||
|
|
||||||
|
return messages, captured_content
|
||||||
|
|
||||||
|
def test_upload_writes_regular_file_to_server_container(self) -> None:
|
||||||
|
content = b"binary upload test\x00\xff"
|
||||||
|
messages, uploaded = self._upload(content)
|
||||||
|
|
||||||
|
self.assertEqual(uploaded, content)
|
||||||
|
self.assertEqual(messages[-1]["type"], "file_uploaded")
|
||||||
|
|
||||||
|
def test_upload_creates_empty_file(self) -> None:
|
||||||
|
messages, uploaded = self._upload(b"")
|
||||||
|
|
||||||
|
self.assertEqual(uploaded, b"")
|
||||||
|
self.assertEqual(messages[-1]["type"], "file_uploaded")
|
||||||
|
|
||||||
|
def test_upload_reports_storage_failure(self) -> None:
|
||||||
|
messages, _uploaded = self._upload(b"payload", write_success=False)
|
||||||
|
|
||||||
|
self.assertEqual(messages[-1]["type"], "upload_error")
|
||||||
|
self.assertEqual(messages[-1]["error"], "Failed to upload file")
|
||||||
|
|
||||||
|
def test_upload_rejects_invalid_base64(self) -> None:
|
||||||
|
messages, _uploaded = self._upload(b"payload", chunk_data="not-base64!")
|
||||||
|
|
||||||
|
self.assertEqual(messages[-1]["type"], "upload_error")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
from kubernetes_service import KubernetesManager
|
||||||
|
|
||||||
|
|
||||||
|
class KubernetesUploadWriteTests(unittest.TestCase):
|
||||||
|
def _manager(self, command_results: list[str]) -> KubernetesManager:
|
||||||
|
manager = KubernetesManager.__new__(KubernetesManager)
|
||||||
|
manager.connected = True
|
||||||
|
manager.create_directory = Mock(return_value=True)
|
||||||
|
manager.exec_command_with_file_stdin = Mock(return_value="")
|
||||||
|
manager.exec_command_with_stdin = Mock(return_value="")
|
||||||
|
manager.exec_command = Mock(side_effect=command_results)
|
||||||
|
return manager
|
||||||
|
|
||||||
|
def test_streaming_upload_accepts_empty_file(self) -> None:
|
||||||
|
manager = self._manager(["temp_exists", "decode_success", "exists"])
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as temp_dir:
|
||||||
|
source = Path(temp_dir) / "empty.bin"
|
||||||
|
source.write_bytes(b"")
|
||||||
|
|
||||||
|
uploaded = manager.write_file_binary_from_disk(
|
||||||
|
"test-namespace", "test-pod", "/data/empty.bin", str(source), container_name="game-container"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(uploaded)
|
||||||
|
self.assertEqual(manager.exec_command.call_count, 3)
|
||||||
|
self.assertTrue(all(call.kwargs["container_name"] == "game-container" for call in manager.exec_command.call_args_list))
|
||||||
|
|
||||||
|
def test_streaming_upload_accepts_binary_file(self) -> None:
|
||||||
|
manager = self._manager(["temp_exists", "decode_success", "exists"])
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as temp_dir:
|
||||||
|
source = Path(temp_dir) / "binary.bin"
|
||||||
|
source.write_bytes(b"\x00\xff\x01")
|
||||||
|
|
||||||
|
uploaded = manager.write_file_binary_from_disk(
|
||||||
|
"test-namespace", "test-pod", "/data/binary.bin", str(source), container_name="game-container"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(uploaded)
|
||||||
|
manager.exec_command_with_file_stdin.assert_called_once()
|
||||||
|
|
||||||
|
def test_base64_upload_accepts_empty_file(self) -> None:
|
||||||
|
manager = self._manager(["temp_exists", "decode_success", "exists"])
|
||||||
|
|
||||||
|
uploaded = manager.write_file_binary(
|
||||||
|
"test-namespace", "test-pod", "/data/empty.bin", "", container_name="game-container"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(uploaded)
|
||||||
|
self.assertEqual(manager.exec_command.call_count, 3)
|
||||||
|
self.assertTrue(all(call.kwargs["container_name"] == "game-container" for call in manager.exec_command.call_args_list))
|
||||||
|
|
||||||
|
def test_upload_stops_when_parent_directory_creation_fails(self) -> None:
|
||||||
|
manager = self._manager([])
|
||||||
|
manager.create_directory.return_value = False
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as temp_dir:
|
||||||
|
source = Path(temp_dir) / "file.bin"
|
||||||
|
source.write_bytes(b"content")
|
||||||
|
|
||||||
|
uploaded = manager.write_file_binary_from_disk(
|
||||||
|
"test-namespace", "test-pod", "/data/new/file.bin", str(source), container_name="game-container"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(uploaded)
|
||||||
|
manager.exec_command_with_file_stdin.assert_not_called()
|
||||||
|
manager.exec_command.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
+37
-5
@@ -2060,7 +2060,13 @@ async def handle_upload_file(client_id, data):
|
|||||||
return
|
return
|
||||||
|
|
||||||
# Use write_file_binary for all files to support binary files
|
# Use write_file_binary for all files to support binary files
|
||||||
success = k8s_manager.write_file_binary(namespace, pods[0], file_path, file_content)
|
success = k8s_manager.write_file_binary(
|
||||||
|
namespace,
|
||||||
|
pods[0],
|
||||||
|
file_path,
|
||||||
|
file_content,
|
||||||
|
container_name=server_id,
|
||||||
|
)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
@@ -2088,7 +2094,14 @@ async def handle_start_chunked_upload(client_id, data):
|
|||||||
total_chunks = data.get('totalChunks')
|
total_chunks = data.get('totalChunks')
|
||||||
total_size = data.get('totalSize')
|
total_size = data.get('totalSize')
|
||||||
|
|
||||||
if not server_id or not file_path or not total_chunks:
|
if (
|
||||||
|
not server_id
|
||||||
|
or not file_path
|
||||||
|
or not isinstance(total_chunks, int)
|
||||||
|
or total_chunks < 1
|
||||||
|
or not isinstance(total_size, int)
|
||||||
|
or total_size < 0
|
||||||
|
):
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
'type': 'upload_error',
|
'type': 'upload_error',
|
||||||
'error': 'Server ID, file path, and total chunks required',
|
'error': 'Server ID, file path, and total chunks required',
|
||||||
@@ -2174,7 +2187,14 @@ async def handle_upload_file_chunk(client_id, data):
|
|||||||
chunk_data = data.get('chunkData')
|
chunk_data = data.get('chunkData')
|
||||||
total_chunks = data.get('totalChunks')
|
total_chunks = data.get('totalChunks')
|
||||||
|
|
||||||
if not server_id or not file_path or chunk_index is None or not chunk_data:
|
if (
|
||||||
|
not server_id
|
||||||
|
or not file_path
|
||||||
|
or not isinstance(chunk_index, int)
|
||||||
|
or chunk_index < 0
|
||||||
|
or chunk_data is None
|
||||||
|
or not isinstance(chunk_data, str)
|
||||||
|
):
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
'type': 'upload_error',
|
'type': 'upload_error',
|
||||||
'error': 'Missing required chunk data',
|
'error': 'Missing required chunk data',
|
||||||
@@ -2205,6 +2225,8 @@ async def handle_upload_file_chunk(client_id, data):
|
|||||||
return
|
return
|
||||||
|
|
||||||
upload_info = chunked_uploads[upload_id]
|
upload_info = chunked_uploads[upload_id]
|
||||||
|
if chunk_index >= upload_info['total_chunks']:
|
||||||
|
raise ValueError('Chunk index is outside the upload session')
|
||||||
temp_file_path = upload_info['temp_file']
|
temp_file_path = upload_info['temp_file']
|
||||||
|
|
||||||
# Ensure CHUNK_UPLOAD_DIR and parent directory exist (in case they were cleaned up or don't exist)
|
# Ensure CHUNK_UPLOAD_DIR and parent directory exist (in case they were cleaned up or don't exist)
|
||||||
@@ -2219,7 +2241,7 @@ async def handle_upload_file_chunk(client_id, data):
|
|||||||
logger.warning(f"Chunk {chunk_index} already received for upload {upload_id}, skipping")
|
logger.warning(f"Chunk {chunk_index} already received for upload {upload_id}, skipping")
|
||||||
else:
|
else:
|
||||||
# Decode base64 chunk and write directly to disk file
|
# Decode base64 chunk and write directly to disk file
|
||||||
chunk_bytes = base64.b64decode(chunk_data)
|
chunk_bytes = base64.b64decode(chunk_data, validate=True)
|
||||||
|
|
||||||
# Write chunk to temporary file at correct position
|
# Write chunk to temporary file at correct position
|
||||||
# We need to write chunks in order, so we'll append and sort later, or use a different approach
|
# We need to write chunks in order, so we'll append and sort later, or use a different approach
|
||||||
@@ -2321,6 +2343,10 @@ async def handle_upload_file_chunk(client_id, data):
|
|||||||
out_f.write(chunk_data)
|
out_f.write(chunk_data)
|
||||||
bytes_written += read_size
|
bytes_written += read_size
|
||||||
|
|
||||||
|
expected_size = upload_info.get('total_size')
|
||||||
|
if expected_size is not None and os.path.getsize(reassembled_file_path) != expected_size:
|
||||||
|
raise ValueError('Uploaded file size does not match the declared size')
|
||||||
|
|
||||||
# Clear chunk positions to free memory
|
# Clear chunk positions to free memory
|
||||||
chunk_positions.clear()
|
chunk_positions.clear()
|
||||||
|
|
||||||
@@ -2351,7 +2377,13 @@ async def handle_upload_file_chunk(client_id, data):
|
|||||||
file_path = validate_path_for_server(server_id, file_path)
|
file_path = validate_path_for_server(server_id, file_path)
|
||||||
|
|
||||||
# Upload the file using streaming method (reads from disk, doesn't load into memory)
|
# Upload the file using streaming method (reads from disk, doesn't load into memory)
|
||||||
success = k8s_manager.write_file_binary_from_disk(namespace, pods[0], file_path, reassembled_file_path)
|
success = k8s_manager.write_file_binary_from_disk(
|
||||||
|
namespace,
|
||||||
|
pods[0],
|
||||||
|
file_path,
|
||||||
|
reassembled_file_path,
|
||||||
|
container_name=server_id,
|
||||||
|
)
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
await send_message(client_id, {
|
await send_message(client_id, {
|
||||||
|
|||||||
Reference in new issue
Block a user