Compare commits

...

3 Commits

11 changed files with 165 additions and 13 deletions
+3 -1
View File
@@ -2,4 +2,6 @@ dist
logs
certs
build
.venv
.venv
__pycache__
.pyc
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+104 -12
View File
@@ -1234,17 +1234,62 @@ def update_appointment_statuses():
except Exception as e:
app.logger.error(f"Automatic appointment status update failed: {e}")
# Schedule jobs
# Schedule jobs - only start scheduler if this is the main process or a single-worker deployment
# This prevents race conditions in multi-worker Gunicorn environments
scheduler = BackgroundScheduler()
if cfg.SCHEDULER_ENABLED:
scheduler.add_job(func=create_daily_backup, trigger="interval", hours=cfg.BACKUP_INTERVAL_HOURS)
scheduler.add_job(func=update_appointment_statuses, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
scheduler.add_job(func=create_return_reminders, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
scheduler.start()
_scheduler_initialized = False
def _initialize_scheduler():
"""Initialize the background scheduler in a safe way for multi-worker deployments."""
global _scheduler_initialized
if _scheduler_initialized or not cfg.SCHEDULER_ENABLED:
return
try:
# For multi-worker Gunicorn, check if we're in a reasonable scenario
# Using a lock file to ensure only one instance starts the scheduler
scheduler_lock_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.scheduler_lock')
try:
# Try to create the lock file - only succeeds if it doesn't exist
lock_fd = os.open(scheduler_lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
os.close(lock_fd)
should_start = True
except FileExistsError:
should_start = False
app.logger.warning("Scheduler lock exists - another process is already running the scheduler")
if should_start:
scheduler.add_job(func=create_daily_backup, trigger="interval", hours=cfg.BACKUP_INTERVAL_HOURS)
scheduler.add_job(func=update_appointment_statuses, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
scheduler.add_job(func=create_return_reminders, trigger="interval", minutes=cfg.SCHEDULER_INTERVAL_MIN)
scheduler.start()
_scheduler_initialized = True
app.logger.info(f"Scheduler started successfully (interval={cfg.SCHEDULER_INTERVAL_MIN} min)")
else:
app.logger.info("Scheduler skipped - another worker instance is running it")
except Exception as e:
app.logger.error(f"Failed to initialize scheduler: {e}")
_scheduler_initialized = False
# Initialize scheduler on app startup
_initialize_scheduler()
# Register shutdown handler to stop scheduler when app is terminated
import atexit
atexit.register(lambda: scheduler.shutdown() if cfg.SCHEDULER_ENABLED else None)
def _shutdown_scheduler():
if cfg.SCHEDULER_ENABLED and _scheduler_initialized:
try:
scheduler.shutdown()
lock_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.scheduler_lock')
try:
os.remove(lock_path)
except Exception:
pass
except Exception as e:
app.logger.error(f"Error during scheduler shutdown: {e}")
atexit.register(_shutdown_scheduler)
def allowed_file(filename, file_content=None, max_size_mb=cfg.MAX_UPLOAD_MB):
"""
@@ -8969,8 +9014,7 @@ def my_borrowed_items():
planned_ausleihungen = list(ausleihungen_collection.find({
'User': username,
'Status': 'planned',
'Start': {'$gt': current_time}
'Status': 'planned'
}))
# DEBUG: Log the number of planned appointments found
@@ -9602,21 +9646,69 @@ def schedule_appointment():
print(f"Error checking for booking conflicts: {e}")
return jsonify({'success': False, 'message': f'Fehler beim Prüfen der Verfügbarkeit: {str(e)}'}), 500
# Create the appointment as a planned booking
# Check if the appointment should already be active
now = datetime.datetime.now()
initial_status = 'active' if start_datetime <= now else 'planned'
# Create the appointment
try:
appointment_id = au.add_planned_booking(
# Use add_ausleihung directly to set the correct initial status
appointment_id = au.add_ausleihung(
item_id=item_id,
user=session['username'],
start_date=start_datetime,
end_date=end_datetime,
notes=notes,
status=initial_status,
period=booking_period # Will be None for multi-day
)
# If it became active immediately, log it and send a notification
if initial_status == 'active' and appointment_id:
app.logger.info(f"Appointment {appointment_id} scheduled retroactively as active.")
# We can also notify the user right away
item_name = item.get('Name', 'Unbekannt')
# Log audit event
_append_audit_event_standalone(
'ausleihung_started',
{
'borrow_id': str(appointment_id),
'item_id': item_id,
'item_name': item_name,
'user': session['username'],
'status_before': 'planned',
'status_after': 'active'
}
)
# Send notification
try:
client_temp = MongoClient(MONGODB_HOST, MONGODB_PORT)
db_temp = client_temp[MONGODB_DB]
_create_notification(
db_temp,
audience='user',
notif_type='appointment_activated',
title='Reservierung ist jetzt aktiv',
message=f"Deine geplante Ausleihe für {item_name} startet jetzt.",
target_user=session['username'],
reference={
'appointment_id': str(appointment_id),
'item_id': str(item_id),
'event': 'activated',
},
unique_key=f"appointment:activated:{appointment_id}",
severity='info'
)
client_temp.close()
except Exception as notif_err:
app.logger.error(f"Error sending immediate active notification: {notif_err}")
if not appointment_id:
return jsonify({'success': False, 'message': 'Termin konnte nicht erstellt werden'}), 500
except Exception as e:
print(f"Error creating planned booking: {e}")
print(f"Error creating booking: {e}")
return jsonify({'success': False, 'message': f'Fehler beim Erstellen des Termins: {str(e)}'}), 500
# If we got this far, we have a valid appointment_id
+16
View File
@@ -4000,6 +4000,22 @@ document.addEventListener('DOMContentLoaded', ()=>{
applyFilters();
}
// Open item modal with fresh details from backend.
function openItemQuick(id) {
fetch(`/get_item/${id}`)
.then(response => response.json())
.then(item => {
if (item && !item.error) {
openItemModal(item);
} else {
console.error('Item details could not be loaded:', item);
}
})
.catch(err => {
console.error('Error loading item details:', err);
});
}
function openEditModalForSelectedUnit(defaultItemId, selectId) {
let targetItemId = defaultItemId;
+42
View File
@@ -0,0 +1,42 @@
"""
Gunicorn configuration for Inventarsystem.
This configuration ensures that:
1. The BackgroundScheduler runs reliably in only one worker process
2. Appointment status updates and reminders work correctly
3. Multi-worker deployments don't cause race conditions
"""
import os
import sys
from pathlib import Path
# Get project root
PROJECT_ROOT = Path(__file__).parent
# Basic configuration
bind = "unix:/tmp/inventarsystem.sock"
workers = 1 # CRITICAL: Only 1 worker to prevent BackgroundScheduler race conditions
worker_class = "sync"
timeout = 60
graceful_timeout = 20
max_requests = 1000
max_requests_jitter = 100
# Logging
accesslog = str(PROJECT_ROOT / "logs" / "access.log")
errorlog = str(PROJECT_ROOT / "logs" / "error.log")
log_level = "info"
capture_output = True
# Worker initialization hook to ensure scheduler starts only once
def on_starting(server):
"""Called just before the master process is initialized."""
print("[GUNICORN] Starting Inventarsystem with scheduler support (1 worker only)")
def when_ready(server):
"""Called just after the server is started."""
print("[GUNICORN] Server is ready. Scheduler should be active in the single worker process.")
# Ensure the logs directory exists
os.makedirs(PROJECT_ROOT / "logs", exist_ok=True)