From 2d4a7934831c791cfceb1ec7a37a39d4824aeca1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 20 Jul 2022 20:40:50 -0500 Subject: add Dumper --- src/slskd/Common/Dumper.cs | 156 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 src/slskd/Common/Dumper.cs (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs new file mode 100644 index 00000000..da6ec06c --- /dev/null +++ b/src/slskd/Common/Dumper.cs @@ -0,0 +1,156 @@ +// +// 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/. +// + +namespace slskd +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Net.Http; + using System.Runtime.InteropServices; + using System.Threading.Tasks; + + /// + /// Dumps the contents of the application's memory to a .dmp file using dotnet-dump. + /// + /// + /// + /// Monitor https://docs.microsoft.com/en-us/dotnet/core/diagnostics/dotnet-dump for tool updates. Currently supported + /// runtime IDs: + /// + /// + /// Currently supported runtime IDs: + /// https://aka.ms/dotnet-dump/win-x86 + /// https://aka.ms/dotnet-dump/win-x64 + /// https://aka.ms/dotnet-dump/win-arm + /// https://aka.ms/dotnet-dump/win-arm64 + /// https://aka.ms/dotnet-dump/osx-x64 + /// https://aka.ms/dotnet-dump/linux-x64 + /// https://aka.ms/dotnet-dump/linux-arm + /// https://aka.ms/dotnet-dump/linux-arm64 + /// https://aka.ms/dotnet-dump/linux-musl-x64 + /// https://aka.ms/dotnet-dump/linux-musl-arm64 + /// + /// + /// + 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 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); + + await ExecAsync(BinFile, Environment.ProcessId, 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, int pid, string output) + { + using var process = new Process(); + process.StartInfo.FileName = bin; + process.StartInfo.Arguments = $"collect --process-id {pid} --type full --output {output}"; + 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 -- cgit v1.2.3 From f15487046ab14c0de4ab2562a02dd9467b54703f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 20 Jul 2022 21:39:41 -0500 Subject: chmod bin on linux/mac --- src/slskd/Common/Dumper.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs index da6ec06c..766fe803 100644 --- a/src/slskd/Common/Dumper.cs +++ b/src/slskd/Common/Dumper.cs @@ -69,7 +69,12 @@ namespace slskd await Download(url, BinFile); - await ExecAsync(BinFile, Environment.ProcessId, outputFile); + 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; } @@ -97,11 +102,11 @@ namespace slskd await remoteStream.CopyToAsync(localStream); } - private async Task ExecAsync(string bin, int pid, string output) + private async Task ExecAsync(string bin, string args) { using var process = new Process(); process.StartInfo.FileName = bin; - process.StartInfo.Arguments = $"collect --process-id {pid} --type full --output {output}"; + process.StartInfo.Arguments = args; process.Start(); await process.WaitForExitAsync(); } -- cgit v1.2.3 From 6934fd27435923ef267de37438dd6c30e72b0793 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 Jul 2022 15:03:39 -0500 Subject: remove console logging --- src/slskd/Application.cs | 20 +++++++++----------- src/slskd/Common/Logging/ConsoleWriteLineLogger.cs | 9 ++++++++- src/slskd/Program.cs | 9 ++++++++- 3 files changed, 25 insertions(+), 13 deletions(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 9d7e96ef..a2598d1e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -124,10 +124,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; @@ -464,14 +464,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)) { @@ -557,7 +556,6 @@ namespace slskd private void Client_UserStatusChanged(object sender, UserStatus args) { - Console.WriteLine($"[USER] {args.Username}: {args.Presence}"); } private Task PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename) @@ -626,7 +624,7 @@ namespace slskd string localFilename; FileInfo fileInfo = default; - Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); + Log.Information("[{Context}] {Username} requested {Filename}]", "UPLOAD REQUESTED", username, filename); try { @@ -641,7 +639,7 @@ namespace slskd } catch (NotFoundException) { - Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); + Log.Information("[{Context}] {Filename} for {Username}: file not found", "UPLOAD REJECTED", username, filename); throw new DownloadEnqueueException($"File not shared."); } @@ -679,7 +677,7 @@ namespace slskd await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); }).ContinueWith(t => { - Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); + Log.Information("[{Context}] {Filename} for {Username}: {Message}", "UPLOAD FAILED", username, filename, t.Exception?.Message); }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget } catch (Exception ex) @@ -875,7 +873,7 @@ namespace slskd var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); - Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText} (forecasted position: {forecastedPosition})"); + Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText); return new SearchResponse( Client.Username, 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 /// 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/Program.cs b/src/slskd/Program.cs index ae4f2015..f11132b4 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -991,7 +991,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) -- cgit v1.2.3