|
| 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 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.IO; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Microsoft.CodeAnalysis; |
| 10 | +using Microsoft.DotNet.Interactive; |
| 11 | +using Microsoft.DotNet.Interactive.Commands; |
| 12 | +using Microsoft.DotNet.Interactive.CSharp; |
| 13 | +using Microsoft.DotNet.Interactive.Utility; |
| 14 | +using Microsoft.Spark.Interop; |
| 15 | +using Microsoft.Spark.Sql; |
| 16 | +using Microsoft.Spark.Utils; |
| 17 | + |
| 18 | +namespace Microsoft.Spark.Extensions.DotNet.Interactive |
| 19 | +{ |
| 20 | + /// <summary> |
| 21 | + /// A kernel extension when using .NET for Apache Spark with Microsoft.DotNet.Interactive |
| 22 | + /// Adds nuget and assembly dependencies to the default <see cref="SparkSession"/> |
| 23 | + /// using <see cref="SparkContext.AddFile(string, bool)"/>. |
| 24 | + /// </summary> |
| 25 | + public class AssemblyKernelExtension : IKernelExtension |
| 26 | + { |
| 27 | + private const string TempDirEnvVar = "DOTNET_SPARK_EXTENSION_INTERACTIVE_TMPDIR"; |
| 28 | + |
| 29 | + private readonly PackageResolver _packageResolver = |
| 30 | + new PackageResolver(new PackageRestoreContextWrapper()); |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Called by the Microsoft.DotNet.Interactive Assembly Extension Loader. |
| 34 | + /// </summary> |
| 35 | + /// <param name="kernel">The kernel calling this method.</param> |
| 36 | + /// <returns><see cref="Task.CompletedTask"/> when extension is loaded.</returns> |
| 37 | + public Task OnLoadAsync(IKernel kernel) |
| 38 | + { |
| 39 | + if (kernel is CompositeKernel kernelBase) |
| 40 | + { |
| 41 | + Environment.SetEnvironmentVariable(Constants.RunningREPLEnvVar, "true"); |
| 42 | + |
| 43 | + DirectoryInfo tempDir = CreateTempDirectory(); |
| 44 | + kernelBase.RegisterForDisposal(new DisposableDirectory(tempDir)); |
| 45 | + |
| 46 | + kernelBase.AddMiddleware(async (command, context, next) => |
| 47 | + { |
| 48 | + if ((context.HandlingKernel is CSharpKernel kernel) && |
| 49 | + (command is SubmitCode) && |
| 50 | + TryGetSparkSession(out SparkSession sparkSession) && |
| 51 | + TryEmitAssembly(kernel, tempDir.FullName, out string assemblyPath)) |
| 52 | + { |
| 53 | + sparkSession.SparkContext.AddFile(assemblyPath); |
| 54 | + |
| 55 | + foreach (string filePath in GetPackageFiles(tempDir.FullName)) |
| 56 | + { |
| 57 | + sparkSession.SparkContext.AddFile(filePath); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + await next(command, context); |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + return Task.CompletedTask; |
| 66 | + } |
| 67 | + |
| 68 | + private DirectoryInfo CreateTempDirectory() |
| 69 | + { |
| 70 | + string envTempDir = Environment.GetEnvironmentVariable(TempDirEnvVar); |
| 71 | + string tempDirBasePath = string.IsNullOrEmpty(envTempDir) ? |
| 72 | + Directory.GetCurrentDirectory() : |
| 73 | + envTempDir; |
| 74 | + |
| 75 | + if (!IsPathValid(tempDirBasePath)) |
| 76 | + { |
| 77 | + throw new Exception($"[{GetType().Name}] Spaces in " + |
| 78 | + $"'{tempDirBasePath}' is unsupported. Set the {TempDirEnvVar} " + |
| 79 | + "environment variable to control the base path. Please see " + |
| 80 | + "https://issues.apache.org/jira/browse/SPARK-30126 and " + |
| 81 | + "https://github.com/apache/spark/pull/26773 for more details."); |
| 82 | + } |
| 83 | + |
| 84 | + return Directory.CreateDirectory( |
| 85 | + Path.Combine(tempDirBasePath, Path.GetRandomFileName())); |
| 86 | + } |
| 87 | + |
| 88 | + private bool TryEmitAssembly(CSharpKernel kernel, string dstPath, out string assemblyPath) |
| 89 | + { |
| 90 | + Compilation compilation = kernel.ScriptState.Script.GetCompilation(); |
| 91 | + string assemblyName = |
| 92 | + AssemblyLoader.NormalizeAssemblyName(compilation.AssemblyName); |
| 93 | + assemblyPath = Path.Combine(dstPath, $"{assemblyName}.dll"); |
| 94 | + if (!File.Exists(assemblyPath)) |
| 95 | + { |
| 96 | + FileSystemExtensions.Emit(compilation, assemblyPath); |
| 97 | + return true; |
| 98 | + } |
| 99 | + |
| 100 | + throw new Exception( |
| 101 | + $"TryEmitAssembly() unexpected duplicate assembly: ${assemblyPath}"); |
| 102 | + } |
| 103 | + |
| 104 | + private bool TryGetSparkSession(out SparkSession sparkSession) |
| 105 | + { |
| 106 | + sparkSession = SparkSession.GetDefaultSession(); |
| 107 | + return sparkSession != null; |
| 108 | + } |
| 109 | + |
| 110 | + private IEnumerable<string> GetPackageFiles(string path) |
| 111 | + { |
| 112 | + foreach (string filePath in _packageResolver.GetFiles(path)) |
| 113 | + { |
| 114 | + if (IsPathValid(filePath)) |
| 115 | + { |
| 116 | + yield return filePath; |
| 117 | + } |
| 118 | + else |
| 119 | + { |
| 120 | + // Copy file to a path without spaces. |
| 121 | + string fileDestPath = Path.Combine( |
| 122 | + path, |
| 123 | + Path.GetFileName(filePath).Replace(" ", string.Empty)); |
| 124 | + File.Copy(filePath, fileDestPath); |
| 125 | + yield return fileDestPath; |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /// <summary> |
| 131 | + /// In some versions of Spark, spaces is unsupported when using |
| 132 | + /// <see cref="SparkContext.AddFile(string, bool)"/>. |
| 133 | + /// |
| 134 | + /// For more details please see: |
| 135 | + /// - https://issues.apache.org/jira/browse/SPARK-30126 |
| 136 | + /// - https://github.com/apache/spark/pull/26773 |
| 137 | + /// </summary> |
| 138 | + /// <param name="path">The path to validate.</param> |
| 139 | + /// <returns>true if the path is supported by Spark, false otherwise.</returns> |
| 140 | + private bool IsPathValid(string path) |
| 141 | + { |
| 142 | + if (!path.Contains(" ")) |
| 143 | + { |
| 144 | + return true; |
| 145 | + } |
| 146 | + |
| 147 | + Version version = SparkEnvironment.SparkVersion; |
| 148 | + return (version.Major, version.Minor, version.Build) switch |
| 149 | + { |
| 150 | + (2, _, _) => false, |
| 151 | + (3, 0, _) => true, |
| 152 | + _ => throw new NotSupportedException($"Spark {version} not supported.") |
| 153 | + }; |
| 154 | + } |
| 155 | + } |
| 156 | +} |
0 commit comments