-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlServerLab.Common.ps1
More file actions
269 lines (211 loc) · 7.09 KB
/
Copy pathSqlServerLab.Common.ps1
File metadata and controls
269 lines (211 loc) · 7.09 KB
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#Requires -Version 7.0
Set-StrictMode -Version Latest
$PSNativeCommandUseErrorActionPreference = $false
$script:RepositoryRoot = Split-Path -Parent $PSScriptRoot
$script:ComposeFile = Join-Path $script:RepositoryRoot 'docker-compose.yml'
$script:EnvironmentFile = Join-Path $script:RepositoryRoot '.env'
$script:SqlRoot = Join-Path $script:RepositoryRoot 'sql'
$script:SqlServerService = 'sqlserver'
$script:SqlCmdPath = '/opt/mssql-tools18/bin/sqlcmd'
function Invoke-DockerCommand {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string[]]$Arguments,
[switch]$CaptureOutput
)
Push-Location $script:RepositoryRoot
try {
if ($CaptureOutput) {
$output = @(& docker @Arguments 2>&1)
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
$details = $output -join [Environment]::NewLine
throw "Docker command failed with exit code $exitCode.`n$details"
}
return $output
}
& docker @Arguments
$exitCode = $LASTEXITCODE
if ($exitCode -ne 0) {
throw "Docker command failed with exit code ${exitCode}: docker $($Arguments -join ' ')"
}
}
finally {
Pop-Location
}
}
function Invoke-ComposeCommand {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string[]]$Arguments,
[switch]$CaptureOutput
)
$composeArguments = @(
'compose'
'--env-file', $script:EnvironmentFile
'-f', $script:ComposeFile
) + $Arguments
Invoke-DockerCommand -Arguments $composeArguments -CaptureOutput:$CaptureOutput
}
function Assert-DockerReady {
[CmdletBinding()]
param()
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
throw 'Docker CLI was not found in PATH.'
}
$serverVersion = Invoke-DockerCommand -Arguments @(
'version'
'--format', '{{.Server.Version}}'
) -CaptureOutput
if ([string]::IsNullOrWhiteSpace(($serverVersion -join '').Trim())) {
throw 'Docker Desktop is installed, but the Docker engine did not return a server version.'
}
Invoke-DockerCommand -Arguments @('compose', 'version') -CaptureOutput | Out-Null
}
function Get-DotEnvValue {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[string]$Name
)
$escapedName = [Regex]::Escape($Name)
$matchingLine = Get-Content -LiteralPath $Path |
Where-Object { $_ -match "^\s*$escapedName\s*=" } |
Select-Object -Last 1
if ($null -eq $matchingLine) {
return $null
}
$value = ($matchingLine -split '=', 2)[1].Trim()
if (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
) {
$value = $value.Substring(1, $value.Length - 2)
}
return $value
}
function Assert-LabConfiguration {
[CmdletBinding()]
param()
if (-not (Test-Path -LiteralPath $script:ComposeFile -PathType Leaf)) {
throw "Compose file not found: $script:ComposeFile"
}
if (-not (Test-Path -LiteralPath $script:EnvironmentFile -PathType Leaf)) {
throw "Local environment file not found: $script:EnvironmentFile`nCopy .env.example to .env and set a local SQL Server password."
}
$password = Get-DotEnvValue -Path $script:EnvironmentFile -Name 'MSSQL_SA_PASSWORD'
if ([string]::IsNullOrWhiteSpace($password)) {
throw 'MSSQL_SA_PASSWORD is missing or empty in .env.'
}
$rejectedPasswords = @(
'REPLACE_WITH_A_LOCAL_PASSWORD'
'ChangeThis_Strong_Password_2026!'
)
if ($password -in $rejectedPasswords) {
throw 'Replace the example MSSQL_SA_PASSWORD value in .env before starting the lab.'
}
$portText = Get-DotEnvValue -Path $script:EnvironmentFile -Name 'MSSQL_PORT'
if (-not [string]::IsNullOrWhiteSpace($portText)) {
$port = 0
if (-not [int]::TryParse($portText, [ref]$port) -or $port -lt 1 -or $port -gt 65535) {
throw "MSSQL_PORT must be an integer between 1 and 65535. Current value: $portText"
}
}
Invoke-ComposeCommand -Arguments @('config', '--quiet')
}
function Get-SqlServerContainerId {
[CmdletBinding()]
param()
$containerId = Invoke-ComposeCommand -Arguments @(
'ps'
'--all'
'--quiet'
$script:SqlServerService
) -CaptureOutput
return ($containerId -join '').Trim()
}
function Get-SqlServerContainerState {
[CmdletBinding()]
param()
$containerId = Get-SqlServerContainerId
if ([string]::IsNullOrWhiteSpace($containerId)) {
return 'not-created'
}
$state = Invoke-DockerCommand -Arguments @(
'inspect'
'--format', '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}'
$containerId
) -CaptureOutput
return ($state -join '').Trim()
}
function Wait-SqlServerHealthy {
[CmdletBinding()]
param(
[ValidateRange(30, 600)]
[int]$TimeoutSeconds = 180
)
$stopwatch = [Diagnostics.Stopwatch]::StartNew()
$lastState = $null
while ($stopwatch.Elapsed.TotalSeconds -lt $TimeoutSeconds) {
$currentState = Get-SqlServerContainerState
if ($currentState -ne $lastState) {
Write-Host "SQL Server container state: $currentState"
$lastState = $currentState
}
switch ($currentState) {
'healthy' {
return
}
'unhealthy' {
Invoke-ComposeCommand -Arguments @('logs', '--tail', '80', $script:SqlServerService)
throw 'SQL Server container reported an unhealthy state.'
}
'exited' {
Invoke-ComposeCommand -Arguments @('logs', '--tail', '80', $script:SqlServerService)
throw 'SQL Server container exited during startup.'
}
'dead' {
Invoke-ComposeCommand -Arguments @('logs', '--tail', '80', $script:SqlServerService)
throw 'SQL Server container entered a dead state.'
}
}
Start-Sleep -Seconds 3
}
Invoke-ComposeCommand -Arguments @('logs', '--tail', '80', $script:SqlServerService)
throw "SQL Server did not become healthy within $TimeoutSeconds seconds."
}
function Assert-SqlServerHealthy {
[CmdletBinding()]
param()
$state = Get-SqlServerContainerState
if ($state -ne 'healthy') {
throw "SQL Server container is not healthy. Current state: $state"
}
}
function Invoke-ContainerSqlCmd {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string[]]$SqlCmdArguments
)
$shellCommand = 'export SQLCMDPASSWORD="$MSSQL_SA_PASSWORD"; exec {0} "$@"' -f $script:SqlCmdPath
$arguments = @(
'exec'
'-T'
$script:SqlServerService
'/bin/bash'
'-lc'
$shellCommand
'--'
'-S', 'localhost'
'-U', 'sa'
'-C'
'-b'
'-r1'
) + $SqlCmdArguments
Invoke-ComposeCommand -Arguments $arguments
}