Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DYN-7691: Add assembly load contexts to packages #15424

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Forms;
Expand Down Expand Up @@ -2218,7 +2219,7 @@ private void AddDllFile(string filename)
{
// we're not sure if this is a managed assembly or not
// we try to load it, if it fails - we add it as an additional file
var result = PackageLoader.TryLoadFrom(filename, out Assembly assem);
var result = PackageLoader.TryLoadFrom(AssemblyLoadContext.Default, filename, out Assembly assem);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if this needs to be isolated or not.

Copy link
Member

@mjkkirschner mjkkirschner Oct 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

umm, certainly seems so? I guess this should use an MLC to determine what type of binary it is before loading it into the real ALC for this package?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh - this is just for publishing, I mean, I still think what I stated is the way to go, but maybe less important.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might add a new task for this

if (result)
{
var assemName = assem.GetName().Name;
Expand Down
8 changes: 6 additions & 2 deletions src/DynamoPackages/Package.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Dynamo.Core;
using Dynamo.Exceptions;
using Dynamo.Graph.Nodes.CustomNodes;
Expand Down Expand Up @@ -228,6 +229,7 @@ internal IEnumerable<Assembly> NodeLibraries
/// </summary>
internal bool RequiresSignedEntryPoints { get; set; }

internal AssemblyLoadContext AssemblyLoadContext { get; set; } = AssemblyLoadContext.Default;
#endregion

public Package(string directory, string name, string versionName, string license)
Expand All @@ -242,6 +244,8 @@ public Package(string directory, string name, string versionName, string license
LoadedCustomNodes = new ObservableCollection<CustomNodeInfo>();
AdditionalFiles = new ObservableCollection<PackageFileInfo>();
Header = PackageUploadBuilder.NewRequestBody(this);

AssemblyLoadContext = new PkgAssemblyLoadContext(Name + "@" + VersionName, RootDirectory);
}

public static Package FromDirectory(string rootPath, ILogger logger)
Expand Down Expand Up @@ -374,7 +378,7 @@ internal IEnumerable<PackageAssembly> EnumerateAndLoadAssembliesInBinDirectory()
if (shouldLoadFile)
{
// dll files may be un-managed, skip those
var result = PackageLoader.TryLoadFrom(assemFile.FullName, out assem);
var result = PackageLoader.TryLoadFrom(AssemblyLoadContext, assemFile.FullName, out assem);
if (result)
{
// IsNodeLibrary may fail, we store the warnings here and then show
Expand Down Expand Up @@ -586,7 +590,7 @@ internal void UninstallCore(CustomNodeManager customNodeManager, PackageLoader p
if (BuiltInPackage)
{
LoadState.SetAsUnloaded();
Analytics.TrackEvent(Actions.BuiltInPackageConflict, Categories.PackageManagerOperations, $"{Name } {versionName} set unloaded");
Analytics.TrackEvent(Actions.BuiltInPackageConflict, Categories.PackageManagerOperations, $"{Name} {versionName} set unloaded");

RaisePropertyChanged(nameof(LoadState));

Expand Down
46 changes: 46 additions & 0 deletions src/DynamoPackages/PackageAssemblyLoadContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;

namespace Dynamo.PackageManager
{
internal class PkgAssemblyLoadContext : AssemblyLoadContext
{
private readonly string RootDir;
private IEnumerable<FileInfo> pkgAssemblies = null;
public PkgAssemblyLoadContext(string name, string pkgRoot, bool unloadable = true) : base(name, unloadable)
{
this.RootDir = pkgRoot;
}

protected override Assembly Load(AssemblyName assemblyName)
{
pkgAssemblies ??= new DirectoryInfo(RootDir).EnumerateFiles("*.dll", new EnumerationOptions() { RecurseSubdirectories = true });

var targetAssemName = assemblyName.Name + ".dll";
var targetAssembly = pkgAssemblies.FirstOrDefault(x => x.Name == targetAssemName);
if (targetAssembly != null)
{
return LoadFromAssemblyPath(targetAssembly.FullName);
}
return null;
}

protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the fact that you can override this function mean that you can also load unmanaged assemblies in isolation?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sadly no, you can only override the search algorithm

{
pkgAssemblies ??= new DirectoryInfo(RootDir).EnumerateFiles("*.dll", new EnumerationOptions() { RecurseSubdirectories = true });

var targetAssemName = unmanagedDllName + ".dll";
var targetAssembly = pkgAssemblies.FirstOrDefault(x => x.Name == targetAssemName);
if (targetAssembly != null)
{
return NativeLibrary.Load(targetAssembly.FullName);
}
return IntPtr.Zero;
}
}
}
46 changes: 42 additions & 4 deletions src/DynamoPackages/PackageLoader.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using Dynamo.Core;
using Dynamo.Exceptions;
using Dynamo.Extensions;
Expand Down Expand Up @@ -37,6 +37,38 @@ public class PackageLoader : LogSourceBase
internal event Func<string, IExtension> RequestLoadExtension;
internal event Action<IExtension> RequestAddExtension;

private HashSet<string> packagesToIsolate = null;
internal HashSet<string> PackagesToIsolate
{
get
{
if (packagesToIsolate == null)
{
packagesToIsolate = [];

string pkgs = DynamoModel.FeatureFlags?.CheckFeatureFlag("IsolatePackages", string.Empty);
if (!string.IsNullOrEmpty(pkgs))
{
foreach (var x in pkgs.Split(","))
{
packagesToIsolate.Add(x);
}
}


pkgs = DynamoModel.FeatureFlags?.CheckFeatureFlag("DoNotIsolatePackages", string.Empty);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Who specifies which packages should be isolated and which shouldn't? If we do, how do we decide that? Is this meant for only the packages that are owned by us? If not, how would this be scalable? Am I right in assuming that in the long run, we'll be getting rid of these feature flags to load all packages in isolation by default (except for the ones that already use ALCs, i.e. if there is a way for us to know that ahead of time)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I foresee that some packages might have issues with being loaded in isolation (maybe the interaction between the isolated types vs the ones in the main load context).
So the main reason for adding feature flags is to slowly roll it out for all packages and have the option to disable it for a select few(like the ones that are already isolated on the package side )

As for “how do we decide which ones to isolate”:
I was thinking to take a couple at a time from the list I used to notify package maintainers about the dotnet8 migration.

if (!string.IsNullOrEmpty(pkgs))
{
foreach (var x in pkgs.Split(","))
{
packagesToIsolate.Remove(x);
}
}
}
return packagesToIsolate;
}
}

/// <summary>
/// This event is raised when a package is first added to the list of packages this package loader is loading.
/// This event occurs before the package is fully loaded.
Expand Down Expand Up @@ -201,7 +233,12 @@ private void TryLoadPackageIntoLibrary(Package package)
{
var dynamoVersion = VersionUtilities.PartialParse(DynamoModel.Version);

List<Assembly> blockedAssemblies = new List<Assembly>();
if (PackagesToIsolate.Contains(package.Name) || PackagesToIsolate.Contains("All"))
{
package.AssemblyLoadContext = new PkgAssemblyLoadContext(package.Name + "@" + package.VersionName, package.RootDirectory);
}

List<Assembly> blockedAssemblies = [];
// Try to load node libraries from all assemblies
foreach (var assem in package.EnumerateAndLoadAssembliesInBinDirectory())
{
Expand Down Expand Up @@ -742,14 +779,15 @@ internal static void CleanSharedPublishLoadContext(MetadataLoadContext mlc)
/// <summary>
/// Attempt to load a managed assembly in to LoadFrom context.
/// </summary>
/// <param name="alc"></param>
/// <param name="filename">The filename of a DLL</param>
/// <param name="assem">out Assembly - the passed value does not matter and will only be set if loading succeeds</param>
/// <returns>Returns true if success, false if BadImageFormatException (i.e. not a managed assembly)</returns>
internal static bool TryLoadFrom(string filename, out Assembly assem)
internal static bool TryLoadFrom(AssemblyLoadContext alc, string filename, out Assembly assem)
{
try
{
assem = Assembly.LoadFrom(filename);
assem = alc.LoadFromAssemblyPath(filename);
return true;
}
catch (FileLoadException e)
Expand Down
4 changes: 3 additions & 1 deletion src/Tools/DynamoFeatureFlags/FeatureFlagsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ internal FeatureFlagsClient(string userkey, string mobileKey = null, bool testMo
AllFlags = LdValue.ObjectFrom(new Dictionary<string,LdValue> { { "TestFlag1",LdValue.Of(true) },
{ "TestFlag2", LdValue.Of("I am a string") },
//in tests we want instancing on so we can test it.
{ "graphics-primitive-instancing", LdValue.Of(true) } });
{ "graphics-primitive-instancing", LdValue.Of(true) },
{ "IsolatePackages", LdValue.Of("Package1,Package2") }
});
return;
}

Expand Down
55 changes: 55 additions & 0 deletions test/Libraries/PackageManagerTests/PackageLoaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading;
using Dynamo.Configuration;
using Dynamo.Core;
Expand All @@ -12,7 +14,10 @@
using Dynamo.Graph.Nodes.CustomNodes;
using Dynamo.Graph.Workspaces;
using Dynamo.Interfaces;
using Dynamo.Models;
using Dynamo.Scheduler;
using Dynamo.Search.SearchElements;
using DynamoUtilities;
using Moq;
using NUnit.Framework;

Expand Down Expand Up @@ -644,6 +649,56 @@ public void PlacingCustomNodeInstanceFromPackageRetainsCorrectPackageInfoState()
loader.RequestLoadNodeLibrary -= libraryLoader.LoadLibraryAndSuppressZTSearchImport;
}

[Test]
public void LoadPackagesInAssemblyIsolation()
{
// Needed for FeatureFlags
Assert.IsTrue(DynamoModel.IsTestMode);
Assert.AreEqual(DynamoModel.FeatureFlags.CheckFeatureFlag<string>("IsolatePackages", ""), "Package1,Package2");

var loader = GetPackageLoader();
var libraryLoader = new ExtensionLibraryLoader(CurrentDynamoModel);

loader.PackagesLoaded += libraryLoader.LoadPackages;
loader.RequestLoadNodeLibrary += libraryLoader.LoadLibraryAndSuppressZTSearchImport;


var packageDirectory = Path.Combine(TestDirectory, "testAssemblyIsolation", "Package1");
var packageDirectory2 = Path.Combine(TestDirectory, "testAssemblyIsolation", "Package2");
var package1 = Package.FromDirectory(packageDirectory, CurrentDynamoModel.Logger);
var package2 = Package.FromDirectory(packageDirectory2, CurrentDynamoModel.Logger);
loader.LoadPackages([package1, package2]);

// 2 packages loaded as expected
var expectedLoadedPackageNum = 0;
foreach (var pkg in loader.LocalPackages)
{
if (pkg.Name == "Package1" || pkg.Name == "Package2")
{
expectedLoadedPackageNum++;
}
}
Assert.AreEqual(2, expectedLoadedPackageNum);

string openPath = Path.Combine(TestDirectory, @"testAssemblyIsolation\graph.dyn");
RunModel(openPath);

var expectedVersions = 0;
var pkgLoadContexts = AssemblyLoadContext.All.Where(x => x.Name.Equals("[email protected]") || x.Name.Equals("[email protected]")).ToList();
foreach (var pkg in pkgLoadContexts)
{
var dep = pkg.Assemblies.FirstOrDefault(x => x.GetName().Name == "Newtonsoft.Json");
Assert.IsNotNull(dep);

var ver = dep.GetName().Version.ToString();
// Expected both versions of Newtonsoft to be loaded
if (ver == "13.0.0.0" || ver == "8.0.0.0")
{
expectedVersions++;
}
}
Assert.AreEqual(2, expectedVersions);
}

[Test]
public void LoadingConflictingCustomNodePackageDoesNotGetLoaded()
Expand Down
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions test/testAssemblyIsolation/Package1/pkg.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"license":"","file_hash":null,"name":"Package1","version":"1.0.0","description":"original package","group":"","keywords":null,"dependencies":[],"contents":"","engine_version":"2.1.0.7840","engine":"dynamo","engine_metadata":"","site_url":"","repository_url":"","contains_binaries":true,"node_libraries":["TestAssemblyIsolation1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"]}
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions test/testAssemblyIsolation/Package2/pkg.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"license":"","file_hash":null,"name":"Package2","version":"1.0.0","description":"original package","group":"","keywords":null,"dependencies":[],"contents":"","engine_version":"2.1.0.7840","engine":"dynamo","engine_metadata":"","site_url":"","repository_url":"","contains_binaries":true,"node_libraries":["TestAssemblyIsolation2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"]}
Loading
Loading