Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Run database migrations as a separate step during entrypoint.
nzbdav-dev4bfeac9254b3
diff --git a/backend/Api/SabControllers/GetHistory/GetHistoryController.cs b/backend/Api/SabControllers/GetHistory/GetHistoryController.csindex 12c8fd4a..d4f1a20c 100644--- a/backend/Api/SabControllers/GetHistory/GetHistoryController.cs+++ b/backend/Api/SabControllers/GetHistory/GetHistoryController.cs@@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;using NzbWebDAV.Config;using NzbWebDAV.Database;-using NzbWebDAV.Database.Models;namespace NzbWebDAV.Api.SabControllers.GetHistory;diff --git a/backend/Program.cs b/backend/Program.csindex aa5f957d..5bd45227 100644--- a/backend/Program.cs+++ b/backend/Program.cs@@ -29,7 +29,7 @@ class Programstatic async Task Main(string[] args){// Initialize logger- var defaultLevel = LogEventLevel.Information;+ var defaultLevel = LogEventLevel.Warning;var envLevel = Environment.GetEnvironmentVariable("LOG_LEVEL");var level = Enum.TryParse<LogEventLevel>(envLevel, true, out var parsed) ? parsed : defaultLevel;Log.Logger = new LoggerConfiguration()@@ -42,8 +42,14 @@ class Program.CreateLogger();// initialize database- var databaseContext = new DavDatabaseContext();- await databaseContext.Database.MigrateAsync();+ await using var databaseContext = new DavDatabaseContext();++ // run database migration, if necessary.+ if (args.Contains("--db-migration"))+ {+ await databaseContext.Database.MigrateAsync(SigtermUtil.GetCancellationToken());+ return;+ }// initialize the config-managervar configManager = new ConfigManager();diff --git a/backend/Queue/QueueManager.cs b/backend/Queue/QueueManager.csindex 7240536d..cd368444 100644--- a/backend/Queue/QueueManager.cs+++ b/backend/Queue/QueueManager.cs@@ -27,7 +27,8 @@ public class QueueManager : IDisposable_usenetClient = usenetClient;_configManager = configManager;_websocketManager = websocketManager;- _cancellationTokenSource = new CancellationTokenSource();+ _cancellationTokenSource = CancellationTokenSource+ .CreateLinkedTokenSource(SigtermUtil.GetCancellationToken());_ = ProcessQueueAsync(_cancellationTokenSource.Token);}diff --git a/backend/Utils/SigtermUtil.cs b/backend/Utils/SigtermUtil.csnew file mode 100644index 00000000..f97ec7d7--- /dev/null+++ b/backend/Utils/SigtermUtil.cs@@ -0,0 +1,43 @@+using System.Runtime.Loader;+using Serilog;++namespace NzbWebDAV.Utils;++public static class SigtermUtil+{+ private static readonly CancellationTokenSource CancellationTokenSource = new();+ private static bool _isInitialized = false;++ /// <summary>+ /// Gets a CancellationToken that will be cancelled when the application+ /// receives a SIGTERM signal (e.g., from a shutdown command in a container).+ /// </summary>+ /// <remarks>+ /// This method is designed to be called once at application startup.+ /// It hooks into the AssemblyLoadContext.Default.Unloading event, which is the+ /// standard way to handle SIGTERM on modern .NET platforms.+ /// </remarks>+ public static CancellationToken GetCancellationToken()+ {+ // Use a lock or flag to ensure the event handler is only registered once.+ lock (CancellationTokenSource)+ {+ if (!_isInitialized)+ {+ // Subscribe to the Unloading event of the default AssemblyLoadContext.+ // This event is triggered when the host runtime initiates a shutdown,+ // which typically happens in response to a SIGTERM signal.+ AssemblyLoadContext.Default.Unloading += (_) =>+ {+ // Signal cancellation to any tasks that are listening.+ CancellationTokenSource.Cancel();+ };++ // Set the flag to true to prevent re-initialization.+ _isInitialized = true;+ }+ }++ return CancellationTokenSource.Token;+ }+}\ No newline at end of filediff --git a/backend/Websocket/WebsocketManager.cs b/backend/Websocket/WebsocketManager.csindex 5e391268..91fa1476 100644--- a/backend/Websocket/WebsocketManager.cs+++ b/backend/Websocket/WebsocketManager.cs@@ -1,6 +1,5 @@using System.Net.WebSockets;using System.Text;-using System.Text.Json;using Microsoft.AspNetCore.Http;using NzbWebDAV.Exceptions;using NzbWebDAV.Utils;@@ -80,11 +79,18 @@ public class WebsocketManager/// <param name="socket">The websocket to wait for disconnect.</param>private static async Task WaitForDisconnected(WebSocket socket){- var buffer = new byte[1024];- WebSocketReceiveResult? result = null;- while (result is not { CloseStatus: not null })- result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), default);- await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, default);+ try+ {+ var buffer = new byte[1024];+ WebSocketReceiveResult? result = null;+ while (result is not { CloseStatus: not null })+ result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), default);+ await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, default);+ }+ catch (Exception e)+ {+ Log.Warning(e.Message);+ }}/// <summary>diff --git a/entrypoint.sh b/entrypoint.shindex f07f64c4..b273e32c 100644--- a/entrypoint.sh+++ b/entrypoint.sh@@ -23,6 +23,21 @@ wait_either() {done}+# Signal handling for graceful shutdown+terminate() {+ echo "Caught termination signal. Shutting down..."+ if [ -n "$BACKEND_PID" ] && kill -0 "$BACKEND_PID" 2>/dev/null; then+ kill "$BACKEND_PID"+ fi+ if [ -n "$FRONTEND_PID" ] && kill -0 "$FRONTEND_PID" 2>/dev/null; then+ kill "$FRONTEND_PID"+ fi+ # Wait for children to exit+ wait+ exit 0+}+trap terminate TERM INT+# Use env vars or default to 1000PUID=${PUID:-1000}PGID=${PGID:-1000}@@ -46,11 +61,20 @@ if [ -z "${FRONTEND_BACKEND_API_KEY}" ]; thenexport FRONTEND_BACKEND_API_KEY=$(head -c 32 /dev/urandom | hexdump -ve '1/1 "%.2x"')fi-# Change permissions on /config directory to the given PUID and GUID-chown $PUID:$GUID /config+# Change permissions on /config directory to the given PUID and PGID+chown $PUID:$PGID /config-# Run backend as appuser in background+# Run backend database migrationcd /app/backend+echo "Running database maintenance."+su-exec appuser ./NzbWebDAV --db-migration+if [ $? -ne 0 ]; then+ echo "Database migration failed. Exiting with error code $?."+ exit $?+fi+echo "Done with database maintenance."++# Run backend as appuser in backgroundsu-exec appuser ./NzbWebDAV &BACKEND_PID=$!