fix image checksum being stored as uuid

This commit is contained in:
2025-06-18 01:05:19 +09:30
parent 30796473c3
commit 08573ce742
6 changed files with 36 additions and 33 deletions
+7 -9
View File
@@ -1,9 +1,7 @@
from flask import request, jsonify, abort
from app import app, db, logger
from app import db, logger
from app.models.models import Image
from datetime import datetime
from app.controller import api_bp
import uuid
def validate_image_data(data, is_update=False):
"""
@@ -55,12 +53,12 @@ def validate_image_data(data, is_update=False):
@api_bp.route('/images', methods=['POST'])
def add_image():
data = request.json
logger.debug(f"Image request {data}")
# Validate incoming data
validated_data = validate_image_data(data)
# Create the Image instance
instance = Image(
# Create the Image
_image = Image(
name="a",
location=validated_data['location'],
size=validated_data['size'],
@@ -69,10 +67,10 @@ def add_image():
os_version=validated_data.get('os_version'),
checksum=validated_data.get('checksum')
)
db.session.add(instance)
db.session.add(_image)
db.session.commit()
logger.debug("Image added to DB")
return jsonify(instance.to_json()), 201
logger.debug(f"Image added to DB with payload {_image.to_json()}")
return jsonify(_image.to_json()), 201
@api_bp.route('/images/<image_id>', methods=['PUT'])
def edit_image(image_id):
+10 -10
View File
@@ -90,15 +90,15 @@ class BaseModel(SoftDeleteMixin,db.Model):
status = Column(String(50), nullable=True)
created_by = Column(String(36), ForeignKey("users.id"), nullable=True)
def __init__(self, *args, **kwargs):
# Convert UUID strings to UUID objects for any UUID fields
for key, value in kwargs.items():
if hasattr(self.__table__.columns, key) and isinstance(getattr(self.__table__.columns, key).type, String):
try:
kwargs[key] = str(uuid.UUID(value)) if value else None
except (ValueError, TypeError, AttributeError):
pass
super().__init__(*args, **kwargs)
# def __init__(self, *args, **kwargs):
# # Convert UUID strings to UUID objects for any UUID fields
# for key, value in kwargs.items():
# if hasattr(self.__table__.columns, key) and isinstance(getattr(self.__table__.columns, key).type, String):
# try:
# kwargs[key] = str(uuid.UUID(value)) if value else None
# except (ValueError, TypeError, AttributeError):
# pass
# super().__init__(*args, **kwargs)
@classmethod
def query_with_deleted(cls):
@@ -563,7 +563,7 @@ class Workload(BaseModel):
None: ["pending", "pending-allocation", "error"], # Initial states
"pending": ["provisioning", "error"],
"provisioning": ["running", "error"],
"running": ["stopping", "error","pending-deleted","dead"],
"running": ["stopping", "error","pending-deleted","dead","stopped"],
"pending-allocation": ["running", "error","allocated","pending-deleted"],
"allocated":["pending-deleted","running","dead","stopped"],
"pending-allocated": ["*"],
+10 -10
View File
@@ -16,17 +16,17 @@ def render_list():
os_version = st.text_input("OS Version (e.g., 20.04)")
checksum = st.text_input("Checksum (optional)")
submit = st.form_submit_button("Create Image")
payload = {
"name": name,
"location": location,
"location_type": location_type,
"size": size,
"os_family": os_family,
"os_version": os_version,
"checksum": checksum
}
if submit and name and location:
result = st.session_state.client.create_image(
name=name,
location=location,
location_type=location_type,
size=size,
os_family=os_family,
os_version=os_version,
checksum=checksum
)
result = st.session_state.client.create_image(payload)
if result:
st.success(f"Image '{name}' created successfully!")
+1
View File
@@ -4,6 +4,7 @@ from flask_socketio import emit
import json
import logging
import requests
from flask import request
from websocket_server.config import get_redis_client
from websocket_server.events import base
+1
View File
@@ -3,6 +3,7 @@
from flask_socketio import emit
import logging
import requests
from flask import request
from websocket_server.events import base
from websocket_server.shared_state import connected_workers, connected_sids_lock, connected_sids
+7 -4
View File
@@ -305,7 +305,7 @@ class VolumeProcessor:
Returns:
True if download was successful (or existing file was valid), False otherwise
"""
self.logger.info(f"Starting download from {url} to {dest_path}")
self.logger.info(f"Starting download from {url} to {dest_path}, expected checksum {expected_checksum}")
# Check if file already exists
if os.path.exists(dest_path):
@@ -477,15 +477,15 @@ class VolumeProcessor:
# Convert to qcow2 format
img_format = source.get('format', 'raw')
self.logger.debug(f"Converting downloaded image to qcow2 format")
self.logger.debug(f"Converting downloaded image to qcow2 format from {img_format} ")
subprocess.run(['qemu-img', 'convert', '-f', img_format, '-O', 'qcow2',
temp_path, full_path], check=True)
self.logger.debug(f"Conversion complete")
# Resize if needed
if size_gb:
self.logger.debug(f"Resizing volume to {size_gb}G")
subprocess.run(['qemu-img', 'resize', full_path, f"{size_gb}G"], check=True)
self.logger.debug(f"Resize complete")
# # Clean up temp file
# os.remove(temp_path)
# self.logger.debug("Temporary download file removed")
@@ -638,14 +638,17 @@ class VolumeProcessor:
try:
if volume_type == 'local':
result = self.create_local_volume(volume_config)
self.logger.debug(f"Result from create_local_volume {result}")
elif volume_type == 'lvm':
result = self.create_lvm_volume(volume_config)
self.logger.debug(f"Result from create_lvm_volume {result}")
elif volume_type == 'ceph':
# Ensure Ceph processor is initialized (lazy initialization)
if not self.ceph_processor and not self._initialize_ceph_processor():
raise ConnectionError("Ceph processor could not be initialized. Check Ceph settings and connectivity.")
# Pass self (VolumeProcessor instance) to handle downloads if needed by Ceph processor
result = self.ceph_processor.create_volume(volume_config, self)
self.logger.debug(f"Result from ceph create_volume {result}")
else:
raise ValueError(f"Unsupported volume type: {volume_type}")