diff options
| author | JP Dillingham <jp@dillingham.me> | 2024-10-26 18:32:35 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-10-26 18:32:35 -0500 |
| commit | e8238d19b3c7b29d2892caeafd66733b5622d1b2 (patch) | |
| tree | e8ced369b7631ef46d3043118aac5518dca76d35 | |
| parent | 54590c78f2102634d982698608784e8d3c9043e0 (diff) | |
| parent | 334627cd06476df897cf3f3ec02ca70b51b7fec1 (diff) | |
| download | slskd-e8238d19b3c7b29d2892caeafd66733b5622d1b2.tar.gz | |
Merge pull request #1232 from slskd/scripts
Add the ability to run user-defined scripts when application events are raised
| -rw-r--r-- | config/slskd.example.yml | 12 | ||||
| -rw-r--r-- | docs/config.md | 23 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/EnumAttribute.cs | 21 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 26 | ||||
| -rw-r--r-- | src/slskd/Events/EventBus.cs | 15 | ||||
| -rw-r--r-- | src/slskd/Events/EventsDbContext.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Events/Types/EventRecord.cs | 9 | ||||
| -rw-r--r-- | src/slskd/Events/Types/Events.cs | 11 | ||||
| -rw-r--r-- | src/slskd/Integrations/Scripts/ScriptService.cs | 139 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 8 |
10 files changed, 256 insertions, 13 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 4b4f0996..7dd6450b 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -213,6 +213,16 @@ # username: ~ # password: ~ # integration: +# scripts: +# my_post_download_script: +# on: +# - DownloadFileComplete +# - DownloadDirectoryComplete +# run: data/my_script.sh --json-to-process $EVENT +# my_logging_script: +# on: +# - All +# run: data/log_slskd_events.sh $EVENT # ftp: # enabled: false # address: ~ @@ -232,4 +242,4 @@ # notify_on_private_message: true # notify_on_room_mention: true # retry_attempts: 3 -# cooldown_time: 900000 +# cooldown_time: 900000
\ No newline at end of file diff --git a/docs/config.md b/docs/config.md index ce1fe2b1..4ff884da 100644 --- a/docs/config.md +++ b/docs/config.md @@ -919,6 +919,29 @@ retention: # Integrations +## User-Defined Scripts + +User-defined scripts can be configured to run when application events are raised. Scripts are given a name (useful for troubleshooting!), a list of triggering events, and a `run` command that's used to execute the script. + +The `run` command must be at least one word, with the first word identifying the executable to run and the rest of the string being the command and arguments that will be passed to the executable when the script is run. The executable needs to be on the system's PATH, otherwise it must be the fully qualified path to the file on disk. + +A reserved placeholder value `$DATA` is replaced with the stringified JSON data associated with the event that caused the script to run. It's the responsibility of the script to parse and handle this JSON. + +#### **YAML** +```yaml +integration: + scripts: + my_post_download_script: + on: + - DownloadFileComplete + - DownloadDirectoryComplete + run: /bin/sh data/my_script.sh --json-to-process "$DATA" # Linux/macOS + my_logging_script: + on: + - All + run: cmd.exe echo $DATA >> event_log.txt # Windows +``` + ## FTP Files can be uploaded to a remote FTP server upon completion. Files are uploaded to the server and remote path specified using the directory and filename with which they were downloaded; the FTP will match the layout of the local disk. diff --git a/src/slskd/Common/Validation/EnumAttribute.cs b/src/slskd/Common/Validation/EnumAttribute.cs index ab28a9f0..ac3e4ce7 100644 --- a/src/slskd/Common/Validation/EnumAttribute.cs +++ b/src/slskd/Common/Validation/EnumAttribute.cs @@ -18,7 +18,9 @@ namespace slskd.Validation { using System; + using System.Collections.Generic; using System.ComponentModel.DataAnnotations; + using System.Linq; /// <summary> /// Validates that the value is a valid member of the specified <see cref="Enum"/>. @@ -36,9 +38,24 @@ namespace slskd.Validation protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null && !Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out _)) + if (value is IList<string> array) { - return new ValidationResult($"The {validationContext.DisplayName} field must be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); + if (array.Any(x => string.IsNullOrEmpty(x))) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more null or empty values"); + } + + if (array.Any(x => !Enum.TryParse(TargetType, x, IgnoreCase, out _))) + { + return new ValidationResult($"The elements in the {validationContext.DisplayName} field must all be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); + } + } + else + { + if (value != null && !Enum.TryParse(TargetType, value.ToString(), IgnoreCase, out _)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be one of: {string.Join(", ", Enum.GetNames(TargetType))}. Case {(IgnoreCase ? "insensitive" : "sensitive")}."); + } } return ValidationResult.Success; diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 0f86ff62..306f9b87 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -32,6 +32,7 @@ namespace slskd using NetTools; using slskd.Authentication; using slskd.Configuration; + using slskd.Events; using slskd.Relay; using slskd.Shares; using slskd.Validation; @@ -2005,6 +2006,12 @@ namespace slskd public class IntegrationOptions { /// <summary> + /// Gets script configuration. + /// </summary> + [Validate] + public Dictionary<string, ScriptOptions> Scripts { get; init; } = []; + + /// <summary> /// Gets FTP options. /// </summary> [Validate] @@ -2017,6 +2024,25 @@ namespace slskd public PushbulletOptions Pushbullet { get; init; } = new PushbulletOptions(); /// <summary> + /// Script configuration. + /// </summary> + public class ScriptOptions + { + /// <summary> + /// Gets the list of Event types that trigger the script. + /// </summary> + [Enum(typeof(EventType))] + public string[] On { get; init; } = Array.Empty<string>(); + + /// <summary> + /// Gets the shell script to invoke. + /// </summary> + [StringLength(int.MaxValue, MinimumLength = 1)] + [NotNullOrWhiteSpace] + public string Run { get; init; } + } + + /// <summary> /// FTP options. /// </summary> public class FtpOptions : IValidatableObject diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index e5552d2d..16b7c9e1 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -78,12 +78,12 @@ public class EventBus // save the event to the database before broadcasting to consumers Events.Add(EventRecord.From<T>(data)); - // broadcast the event in a fire-and-forget fashion + // broadcast the event to granular subscribers in a fire-and-forget fashion // we don't need to wait for anything, just need to kick off the tasks // if something throws it will be logged and the consumer can figure it out if (Subscriptions.TryGetValue(typeof(T), out var subscribers)) { - Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(T), string.Join(", ", subscribers.Keys)); + Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, data.Type, string.Join(", ", subscribers.Keys)); // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => @@ -94,6 +94,17 @@ public class EventBus { Log.Debug("No subscribers for {Type}", typeof(T)); } + + // broadcast the event to catch-all subscribers of type Event; listening for all types + if (Subscriptions.TryGetValue(typeof(Event), out subscribers)) + { + Log.Debug("{Count} catch-all subscriber(s): {Names}", subscribers.Count, string.Join(", ", subscribers.Keys)); + + // we don't care about any of these tasks; contractually we are only obligated to invoke them + _ = Task.WhenAll(subscribers.Select(subscriber => + Task.Run(() => (subscriber.Value as Func<Event, Task>)(data)) + .ContinueWith(task => Log.Error(task.Exception, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message)))); + } } /// <summary> diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs index 9acbc9a4..a86f5d1c 100644 --- a/src/slskd/Events/EventsDbContext.cs +++ b/src/slskd/Events/EventsDbContext.cs @@ -34,6 +34,11 @@ public class EventsDbContext : DbContext { modelBuilder .Entity<EventRecord>() + .Property(e => e.Type) + .HasConversion<string>(); + + modelBuilder + .Entity<EventRecord>() .Property(e => e.Timestamp) .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); } diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs index 11825c09..4323a42b 100644 --- a/src/slskd/Events/Types/EventRecord.cs +++ b/src/slskd/Events/Types/EventRecord.cs @@ -19,7 +19,6 @@ namespace slskd.Events; using System; using System.ComponentModel.DataAnnotations; -using System.Linq; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; @@ -31,7 +30,7 @@ using Microsoft.EntityFrameworkCore; public record EventRecord { public DateTime Timestamp { get; init; } = DateTime.UtcNow; - public string Type { get; private set; } + public EventType Type { get; private set; } public string Data { get; init; } [Key] public Guid Id { get; private set; } @@ -61,10 +60,6 @@ public record EventRecord public static EventRecord From<T>(Event e) where T : Event { - // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' - var type = e.GetType().Name.Split('.').TakeLast(1).First(); - type = type.Substring(0, type.Length - "Event".Length); // chop off "Event" suffix - // construct the data for the record by serializing the event and removing redundant properties var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); var data = JsonNode.Parse(json).AsObject(); @@ -76,7 +71,7 @@ public record EventRecord return new EventRecord { Timestamp = e.Timestamp, - Type = type, + Type = e.Type, Id = e.Id, Data = data.ToJsonString(JsonSerializerOptions), }; diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index 20ec3f9f..9a3a71ed 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -24,10 +24,20 @@ public abstract record Event { public Guid Id { get; } = Guid.NewGuid(); public DateTime Timestamp { get; init; } = DateTime.UtcNow; + public abstract EventType Type { get; } +} + +public enum EventType +{ + None = 0, + Any = 1, + DownloadFileComplete = 2, + DownloadDirectoryComplete = 3, } public sealed record DownloadFileCompleteEvent : Event { + public override EventType Type => EventType.DownloadFileComplete; public string LocalFilename { get; init; } public string RemoteFilename { get; init; } public Transfer Transfer { get; init; } @@ -35,6 +45,7 @@ public sealed record DownloadFileCompleteEvent : Event public sealed record DownloadDirectoryCompleteEvent : Event { + public override EventType Type => EventType.DownloadDirectoryComplete; public string LocalDirectoryName { get; init; } public string RemoteDirectoryName { get; init; } public string Username { get; init; } diff --git a/src/slskd/Integrations/Scripts/ScriptService.cs b/src/slskd/Integrations/Scripts/ScriptService.cs new file mode 100644 index 00000000..48916b2d --- /dev/null +++ b/src/slskd/Integrations/Scripts/ScriptService.cs @@ -0,0 +1,139 @@ +// <copyright file="ScriptService.cs" company="slskd Team"> +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Integrations.Scripts; + +using System; +using System.Diagnostics; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Serilog; +using slskd.Events; + +/// <summary> +/// Handles the invocation of shell scripts. +/// </summary> +public class ScriptService +{ + public ScriptService(EventBus eventBus, IOptionsMonitor<Options> optionsMonitor) + { + Events = eventBus; + OptionsMonitor = optionsMonitor; + + Events.Subscribe<Event>(nameof(ScriptService), HandleEvent); + + Log.Debug("{Service} initialized", nameof(ScriptService)); + } + + private ILogger Log { get; } = Serilog.Log.ForContext<ScriptService>(); + private IOptionsMonitor<Options> OptionsMonitor { get; } + private EventBus Events { get; } + + private async Task HandleEvent(Event data) + { + await Task.Yield(); + + Log.Debug("Handling event {Event}", data); + + bool EqualsThisEvent(string type) => type.Equals(data.Type.ToString(), StringComparison.OrdinalIgnoreCase); + bool EqualsLiterallyAnyEvent(string type) => type.Equals(EventType.Any.ToString(), StringComparison.OrdinalIgnoreCase); + + var options = OptionsMonitor.CurrentValue; + var scriptsTriggeredByThisEventType = options.Integration.Scripts + .Where(kvp => kvp.Value.On.Any(EqualsThisEvent) || kvp.Value.On.Any(EqualsLiterallyAnyEvent)); + + foreach (var script in scriptsTriggeredByThisEventType) + { + _ = Task.Run(() => + { + Process process = default; + + try + { + var run = script.Value.Run; + + // split the string into at most 2 parts, leaving part [0] the executable and part [1] the rest of the string, but possibly null + var parts = run.Split(" ", count: 2, options: StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.RemoveEmptyEntries); + + var executable = parts[0]; + string args = default; + + if (parts.Length > 1) + { + args = parts[1].Replace("$DATA", data.ToJson()); + } + + Log.Debug("Running script '{Script}': {Run}", script.Key, run); + var sw = Stopwatch.StartNew(); + + process = new Process() + { + StartInfo = new ProcessStartInfo(fileName: executable) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + }, + }; + + process.Start(); + + if (args is not null) + { + process.StandardInput.WriteLine(args); + } + + process.StandardInput.WriteLine("exit"); + + process.WaitForExit(); + sw.Stop(); + + var error = process.StandardError.ReadToEnd(); + + if (!string.IsNullOrEmpty(error)) + { + throw new Exception($"STDERR: {Regex.Replace(error, @"\r\n?|\n", " ", RegexOptions.Compiled)}"); + } + + var result = process.StandardOutput.ReadToEnd(); + var resultAsLines = result.Split(["\r\n", "\r", "\n"], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); + + Log.Debug("Script '{Script}' ran successfully in {Duration}ms; output: {Output}", script.Key, sw.ElapsedMilliseconds, resultAsLines); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to run script '{Script}': {Message}", script.Key, ex.Message); + } + finally + { + try + { + process?.Close(); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to clean up process started from script '{Script}': {Message}", script.Key, ex.Message); + } + } + }); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6392385f..f18d9c09 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -60,6 +60,7 @@ namespace slskd using slskd.Files; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; + using slskd.Integrations.Scripts; using slskd.Messaging; using slskd.Relay; using slskd.Search; @@ -484,6 +485,10 @@ namespace slskd var app = builder.Build(); + // hack: services that exist only to subscribe to the event bus are not referenced by anything else + // and are thus never instantiated. force a reference here so they are created. + _ = app.Services.GetService<ScriptService>(); + app.ConfigureAspDotNetPipeline(); if (OptionsAtStartup.Flags.NoStart) @@ -553,7 +558,6 @@ namespace slskd services.AddHostedService(p => p.GetRequiredService<IApplication>()); services.AddSingleton<IWaiter, Waiter>(); - services.AddSingleton<IConnectionWatchdog, ConnectionWatchdog>(); if (OptionsAtStartup.Flags.Volatile) @@ -578,6 +582,8 @@ namespace slskd services.AddSingleton<EventService>(); services.AddSingleton<EventBus>(); + services.AddSingleton<ScriptService>(); + services.AddSingleton<IBrowseTracker, BrowseTracker>(); services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); |
