summaryrefslogtreecommitdiffstats
path: root/qa/workunits/windows/libvirt_vm/utils.ps1
blob: f29ab79f5b37926033b6fe58e92f6f6d0f224e7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
function Invoke-CommandLine {
    Param(
        [Parameter(Mandatory=$true)]
        [String]$Command,
        [String]$Arguments,
        [Int[]]$AllowedExitCodes=@(0)
    )
    & $Command $Arguments.Split(" ")
    if($LASTEXITCODE -notin $AllowedExitCodes) {
        Throw "$Command $Arguments returned a non zero exit code ${LASTEXITCODE}."
    }
}

function Start-ExecuteWithRetry {
    Param(
        [Parameter(Mandatory=$true)]
        [ScriptBlock]$ScriptBlock,
        [Int]$MaxRetryCount=10,
        [Int]$RetryInterval=3,
        [String]$RetryMessage,
        [Array]$ArgumentList=@()
    )
    $currentErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = "Continue"
    $retryCount = 0
    while ($true) {
        try {
            $res = Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $ArgumentList
            $ErrorActionPreference = $currentErrorActionPreference
            return $res
        } catch [System.Exception] {
            $retryCount++
            if ($retryCount -gt $MaxRetryCount) {
                $ErrorActionPreference = $currentErrorActionPreference
                Throw $_
            } else {
                $prefixMsg = "Retry(${retryCount}/${MaxRetryCount})"
                if($RetryMessage) {
                    Write-Host "${prefixMsg} - $RetryMessage"
                } elseif($_) {
                    Write-Host "${prefixMsg} - $($_.ToString())"
                }
                Start-Sleep $RetryInterval
            }
        }
    }
}

function Start-FileDownload {
    Param(
        [Parameter(Mandatory=$true)]
        [String]$URL,
        [Parameter(Mandatory=$true)]
        [String]$Destination,
        [Int]$RetryCount=10
    )
    Write-Output "Downloading $URL to $Destination"
    Start-ExecuteWithRetry `
        -ScriptBlock { Invoke-CommandLine -Command "curl.exe" -Arguments "-L -s -o $Destination $URL" } `
        -MaxRetryCount $RetryCount `
        -RetryMessage "Failed to download '${URL}'. Retrying"
    Write-Output "Successfully downloaded."
}

function Add-ToPathEnvVar {
    Param(
        [Parameter(Mandatory=$true)]
        [String[]]$Path,
        [Parameter(Mandatory=$false)]
        [ValidateSet([System.EnvironmentVariableTarget]::User, [System.EnvironmentVariableTarget]::Machine)]
        [System.EnvironmentVariableTarget]$Target=[System.EnvironmentVariableTarget]::Machine
    )
    $pathEnvVar = [Environment]::GetEnvironmentVariable("PATH", $Target).Split(';')
    $currentSessionPath = $env:PATH.Split(';')
    foreach($p in $Path) {
        if($p -notin $pathEnvVar) {
            $pathEnvVar += $p
        }
        if($p -notin $currentSessionPath) {
            $currentSessionPath += $p
        }
    }
    $env:PATH = $currentSessionPath -join ';'
    $newPathEnvVar = $pathEnvVar -join ';'
    [Environment]::SetEnvironmentVariable("PATH", $newPathEnvVar, $Target)
}

function Install-Tool {
    [CmdletBinding(DefaultParameterSetName = "URL")]
    Param(
        [Parameter(Mandatory=$true, ParameterSetName = "URL")]
        [String]$URL,
        [Parameter(Mandatory=$true, ParameterSetName = "LocalPath")]
        [String]$LocalPath,
        [Parameter(ParameterSetName = "URL")]
        [Parameter(ParameterSetName = "LocalPath")]
        [String[]]$Params=@(),
        [Parameter(ParameterSetName = "URL")]
        [Parameter(ParameterSetName = "LocalPath")]
        [Int[]]$AllowedExitCodes=@(0)
    )
    PROCESS {
        $installerPath = $LocalPath
        if($PSCmdlet.ParameterSetName -eq "URL") {
            $installerPath = Join-Path $env:TEMP $URL.Split('/')[-1]
            Start-FileDownload -URL $URL -Destination $installerPath
        }
        Write-Output "Installing ${installerPath}"
        $kwargs = @{
            "FilePath" = $installerPath
            "ArgumentList" = $Params
            "NoNewWindow" = $true
            "PassThru" = $true
            "Wait" = $true
        }
        if((Get-ChildItem $installerPath).Extension -eq '.msi') {
            $kwargs["FilePath"] = "msiexec.exe"
            $kwargs["ArgumentList"] = @("/i", $installerPath) + $Params
        }
        $p = Start-Process @kwargs
        if($p.ExitCode -notin $AllowedExitCodes) {
            Throw "Installation failed. Exit code: $($p.ExitCode)"
        }
        if($PSCmdlet.ParameterSetName -eq "URL") {
            Start-ExecuteWithRetry `
                -ScriptBlock { Remove-Item -Force -Path $installerPath -ErrorAction Stop } `
                -RetryMessage "Failed to remove ${installerPath}. Retrying"
        }
    }
}