|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.CommandLine; |
| 5 | +using System.Diagnostics; |
| 6 | +using System.Text.Json; |
| 7 | +using Microsoft.DotNet.Cli.Commands.Run; |
| 8 | +using Microsoft.DotNet.Cli.Utils; |
| 9 | +using Microsoft.DotNet.Cli.Utils.Extensions; |
| 10 | + |
| 11 | +namespace Microsoft.DotNet.Cli.Commands.Clean.FileBasedAppArtifacts; |
| 12 | + |
| 13 | +internal sealed class CleanFileBasedAppArtifactsCommand(ParseResult parseResult) : CommandBase(parseResult) |
| 14 | +{ |
| 15 | + public override int Execute() |
| 16 | + { |
| 17 | + bool dryRun = _parseResult.GetValue(CleanFileBasedAppArtifactsCommandParser.DryRunOption); |
| 18 | + |
| 19 | + using var metadataFileStream = OpenMetadataFile(); |
| 20 | + |
| 21 | + bool anyErrors = false; |
| 22 | + int count = 0; |
| 23 | + |
| 24 | + foreach (var folder in GetFoldersToRemove()) |
| 25 | + { |
| 26 | + if (dryRun) |
| 27 | + { |
| 28 | + Reporter.Verbose.WriteLine($"Would remove folder: {folder.FullName}"); |
| 29 | + count++; |
| 30 | + } |
| 31 | + else |
| 32 | + { |
| 33 | + try |
| 34 | + { |
| 35 | + folder.Delete(recursive: true); |
| 36 | + Reporter.Verbose.WriteLine($"Removed folder: {folder.FullName}"); |
| 37 | + count++; |
| 38 | + } |
| 39 | + catch (Exception ex) |
| 40 | + { |
| 41 | + Reporter.Error.WriteLine(string.Format(CliCommandStrings.CleanFileBasedAppArtifactsErrorRemovingFolder, folder, ex.Message).Red()); |
| 42 | + anyErrors = true; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + Reporter.Output.WriteLine( |
| 48 | + dryRun |
| 49 | + ? CliCommandStrings.CleanFileBasedAppArtifactsWouldRemoveFolders |
| 50 | + : CliCommandStrings.CleanFileBasedAppArtifactsTotalFoldersRemoved, |
| 51 | + count); |
| 52 | + |
| 53 | + if (!dryRun) |
| 54 | + { |
| 55 | + UpdateMetadata(metadataFileStream); |
| 56 | + } |
| 57 | + |
| 58 | + return anyErrors ? 1 : 0; |
| 59 | + } |
| 60 | + |
| 61 | + private IEnumerable<DirectoryInfo> GetFoldersToRemove() |
| 62 | + { |
| 63 | + var directory = new DirectoryInfo(VirtualProjectBuildingCommand.GetTempSubdirectory()); |
| 64 | + |
| 65 | + if (!directory.Exists) |
| 66 | + { |
| 67 | + Reporter.Error.WriteLine(string.Format(CliCommandStrings.CleanFileBasedAppArtifactsDirectoryNotFound, directory.FullName).Yellow()); |
| 68 | + yield break; |
| 69 | + } |
| 70 | + |
| 71 | + Reporter.Output.WriteLine(CliCommandStrings.CleanFileBasedAppArtifactsScanning, directory.FullName); |
| 72 | + |
| 73 | + var days = _parseResult.GetValue(CleanFileBasedAppArtifactsCommandParser.DaysOption); |
| 74 | + var cutoff = DateTime.UtcNow.AddDays(-days); |
| 75 | + |
| 76 | + foreach (var subdir in directory.GetDirectories()) |
| 77 | + { |
| 78 | + if (subdir.LastWriteTimeUtc < cutoff) |
| 79 | + { |
| 80 | + yield return subdir; |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + private static FileInfo GetMetadataFile() |
| 86 | + { |
| 87 | + return new FileInfo(VirtualProjectBuildingCommand.GetTempSubpath(RunFileArtifactsMetadata.FilePath)); |
| 88 | + } |
| 89 | + |
| 90 | + private FileStream? OpenMetadataFile() |
| 91 | + { |
| 92 | + if (!_parseResult.GetValue(CleanFileBasedAppArtifactsCommandParser.AutomaticOption)) |
| 93 | + { |
| 94 | + return null; |
| 95 | + } |
| 96 | + |
| 97 | + // Open and lock the metadata file to ensure we are the only automatic cleanup process. |
| 98 | + return GetMetadataFile().Open(FileMode.Create, FileAccess.ReadWrite, FileShare.None); |
| 99 | + } |
| 100 | + |
| 101 | + private static void UpdateMetadata(FileStream? metadataFileStream) |
| 102 | + { |
| 103 | + if (metadataFileStream is null) |
| 104 | + { |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + var metadata = new RunFileArtifactsMetadata |
| 109 | + { |
| 110 | + LastAutomaticCleanupUtc = DateTime.UtcNow, |
| 111 | + }; |
| 112 | + JsonSerializer.Serialize(metadataFileStream, metadata, RunFileJsonSerializerContext.Default.RunFileArtifactsMetadata); |
| 113 | + } |
| 114 | + |
| 115 | + /// <summary> |
| 116 | + /// Starts a background process to clean up file-based app artifacts if needed. |
| 117 | + /// </summary> |
| 118 | + public static void StartAutomaticCleanupIfNeeded() |
| 119 | + { |
| 120 | + if (ShouldStartAutomaticCleanup()) |
| 121 | + { |
| 122 | + Reporter.Verbose.WriteLine("Starting automatic cleanup of file-based app artifacts."); |
| 123 | + |
| 124 | + var startInfo = new ProcessStartInfo |
| 125 | + { |
| 126 | + FileName = new Muxer().MuxerPath, |
| 127 | + Arguments = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart( |
| 128 | + [ |
| 129 | + CleanCommandParser.GetCommand().Name, |
| 130 | + CleanFileBasedAppArtifactsCommandParser.Command.Name, |
| 131 | + CleanFileBasedAppArtifactsCommandParser.AutomaticOption.Name, |
| 132 | + ]), |
| 133 | + UseShellExecute = false, |
| 134 | + RedirectStandardInput = true, |
| 135 | + RedirectStandardOutput = true, |
| 136 | + RedirectStandardError = true, |
| 137 | + CreateNoWindow = true, |
| 138 | + }; |
| 139 | + |
| 140 | + Process.Start(startInfo); |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + private static bool ShouldStartAutomaticCleanup() |
| 145 | + { |
| 146 | + if (Env.GetEnvironmentVariableAsBool("DOTNET_CLI_DISABLE_FILE_BASED_APP_ARTIFACTS_AUTOMATIC_CLEANUP", defaultValue: false)) |
| 147 | + { |
| 148 | + return false; |
| 149 | + } |
| 150 | + |
| 151 | + FileInfo? metadataFile = null; |
| 152 | + try |
| 153 | + { |
| 154 | + metadataFile = GetMetadataFile(); |
| 155 | + |
| 156 | + if (!metadataFile.Exists) |
| 157 | + { |
| 158 | + return true; |
| 159 | + } |
| 160 | + |
| 161 | + using var stream = metadataFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read); |
| 162 | + var metadata = JsonSerializer.Deserialize(stream, RunFileJsonSerializerContext.Default.RunFileArtifactsMetadata); |
| 163 | + |
| 164 | + if (metadata?.LastAutomaticCleanupUtc is not { } timestamp) |
| 165 | + { |
| 166 | + return true; |
| 167 | + } |
| 168 | + |
| 169 | + // Start automatic cleanup every two days. |
| 170 | + return timestamp.AddDays(2) < DateTime.UtcNow; |
| 171 | + } |
| 172 | + catch (Exception ex) |
| 173 | + { |
| 174 | + Reporter.Verbose.WriteLine($"Cannot access artifacts metadata file '{metadataFile?.FullName}': {ex}"); |
| 175 | + |
| 176 | + // If the file cannot be accessed, automatic cleanup might already be running. |
| 177 | + return false; |
| 178 | + } |
| 179 | + } |
| 180 | +} |
| 181 | + |
| 182 | +/// <summary> |
| 183 | +/// Metadata stored at the root level of the file-based app artifacts directory. |
| 184 | +/// </summary> |
| 185 | +internal sealed class RunFileArtifactsMetadata |
| 186 | +{ |
| 187 | + public const string FilePath = "dotnet-run-file-artifacts-metadata.json"; |
| 188 | + |
| 189 | + public DateTime? LastAutomaticCleanupUtc { get; init; } |
| 190 | +} |
0 commit comments