Skip to content

Refactor module assembly loading logic to allow the whole module to be loaded in a custom ALC - #16889

Merged
Dongbo Wang (daxian-dbw) merged 9 commits into
PowerShell:masterfrom
daxian-dbw:module
Feb 23, 2022
Merged

Dongbo Wang (daxian-dbw) merged 9 commits into
PowerShell:masterfrom
daxian-dbw:module

Conversation

@daxian-dbw

Copy link
Copy Markdown
Member

PR Summary

Related to #2083

Refactor module assembly loading logic to allow the whole module to be loaded in a custom ALC.

PR Context

The document Loading through .NET Core Assembly Load Contexts introduces a technique to allow a module author to fully control the potentially conflicting dependencies by leveraging a custom AssemblyLoadContext. This technique was used by the Bicep module, and have a great example documented in this blog post: Resolving PowerShell Module Conflicts.

This technique requires the use of dependency assemblies to be wrapped in a "bridge" assembly. The true module assemblies will need to reference the "bridge" assembly, depending on which to pull in the real dependencies. It's usually not easy to satisfy that requirement, especially for an existing module, that often means significant refactoring.

This PR refactors how assembly loading works during module loading. It leverages the existing-but-not-really-used AssemblyCache to make sure a nested module assembly or a root module assembly will not be loaded into the default ALC when they are designed to be loaded by a custom ALC of the module.

With the changes in this PR, we don't need the "bridge" assembly anymore, the real nested/root module assemblies can be directly loaded in a custom ALC, which handles all their dependencies in an isolated way.

Example

The IsolatedModule located at <repo-root>\test\tools\Modules\IsolatedModule serves as an example of such a module, and it's also used in our test.
The module assemblies are published by <repo-root>\test\tools\TestAlc. Simply run dotnet publish in this folder to populate the assemblies to the folder <repo-root>\test\tools\Modules\IsolatedModule with the pre-defined folder structure.

The layout of files in IsolatedModule is:

│   IsolatedModule.psd1
│   Test.Isolated.Init.dll
│
└───Dependencies
        Newtonsoft.Json.dll
        Test.Isolated.Nested.dll
        Test.Isolated.Root.dll

The content of IsolatedModule.psd1 is:

@{
    ModuleVersion = '0.0.1'
    GUID = '20d4742b-b17d-4ce8-b8da-29b25433cd18'
    Author = 'Microsoft Corporation'

    RootModule = 'Test.Isolated.Root.dll'
    NestedModules = @('Test.Isolated.Init.dll', 'Test.Isolated.Nested.dll')
    FunctionsToExport = @()
    CmdletsToExport = @('Test-NestedCommand', 'Test-RootCommand')
    VariablesToExport = '*'
    AliasesToExport = @()
}

The nested module Test.Isolated.Init.dll is the only one that PowerShell can discover under the module base folder. It contains a custom ALC implementation and will set up the Resolving handler to handle loading the real module assemblies Test.Isolated.Nested.dll and Test.Isolated.Root.dll.

The processing order for module loading is RequiredAssemblies -> NestedModules -> RootModule.
In this example, Test.Isolated.Init.dll is the first nested module and it gets processed first. After that, Resovling handler has been setup to deal with Test.Isolated.Nested.dll and Test.Isolated.Root.dll. PowerShell won't be able to locate those 2 assemblies, so it's up to the Resovling handler to load them in the custom ALC.

Test.Isolated.Nested.dll depends on the 10.0.0.0 version of Newtonsoft.Json.dll, which will be loaded by the custom ALC when requested.

All module assemblies will be put in the AssemblyCache, and PowerShell type resolution always searches AssemblyCache first (existing behavior). So, public types exposed by Test.Isolated.Nested.dll and Test.Isolated.Root.dll will be resolvable, but the specific Newtonsoft.Json.dll under the Dependencies folder will always be invisible to PowerShell.

NOTE: As is called in the processing order, RequiredAssemblies are first processed, by which time the Resolving handler hasn't been setup yet. So, it's impossible to load required assemblies into the module's custom ALC. But RequiredAssemblies is more commonly used by script module instead of binary module.

PR Checklist

@iSazonov

Copy link
Copy Markdown
Collaborator

Dongbo Wang (@daxian-dbw) Is it all only about binary modules?
If I remember right we discussed Import-Module -Isolate to put whole module in custom dynamic-created ALC with generic handler - do you consider this?

@daxian-dbw

Copy link
Copy Markdown
Member Author

This is only for binary module, and only for binary modules that do not use types from the conflicting assembly as parameter type or return type.

We are not going with the "Import-Module -Isolated" approach because of the type-identity issue. An end user won't really understand how the module is supposed to work, and allowing the end user to choose whether or not to import a module to a custom ALC just won't work -- the end user will run into the type-identity issue without a clue of what's going on, and will just believe it's a broken feature.

We have discussed this in the RFC in length, and it's clear that it's the module author's responsibility to avoid conflicts, and our job is to make that easier.

@iSazonov

Copy link
Copy Markdown
Collaborator

Newtonsoft.Json.dll

Can we replace the dll with custom test dll? Newtonsoft is updated frequently (with security fixes too) and we will have to track and update it.

@daxian-dbw

Copy link
Copy Markdown
Member Author

No need to update the version in the test. The test is deliberately using an old version 10.0.0.1 to indicate that it can depends on specific version of the assembly without being affected by what PowerShell is using.

@iSazonov

Copy link
Copy Markdown
Collaborator

No need to update the version in the test.

I hope MSFT compliance CIs pass this :-)

Comment thread build.psm1 Resolved
@ghost ghost added Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept and removed Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept labels Feb 17, 2022
@ghost ghost added Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept and removed Waiting on Author The PR was reviewed and requires changes or comments from the author before being accept labels Feb 17, 2022

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Overall, changes LGTM. I just have a few comments/questions, mainly about making sure comments are clear.

@daxian-dbw

Copy link
Copy Markdown
Member Author

Paul Higinbotham (@PaulHigin) Thanks for the review! I will review the comments to make them more descriptive and with more details.

@daxian-dbw Dongbo Wang (daxian-dbw) added the CL-Engine Indicates that a PR should be marked as an engine change in the Change Log label Feb 18, 2022
@pull-request-quantifier-deprecated

Copy link
Copy Markdown

This PR has 662 quantified lines of changes. In general, a change size of upto 200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra Large
Size       : +412 -250
Percentile : 88.73%

Total files changed: 16

Change summary by file extension:
.psm1 : +11 -5
.cs : +277 -244
.ps1 : +65 -1
.psd1 : +13 -0
.sln : +0 -0
.csproj : +46 -0

Change counts above are quantified counts, based on the PullRequestQuantifier customizations.

Why proper sizing of changes matters

Optimal pull request sizes drive a better predictable PR flow as they strike a
balance between between PR complexity and PR review overhead. PRs within the
optimal size (typical small, or medium sized PRs) mean:

  • Fast and predictable releases to production:
    • Optimal size changes are more likely to be reviewed faster with fewer
      iterations.
    • Similarity in low PR complexity drives similar review times.
  • Review quality is likely higher as complexity is lower:
    • Bugs are more likely to be detected.
    • Code inconsistencies are more likely to be detetcted.
  • Knowledge sharing is improved within the participants:
    • Small portions can be assimilated better.
  • Better engineering practices are exercised:
    • Solving big problems by dividing them in well contained, smaller problems.
    • Exercising separation of concerns within the code changes.

What can I do to optimize my changes

  • Use the PullRequestQuantifier to quantify your PR accurately
    • Create a context profile for your repo using the context generator
    • Exclude files that are not necessary to be reviewed or do not increase the review complexity. Example: Autogenerated code, docs, project IDE setting files, binaries, etc. Check out the Excluded section from your prquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in your prquantifier.yaml context profile.
    • Only use the labels that matter to you, see context specification to customize your prquantifier.yaml context profile.
  • Change your engineering behaviors
    • For PRs that fall outside of the desired spectrum, review the details and check if:
      • Your PR could be split in smaller, self-contained PRs instead
      • Your PR only solves one particular issue. (For example, don't refactor and code new features in the same PR).

How to interpret the change counts in git diff output

  • One line was added: +1 -0
  • One line was deleted: +0 -1
  • One line was modified: +1 -1 (git diff doesn't know about modified, it will
    interpret that line like one addition plus one deletion)
  • Change percentiles: Change characteristics (addition, deletion, modification)
    of this PR in relation to all other PRs within the repository.


Was this comment helpful? 👍  :ok_hand:  :thumbsdown: (Email)
Customize PullRequestQuantifier for this repository.

@iSazonov

Copy link
Copy Markdown
Collaborator

Dongbo Wang (@daxian-dbw) I forget ask about processing native dll-s. I don't see the scenarios in description and tests. Do you consider this?

@daxian-dbw

Copy link
Copy Markdown
Member Author

No special handling to native dlls. A module author can register the ResolvingUnmanagedDll event to the custom ALC, which will take precedence when resolving native dlls.

@iSazonov

Copy link
Copy Markdown
Collaborator

Great!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CL-Engine Indicates that a PR should be marked as an engine change in the Change Log Extra Large

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants