The lazy programmer scripts
scripts that work

Leader election (PowerShell) GitHub

This is a small script useful when multiple Jenkins parallel jobs try to acess the same shared resources, in order to decide for a leader. It is the simplest leader election possible, and it works as long as the sleep wait time is long enough for all the parallel jobs to converge to the same point.

The most important part is that the parallel workers do not need to establish quorum and communicate with each other.

The function is the most naive implementation of the consensus in a proof of work blockchain.

#ps1

function Is-Leader {
    param( $identifier )
    $guid = (New-Guid).Guid
    Write-Host "Guid for this worker is $guid"
    $basePath = "C:\\Windows\Temp\$windowsVersion"
    if (Test-Path $basePath) {
        # this means the leader has been previously elected
        return $false 
    }
    New-Item -Type Directory -Force $basePath | Out-Null
    New-Item -Type File -Force "${basePath}\${guid}" | Out-Null
    # the timeout needs to be long enough for all workers to be have started and got to the
    # above line
    Start-Sleep 10
    $bestGuid = (Get-ChildItem -Path $basePath | Sort-Object | Select-Object -First 1).Name
    Write-Host "BestGuid is: $bestGuid. Guid for this worker is: ${guid}"
    return $bestGuid -eq $guid
}

Is-Leader "unique-resource-name"

That's all, folks!

Written by kami on Friday June 9, 2023
Permalink -

Leave a comment

comments powered by Disqus

« Deploy Polygon (Matic) private RPC -