Skip to content

Add new Dispose {} type block so script cmdlets have opportunity to cleanup #6673

Closed

Description

Was discussing with Jeffrey Snover (@jpsnover) a concern that if a cmdlet opens a resource (like a database connection) in Begin, and later in the pipeline an exception is thrown, End is not called to dispose of the connection.

Steps to reproduce

function a {
    [cmdletbinding()]
    param()

    begin { "a:begin" }
    process { 1 }
    end { "a:end" }
}

function b {
    [cmdletbinding()]
    param([parameter(ValueFromPipeline=$true)]$a)

    begin { "b:begin" }
    process { $a; throw 'oops' }
}

a | b

Expected behavior

b:begin
a:begin
a:end
oops
At /Users/steve/test/end_not_called.ps1:15 char:19
+     process { $a; throw "oops" }
+                   ~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (oops:String) [], RuntimeException
    + FullyQualifiedErrorId : oops

Actual behavior

b:begin
a:begin
oops
At /Users/steve/test/end_not_called.ps1:15 char:19
+     process { $a; throw "oops" }
+                   ~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (oops:String) [], RuntimeException
    + FullyQualifiedErrorId : oops

Environment data

Name                           Value
----                           -----
PSVersion                      6.1.0-preview.1
PSEdition                      Core
GitCommitId                    v6.1.0-preview.1
OS                             Darwin 17.5.0 Darwin Kernel Version 17.5.0: Mon Mar  5 22:24:32 PST 2018; root:xnu-4570.51.1~1/RELEASE_X86_64
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. BrucePay commented on Apr 18, 2018

    @BrucePay
    Collaborator

    Steve Lee (@SteveL-MSFT) I had some further discussions with Jeffrey Snover (@jpsnover). Basically EndProcessing isn't called if there is an exception because it's not a destructor. EndProcessing is just part of the normal processing. Consider a counter function function count {begin {$c=0} process {$c++} end {$c}} . An exception should terminate function execution not resume execution at end. If it ran end then whatever was in $c would be incorrectly emitted to the pipeline. As far as clean-up goes, for compiled cmdlets, we call Dispose on the cmdlet which allows for clean-up. For scripts, we don't expose Dispose in a useful way so perhaps we should add a "cleanup { }" block for functions scripts. (IIRC our thinking wrt scripts was that scripts call cmdlets and cmdlets get disposed therefore most things in a script will be disposed. Things that don't get disposed that way will eventually be disposed by the garbage collector/finalizer q.e.d there was no need for a cleanup block.)

  2. SteveL-MSFT commented on Apr 18, 2018

    @SteveL-MSFT
    MemberAuthor

    Seems reasonable

  3. dragonwolf83 commented on Apr 18, 2018

    @dragonwolf83

    I don't like the idea of waiting on garbage collection to close a database connection. There is a need for a Cleanup {} or Finally {} block for the exact scenario outlined.

    I wrote an "advanced function" that opens a DataReader connection in the Begin {} block so that it could pass the record to other cmdlets to do stuff. I could never figure out how to properly close it if a terminating error happened anywhere in the pipeline. Adding a new block would solve that problem.

  4. iSazonov commented on Apr 19, 2018

    @iSazonov
    Collaborator

    Interesting how cmdlet dispose local variables? We could add a script property (or something like that) with code to mandatory execute a dispose code.

  5. SteveL-MSFT commented on Apr 19, 2018

    @SteveL-MSFT
    MemberAuthor

    Reusing this issue to consider having a Finally{} type block for cleanup

  6. changed the title [-]EndProcessing is not called if exception is thrown in pipeline[/-] [+]Add new `finally {}` type block so script cmdlets have opportunity to cleanup[/+] on Apr 19, 2018
  7. added
    WG-Language
    on Apr 19, 2018
  8. aetos382 commented on Apr 19, 2018

    @aetos382
    Contributor

    Please consider providing syntax like C# using block.

  9. PetSerAl commented on Apr 19, 2018

    @PetSerAl
    Contributor

    Ilya (@iSazonov)

    Interesting how cmdlet dispose local variables? We could add a script property (or something like that) with code to mandatory execute a dispose code.

    Compiled cmdlets can just implement IDisposable and PowerShell engine properly call it to do cleanup.

  10. iSazonov commented on Apr 19, 2018

    @iSazonov
    Collaborator

    I meant

    $con = OpenDatabase
    $con.SetDisposeScriptBlock( { $using:con.Close() } )
  11. BrucePay commented on Apr 20, 2018

    @BrucePay
    Collaborator

    aetos (@aetos382) This is a slightly different scenario where a resource internal to the command is opened in Begin, used in Process and then closed in End. A using-style statement isn't applicable since there are three separate blocks and you don't want to dispose the resource when a block completes, only when all blocks have completed. Now you could wrap each of the blocks in a try/catch statement

    try
    {
          ... do stuff with resource....
    }
    catch {
          ... close the resource
    }
    

    Note that you want to use catch instead of finally because you only want to close the resource if there's an exception. In the normal flow, the resource would be released in the end block.

    WRT the finally {} cmdlet block Steve Lee (@SteveL-MSFT), proposes, I expect that it would be run when the command is disposed by the pipeline processor. (Consequently, one might argue that it should be called Dispose instead of Finally. Another name might be trap { } in which case we would have to think about break and continue semantics.

  12. changed the title [-]Add new `finally {}` type block so script cmdlets have opportunity to cleanup[/-] [+]Add new `Dispose {}` type block so script cmdlets have opportunity to cleanup[/+] on Apr 20, 2018
  13. 49 remaining items

  14. iSazonov commented on May 13, 2020

    @iSazonov
    Collaborator

    The idea was expressed by Bruce Payette (@BrucePay), then in another form Jason Shirk (@lzybkr), then alx9r.
    I would not want to lose this idea and put it in PowerShell/PowerShell-RFC#250

  15. vexx32 commented on May 13, 2020

    @vexx32
    Collaborator

    Ilya (@iSazonov) appreciate the writeup!

    I had a bit of a read just a little bit ago, but it seems to me the concept is flawed from the beginning. Automatic resource management is effectively trying to predict what users want from the code, which IMO is never a great way to try to create a reliable experience for users.

    I'll add more detailed comments to the RFC itself.

  16. iSazonov commented on May 13, 2020

    @iSazonov
    Collaborator

    Rain Sallow (/u/ta11ow) (@vexx32) The RFC comes from the fact that I like when PowerShell makes smart things :-)

    it seems to me the concept is flawed from the beginning

    As joke - it seems to you :-) Do you really deny the garbage collector in C#?!

  17. vexx32 commented on May 13, 2020

    @vexx32
    Collaborator

    Not at all. But I think us attempting to re-create a garbage collector when there's already one available in .NET is a bit of wasted effort, frankly. Can we improve how we work with it? To a point, sure! But trying to do too much there is liable to create an incredibly confusing UX.

  18. iSazonov commented on May 13, 2020

    @iSazonov
    Collaborator

    We need to look script examples where it could be a problem.

  19. essentialexch commented on May 13, 2020

    @essentialexch

    There is nothing that says both of these cannot be done.

    I'd really (speaking as someone who prefers language to change slowly!!) prefer to not wait another year or two to have a dispose-type capability in PowerShell. It's an enormously powerful concept especially for network, database, and file-system (i.e., most) scripts that are long-running and robust.

    So I'd hate for Rain Sallow (/u/ta11ow) (@vexx32) 's implementation to get derailed by a similar-but-not-identical resource-tracking proposal from Ilya (@iSazonov) .

  20. SeeminglyScience commented on May 13, 2020

    @SeeminglyScience
    Contributor

    I don't necessarily see a problem with scope based disposal, but it's gotta be explicit. For instance, a nested/non-public function that creates a database connection for use in a larger function/module is gonna break.

  21. iSazonov commented on May 13, 2020

    @iSazonov
    Collaborator

    For instance, a nested/non-public function that creates a database connection for use in a larger function/module is gonna break.

    It is developer duty to make this correctly. If it is a module developer should set "DisposeKind.AtModuleUnload" for the connection object. Now consumer gets PowerShell magic - automatically closing the connection.
    I would not want us to dive into the implementation details - it is clear that this is not easy.

  22. vexx32 commented on May 13, 2020

    @vexx32
    Collaborator

    Yeah, I'm not sure I see a lot of value in making this a "magic" sort of implementation. If there is desire for that kind of functionality on module unload, authors can already register tasks for module unload. I wonder if we'd be perhaps better off making that functionality more easily accessible in general rather than for a specific targeted purpose you're suggesting..

  23. SeeminglyScience commented on May 13, 2020

    @SeeminglyScience
    Contributor

    It is developer duty to make this correctly. If it is a module developer should set "DisposeKind.AtModuleUnload" for the connection object. Now consumer gets PowerShell magic - automatically closing the connection.

    If I do this:

    $rs = & {
        $temp = [runspacefactory]::CreateRunspace()
        $temp.Open()
        $temp
    }

    How am I as a script writer supposed to know that $rs is now closed. Even as someone who would be well aware of the change, it would be incredibly difficult to troubleshoot.

    Plus, you can assign objects you don't own to variables:

    $currentRunspace = [runspace]::DefaultRunspace

    I would not want us to dive into the implementation details - it is clear that this is not easy.

    Yeah psuedo code is fine of course. To be clear though, if automatic disposal is opt-out then this would be an incredibly large breaking change.

  24. iSazonov commented on May 13, 2020

    @iSazonov
    Collaborator

    I believe PowerShell can be smart enough to understand that an object is published in pipeline and shouldn't be destroyed. Can? :-) It is mentioned in RFC too. In fact, we can come up with any scenario and find a way to get around it or vice versa to fix it.

  25. SeeminglyScience commented on May 13, 2020

    @SeeminglyScience
    Contributor

    I believe PowerShell can be smart enough to understand that an object is published in pipeline and shouldn't be destroyed.

    It's not going to be that easy, you'd need full escape analysis

    1. Saved to a property
    2. Passed as a method argument
    3. Saved to an array
    4. Passed as a command argument
    5. Saved to a parent scope

    Plus you'd have to intimately familiar with all of those restrictions, if not then troubleshooting why your object breaks in script A but works great in script B will be very difficult.

    I don't see why it has to be automatic. Adding another use to the using keyword for assignments ala using $b = [runspacefactory]::CreateRunspace() seems like the move to me. If you don't explicitly request disposal, waiting until it hits the finalizer is probably fine. If not, it's the developers duty to quickly mark the assignment with using.

  26. jborean93 commented on Feb 13, 2022

    @jborean93
    Collaborator

    I believe this was implemented with #15177, feel free to correct me if I'm wrong.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-DiscussionIssue-EnhancementResolution-FixedWG-Language

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions