diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-07-30 16:11:20 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2022-07-30 16:11:20 -0500 |
| commit | d73f566ea610f40f73a18671089bd1137cd51273 (patch) | |
| tree | 4123c3ca8e0f97b636bc03468f1f16759796b25b /src | |
| parent | fbdd590393206d5fa6679a7b5c6e2ca6637bc724 (diff) | |
| parent | 001a7c0f708de3d7374d9234e07a6ba477cfbc31 (diff) | |
| download | slskd-d73f566ea610f40f73a18671089bd1137cd51273.tar.gz | |
Merge remote-tracking branch 'origin/master' into transfers
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 104 | ||||
| -rw-r--r-- | src/slskd/Common/Dumper.cs | 161 | ||||
| -rw-r--r-- | src/slskd/Common/Logging/ConsoleWriteLineLogger.cs | 9 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ApplicationController.cs | 10 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 9 | ||||
| -rw-r--r-- | src/web/package-lock.json | 12 |
6 files changed, 260 insertions, 45 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 409b9aaf..2597ac93 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -122,10 +122,10 @@ namespace slskd Client.UserStatusChanged += Client_UserStatusChanged; Client.PrivateMessageReceived += Client_PrivateMessageRecieved; - Client.PrivateRoomMembershipAdded += (e, room) => Console.WriteLine($"Added to private room {room}"); - Client.PrivateRoomMembershipRemoved += (e, room) => Console.WriteLine($"Removed from private room {room}"); - Client.PrivateRoomModerationAdded += (e, room) => Console.WriteLine($"Promoted to moderator in private room {room}"); - Client.PrivateRoomModerationRemoved += (e, room) => Console.WriteLine($"Demoted from moderator in private room {room}"); + Client.PrivateRoomMembershipAdded += (e, room) => Log.Information("Added to private room {Room}", room); + Client.PrivateRoomMembershipRemoved += (e, room) => Log.Information("Removed from private room {Room}", room); + Client.PrivateRoomModerationAdded += (e, room) => Log.Information("Promoted to moderator in private room {Room}", room); + Client.PrivateRoomModerationRemoved += (e, room) => Log.Information("Demoted from moderator in private room {Room}", room); Client.PublicChatMessageReceived += Client_PublicChatMessageReceived; Client.RoomMessageReceived += Client_RoomMessageReceived; @@ -341,10 +341,18 @@ namespace slskd /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns> private async Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint) { - var directories = (await Shares.BrowseAsync()) - .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes + try + { + var directories = (await Shares.BrowseAsync()) + .Select(d => new Soulseek.Directory(d.Name.Replace('/', '\\'), d.Files)); // Soulseek NS requires backslashes - return new BrowseResponse(directories); + return new BrowseResponse(directories); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to resolve browse response: {Message}", ex.Message); + throw; + } } private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args) @@ -453,14 +461,13 @@ namespace slskd if (Options.Integration.Pushbullet.Enabled && !args.Replayed) { - Console.WriteLine("Pushing..."); _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message); } } private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args) { - Console.WriteLine($"[PUBLIC CHAT] [{args.RoomName}] [{args.Username}]: {args.Message}"); + Log.Information("[Public Chat/{Room}] [{Username}]: {Message}", args.RoomName, args.Username, args.Message); if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username)) { @@ -546,7 +553,6 @@ namespace slskd private void Client_UserStatusChanged(object sender, UserStatus args) { - Console.WriteLine($"[USER] {args.Username}: {args.Presence}"); } private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename) @@ -559,7 +565,7 @@ namespace slskd catch (Exception ex) { Log.Warning(ex, "Failed to estimate place in queue for {Filename} requested by {Username}", filename, username); - return Task.FromResult<int?>(null); + throw; } } @@ -573,8 +579,16 @@ namespace slskd /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> private async Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - var dir = await Shares.ListDirectoryAsync(directory); - return dir; + try + { + var dir = await Shares.ListDirectoryAsync(directory); + return dir; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to resolve directory contents: {Message}", ex.Message); + throw; + } } private async Task OptionsMonitor_OnChange(Options newOptions) @@ -752,29 +766,37 @@ namespace slskd return null; } - var results = await Shares.SearchAsync(query); - - if (results.Any()) + try { - // make sure our average speed (as reported by the server) is reasonably up to date - await RefreshUserStatistics(); + var results = await Shares.SearchAsync(query); - var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); + if (results.Any()) + { + // make sure our average speed (as reported by the server) is reasonably up to date + await RefreshUserStatistics(); - Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText} (forecasted position: {forecastedPosition})"); + var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); - return new SearchResponse( - Client.Username, - token, - uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, - freeUploadSlots: forecastedPosition == 0 ? 1 : 0, - queueLength: forecastedPosition, - fileList: results); - } + Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText); - // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no - // response will be sent to the requestor. - return null; + return new SearchResponse( + Client.Username, + token, + uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, + freeUploadSlots: forecastedPosition == 0 ? 1 : 0, + queueLength: forecastedPosition, + fileList: results); + } + + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no + // response will be sent to the requestor. + return null; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to resolve search response: {Message}", ex.Message); + throw; + } } private void ShareState_OnChange((ShareState Previous, ShareState Current) state) @@ -838,13 +860,21 @@ namespace slskd /// <returns>A Task resolving the UserInfo instance.</returns> private Task<UserInfo> UserInfoResolver(string username, IPEndPoint endpoint) { - var info = new UserInfo( - description: Options.Soulseek.Description, - uploadSlots: 1, - queueLength: 0, - hasFreeUploadSlot: false); + try + { + var info = new UserInfo( + description: Options.Soulseek.Description, + uploadSlots: 1, + queueLength: 0, + hasFreeUploadSlot: false); - return Task.FromResult(info); + return Task.FromResult(info); + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to resolve user info: {Message}", ex.Message); + throw; + } } } } diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs new file mode 100644 index 00000000..766fe803 --- /dev/null +++ b/src/slskd/Common/Dumper.cs @@ -0,0 +1,161 @@ +// <copyright file="Dumper.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> + +namespace slskd +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Net.Http; + using System.Runtime.InteropServices; + using System.Threading.Tasks; + + /// <summary> + /// Dumps the contents of the application's memory to a .dmp file using dotnet-dump. + /// </summary> + /// <remarks> + /// <para> + /// Monitor https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump for tool updates. Currently supported + /// runtime IDs: + /// </para> + /// <list type="bullet"> + /// <listheader>Currently supported runtime IDs:</listheader> + /// <item>https://aka.ms/dotnet-dump/win-x86</item> + /// <item>https://aka.ms/dotnet-dump/win-x64</item> + /// <item>https://aka.ms/dotnet-dump/win-arm</item> + /// <item>https://aka.ms/dotnet-dump/win-arm64</item> + /// <item>https://aka.ms/dotnet-dump/osx-x64</item> + /// <item>https://aka.ms/dotnet-dump/linux-x64</item> + /// <item>https://aka.ms/dotnet-dump/linux-arm</item> + /// <item>https://aka.ms/dotnet-dump/linux-arm64</item> + /// <item>https://aka.ms/dotnet-dump/linux-musl-x64</item> + /// <item>https://aka.ms/dotnet-dump/linux-musl-arm64</item> + /// <item></item> + /// </list> + /// </remarks> + public class Dumper : IDisposable + { + private static readonly string URLTemplate = "https://aka.ms/dotnet-dump/$RID"; + + private string BinFile { get; set; } + private bool Disposed { get; set; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + public async Task<string> DumpAsync() + { + BinFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var outputFile = Path.Combine(Path.GetTempPath(), $"slskd_{Path.GetRandomFileName()}.dmp"); + + var url = URLTemplate.Replace("$RID", GetRID()); + + await Download(url, BinFile); + + if (!OperatingSystem.IsWindows()) + { + await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\""); + } + + await ExecAsync(BinFile, $"collect --process-id {Environment.ProcessId} --type full --output {outputFile}"); + + return outputFile; + } + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + TryDelete(BinFile); + } + + Disposed = true; + } + } + + private async Task Download(string url, string destination) + { + using var http = new HttpClient(); + + using var localStream = new FileStream(destination, FileMode.OpenOrCreate); + using var remoteStream = await http.GetStreamAsync(url); + + await remoteStream.CopyToAsync(localStream); + } + + private async Task ExecAsync(string bin, string args) + { + using var process = new Process(); + process.StartInfo.FileName = bin; + process.StartInfo.Arguments = args; + process.Start(); + await process.WaitForExitAsync(); + } + + private string GetRID() + { + // one of: x86, x64, arm, arm64, wasm, s390x + var arch = RuntimeInformation.ProcessArchitecture.ToString().ToLower(); + + // .RuntimeIdentifier returns a very specific (e.g. win10-x64) RID, and we need a generic one (e.g. win-x64). rather + // than trying to hack this up to derive a generic RID, only inspect this to see if this build targeted musl libc (we + // can't get this any other way) + var isMusl = RuntimeInformation.RuntimeIdentifier.ToLower().Contains("musl"); + + string os = default; + + // seems like there should be a way to just retrieve this, but there is not as of .NET 6 + if (OperatingSystem.IsLinux()) + { + os = "linux"; + } + else if (OperatingSystem.IsWindows()) + { + os = "win"; + } + else if (OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD()) + { + os = "osx"; + } + + if (os == default) + { + throw new PlatformNotSupportedException($"Unable to determine operating system. RID is {RuntimeInformation.RuntimeIdentifier}; did someone forget to update Dumper.cs to reflect .NET targeting changes?"); + } + + return $"{os}-{(isMusl ? "musl-" : string.Empty)}{arch}"; + } + + private bool TryDelete(string file) + { + try + { + File.Delete(file); + return true; + } + catch (FileNotFoundException) + { + return false; + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs b/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs index 4e829df6..d7904b7a 100644 --- a/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs +++ b/src/slskd/Common/Logging/ConsoleWriteLineLogger.cs @@ -28,7 +28,14 @@ namespace slskd /// <inheritdoc/> public void Write(LogEvent logEvent) { - Console.WriteLine(logEvent.RenderMessage()); + try + { + Console.WriteLine(logEvent.RenderMessage()); + } + catch + { + // noop. console may not be available in all cases. + } } } } diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index 3cf3c0a3..ac8be802 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -136,5 +136,15 @@ namespace slskd.Core.API return Ok(); } + + [HttpGet("dump")] + [Authorize] + public async Task<IActionResult> DumpMemory() + { + using var dumper = new Dumper(); + var file = await dumper.DumpAsync(); + + return PhysicalFile(file, "application/octet-stream", "slskd.dmp"); + } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 64a16076..42e9ffab 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -996,7 +996,14 @@ namespace slskd banner += "\n└────────────────────────────────────────────────────────┘"; - Console.WriteLine(banner); + try + { + Console.WriteLine(banner); + } + catch + { + // noop. console may not be available in all cases. + } } private static void VerifyDirectory(string directory, bool createIfMissing = true, bool verifyWriteable = true) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index f91b2f40..bb11e3ac 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -15383,9 +15383,9 @@ } }, "node_modules/terser": { - "version": "5.14.1", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.14.1.tgz", - "integrity": "sha512-+ahUAE+iheqBTDxXhTisdA8hgvbEG1hHOQ9xmNjeUJSoi6DU/gMrKNcfZjHkyY6Alnuyc+ikYJaxxfHkT3+WuQ==", + "version": "5.14.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.14.2.tgz", + "integrity": "sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA==", "dev": true, "dependencies": { "@jridgewell/source-map": "^0.3.2", @@ -28101,9 +28101,9 @@ } }, "terser": { - "version": "5.14.1", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.14.1.tgz", - "integrity": "sha512-+ahUAE+iheqBTDxXhTisdA8hgvbEG1hHOQ9xmNjeUJSoi6DU/gMrKNcfZjHkyY6Alnuyc+ikYJaxxfHkT3+WuQ==", + "version": "5.14.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.14.2.tgz", + "integrity": "sha512-oL0rGeM/WFQCUd0y2QrWxYnq7tfSuKBiqTjRPWrRgB46WD/kiwHwF8T23z78H6Q6kGCuuHcPB+KULHRdxvVGQA==", "dev": true, "requires": { "@jridgewell/source-map": "^0.3.2", |
