-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathstart.ps1
More file actions
468 lines (441 loc) · 18.4 KB
/
Copy pathstart.ps1
File metadata and controls
468 lines (441 loc) · 18.4 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/usr/bin/env pwsh
# ----------------------------------------------------------------------------
# Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
#
# WSO2 LLC. licenses this file to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file except
# in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
$PRODUCT_NAME = "ThunderID"
$PRODUCT_NAME_LOWERCASE = $PRODUCT_NAME.ToLower()
$BINARY_NAME = $PRODUCT_NAME_LOWERCASE
# Check for PowerShell Version Compatibility
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-Host ""
Write-Host "================================================================" -ForegroundColor Red
Write-Host " [ERROR] UNSUPPORTED POWERSHELL VERSION" -ForegroundColor Red
Write-Host "================================================================" -ForegroundColor Red
Write-Host ""
Write-Host " You are currently running PowerShell $($PSVersionTable.PSVersion.ToString())" -ForegroundColor Yellow
Write-Host " $PRODUCT_NAME requires PowerShell 7 (Core) or later." -ForegroundColor Yellow
Write-Host ""
Write-Host " Please install the latest version from:"
Write-Host " https://github.com/PowerShell/PowerShell" -ForegroundColor Cyan
Write-Host ""
exit 1
}
$BACKEND_PORT = if ($env:BACKEND_PORT) { [int]$env:BACKEND_PORT } else { 8090 }
$DEBUG_PORT = if ($env:DEBUG_PORT) { [int]$env:DEBUG_PORT } else { 2345 }
$DEBUG_MODE = $false
$WITH_CONSENT = if ($env:WITH_CONSENT -eq 'false') { $false } else { $true }
$RESOURCES_FILE = ""
$ENV_FILE = ""
$BOOTSTRAP_MODE = $false
$BOOTSTRAP_AND_SERVE = $false
$BOOTSTRAP_EXTRA_ARGS = @()
$ADMIN_USERNAME_FLAG_SET = $false
$ADMIN_PASSWORD_FLAG_SET = $false
$script:bootstrapExitCode = 0
# Parse command line arguments
$i = 0
while ($i -lt $args.Count) {
switch ($args[$i]) {
'--debug' {
$DEBUG_MODE = $true
$i++
break
}
'--debug-port' {
$i++
if ($i -lt $args.Count) {
$DEBUG_PORT = [int]$args[$i]
$i++
}
else {
Write-Host "Missing value for --debug-port" -ForegroundColor Red
exit 1
}
break
}
'--port' {
$i++
if ($i -lt $args.Count) {
$BACKEND_PORT = [int]$args[$i]
$i++
}
else {
Write-Host "Missing value for --port" -ForegroundColor Red
exit 1
}
break
}
'--without-consent' {
$WITH_CONSENT = $false
$i++
break
}
'--bootstrap' {
# Run the in-process bootstrap one-shot (create default resources) instead
# of starting the long-running server, then exit.
$BOOTSTRAP_MODE = $true
$i++
break
}
'--bootstrap-and-serve' {
# Run the in-process bootstrap one-shot first, then start the long-running
# server (convenient for local/dev: seed once, then serve).
$BOOTSTRAP_AND_SERVE = $true
$i++
break
}
'--console-redirect-uris' {
$i++
if ($i -lt $args.Count) {
$BOOTSTRAP_EXTRA_ARGS += @('--console-redirect-uris', $args[$i])
$i++
}
else {
Write-Host "Missing value for --console-redirect-uris" -ForegroundColor Red
exit 1
}
break
}
'--admin-username' {
$i++
if ($i -lt $args.Count) {
$BOOTSTRAP_EXTRA_ARGS += @('--admin-username', $args[$i])
$ADMIN_USERNAME_FLAG_SET = $true
$i++
}
else {
Write-Host "Missing value for --admin-username" -ForegroundColor Red
exit 1
}
break
}
'--admin-password' {
$i++
if ($i -lt $args.Count) {
$BOOTSTRAP_EXTRA_ARGS += @('--admin-password', $args[$i])
$ADMIN_PASSWORD_FLAG_SET = $true
$i++
}
else {
Write-Host "Missing value for --admin-password" -ForegroundColor Red
exit 1
}
break
}
'--env' {
$i++
if ($i -lt $args.Count) {
$ENV_FILE = $args[$i]
$i++
}
else {
Write-Host "Missing value for --env" -ForegroundColor Red
exit 1
}
break
}
'--help' {
Write-Host "$PRODUCT_NAME Server Startup Script"
Write-Host ""
Write-Host "Usage: .\start.ps1 [resources_file] [options]"
Write-Host ""
Write-Host "Arguments:"
Write-Host " resources_file Path to exported resources YAML file (optional)"
Write-Host ""
Write-Host "Options:"
Write-Host " --env FILE Path to env file with KEY=VALUE variables"
Write-Host " --debug Enable debug mode with remote debugging"
Write-Host " --port PORT Set application port (default: 8090)"
Write-Host " --debug-port PORT Set debug port (default: 2345)"
Write-Host " --without-consent Disable the bundled consent server"
Write-Host " --bootstrap Create default resources in-process, then exit (used by setup.ps1)"
Write-Host " --bootstrap-and-serve Create default resources in-process, then start the server"
Write-Host " --admin-username VALUE Username for the default admin user (--bootstrap-and-serve only)"
Write-Host " Optional; falls back to ADMIN_USERNAME env var, then defaults to 'admin'"
Write-Host " --admin-password VALUE Password for the default admin user (--bootstrap-and-serve only)"
Write-Host " Falls back to ADMIN_PASSWORD env var; bootstrap fails if neither is set"
Write-Host " --help Show this help message"
Write-Host ""
Write-Host "First-Time Setup:"
Write-Host " For initial setup, use the setup script:"
Write-Host " .\setup.ps1"
Write-Host ""
Write-Host " Then start the server normally:"
Write-Host " .\start.ps1"
Write-Host ""
Write-Host "Examples:"
Write-Host " .\start.ps1 Start server normally"
Write-Host " .\start.ps1 --debug Start in debug mode"
Write-Host " .\start.ps1 --port 9090 Start on custom port"
Write-Host " .\start.ps1 cloud.yml --env my.env Start with exported resources and env"
exit 0
}
default {
if (-not $args[$i].StartsWith('-') -and $RESOURCES_FILE -eq "") {
$RESOURCES_FILE = $args[$i]
$i++
}
else {
Write-Host "Unknown option: $($args[$i])" -ForegroundColor Yellow
Write-Host "Use --help for usage information"
exit 1
}
}
}
}
# --admin-username/--admin-password only make sense when bootstrapping happens in this
# invocation, and specifically only for --bootstrap-and-serve — --bootstrap is the
# seed-only mode setup.ps1 drives internally via environment variables, not flags.
if (($ADMIN_USERNAME_FLAG_SET -or $ADMIN_PASSWORD_FLAG_SET) -and -not $BOOTSTRAP_AND_SERVE) {
Write-Host "Error: --admin-username/--admin-password are only valid together with --bootstrap-and-serve" -ForegroundColor Red
exit 1
}
# Resolve relative paths to absolute.
if ($RESOURCES_FILE -ne "" -and -not [System.IO.Path]::IsPathRooted($RESOURCES_FILE)) {
$RESOURCES_FILE = Join-Path (Get-Location).Path $RESOURCES_FILE
}
if ($ENV_FILE -ne "" -and -not [System.IO.Path]::IsPathRooted($ENV_FILE)) {
$ENV_FILE = Join-Path (Get-Location).Path $ENV_FILE
}
# Exit on any error
$ErrorActionPreference = 'Stop'
# Load and export env vars from the env file.
function Load-EnvFile {
if ($ENV_FILE -eq "") { return }
if (-not (Test-Path $ENV_FILE)) {
Write-Host "Error: env file not found: $ENV_FILE" -ForegroundColor Red
exit 1
}
Write-Host "Loading environment from $ENV_FILE ..."
Get-Content $ENV_FILE | ForEach-Object {
$line = $_.TrimEnd()
if ($line -eq "" -or $line.StartsWith('#')) { return }
if ($line -match '^([A-Za-z_][A-Za-z0-9_]*)=(.*)$') {
$key = $Matches[1]
$value = $Matches[2]
if ($value -match '^\[') {
# JSON array — expand into KEY_0, KEY_1, ...
try {
$arr = $value | ConvertFrom-Json
$idx = 0
foreach ($elem in $arr) {
[System.Environment]::SetEnvironmentVariable("${key}_${idx}", $elem, 'Process')
$idx++
}
} catch {
Write-Error "Failed to parse JSON array for key '$key': $_"
exit 1
}
} else {
[System.Environment]::SetEnvironmentVariable($key, $value, 'Process')
}
}
}
}
# Load env vars before starting the binary so substitution works in resource files.
if ($ENV_FILE -ne "") {
Load-EnvFile
}
function Stop-PortListener {
param (
[int]$port
)
Write-Host "Checking for processes listening on TCP port $port..."
# Try Get-NetTCPConnection first (Windows 8/Server 2012+)
try {
$pids = Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction Stop | Select-Object -ExpandProperty OwningProcess -Unique
}
catch {
# Fallback to netstat parsing
$pids = @()
try {
$netstat = & netstat -ano 2>$null | Select-String ":$port"
foreach ($line in $netstat) {
$parts = ($line -split '\s+') | Where-Object { $_ -ne '' }
if ($parts.Count -ge 5) {
$procId = $parts[-1]
if ([int]::TryParse($procId, [ref]$null)) { $pids += [int]$procId }
}
}
}
catch { }
}
$pids = $pids | Where-Object { $_ -and ($_ -ne 0) } | Select-Object -Unique
foreach ($procId in $pids) {
try {
Write-Host "Killing PID $procId that is listening on port $port"
Stop-Process -Id $procId -Force -ErrorAction SilentlyContinue
}
catch {
Write-Host "Unable to kill PID $procId : $_" -ForegroundColor Yellow
}
}
}
# Kill ports before binding. The bootstrap one-shot does not bind the server port,
# so the check is skipped in that mode.
if (-not $BOOTSTRAP_MODE) {
Stop-PortListener -port $BACKEND_PORT
if ($DEBUG_MODE) { Stop-PortListener -port $DEBUG_PORT }
Start-Sleep -Seconds 1
}
# Check if Delve is available for debug mode
if ($DEBUG_MODE) {
if (-not (Get-Command dlv -ErrorAction SilentlyContinue)) {
Write-Host "[ERROR] Debug mode requires Delve debugger" -ForegroundColor Red
Write-Host ""
Write-Host "[INFO] Install Delve using:" -ForegroundColor Cyan
Write-Host " go install github.com/go-delve/delve/cmd/dlv@latest" -ForegroundColor Cyan
Write-Host ""
Write-Host "[INFO] Add Delve to PATH and re-run this script with --debug" -ForegroundColor Cyan
exit 1
}
}
# Resolve the server executable path
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$possible = @(
(Join-Path $scriptDir "${BINARY_NAME}.exe"),
(Join-Path $scriptDir $BINARY_NAME)
)
$serverExecPath = $possible | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $serverExecPath) {
# Fallback (will work if PATH or current dir has it)
$serverExecPath = Join-Path $scriptDir $BINARY_NAME
}
$proc = $null
try {
# Start consent server if enabled
$consentProc = $null
if ($WITH_CONSENT) {
$consentDir = Join-Path $scriptDir "consent"
if (-not (Test-Path $consentDir)) {
Write-Host "[ERROR] Consent server is enabled but consent directory not found: $consentDir" -ForegroundColor Red
exit 1
}
$consentBinary = @(
(Join-Path $consentDir 'consent-server.exe'),
(Join-Path $consentDir 'consent-server')
) | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $consentBinary) {
Write-Host "[ERROR] Consent server is enabled but consent-server binary not found in: $consentDir" -ForegroundColor Red
exit 1
}
Write-Host "[INFO] Starting Consent Server..."
$consentPort = if ($env:CONSENT_SERVER_PORT) { $env:CONSENT_SERVER_PORT } else { "9090" }
$consentProc = Start-Process -FilePath $consentBinary -WorkingDirectory $consentDir -NoNewWindow -PassThru
$consentTimeout = 30
$consentElapsed = 0
while ($consentElapsed -lt $consentTimeout) {
if ($consentProc.HasExited) {
Write-Host "[ERROR] Consent server process exited unexpectedly (code $($consentProc.ExitCode))" -ForegroundColor Red
exit 1
}
try {
$resp = Invoke-WebRequest -Uri "http://localhost:${consentPort}/health/readiness" -UseBasicParsing -ErrorAction Stop
if ($resp.StatusCode -eq 200) {
Write-Host "[INFO] Consent server is ready"
break
}
} catch { }
Start-Sleep -Seconds 1
$consentElapsed++
}
if ($consentElapsed -ge $consentTimeout) {
Write-Host "[ERROR] Consent server failed to become ready within ${consentTimeout}s" -ForegroundColor Red
exit 1
}
}
# Bootstrap: create the default resources in-process. Runs for both --bootstrap
# (seed-only) and --bootstrap-and-serve. The consent server started above (if
# enabled) stays up for the bootstrap — and, in bootstrap-and-serve mode, for the
# server too. It is stopped by the finally block.
$runServer = (-not $BOOTSTRAP_MODE)
if ($BOOTSTRAP_MODE -or $BOOTSTRAP_AND_SERVE) {
Write-Host "[INFO] Running $PRODUCT_NAME bootstrap ..."
$env:BACKEND_PORT = $BACKEND_PORT
$bootstrapArgs = @('bootstrap') + $BOOTSTRAP_EXTRA_ARGS
$bp = Start-Process -FilePath $serverExecPath -ArgumentList $bootstrapArgs -WorkingDirectory $scriptDir -NoNewWindow -PassThru -Wait
$script:bootstrapExitCode = $bp.ExitCode
if ($bp.ExitCode -eq 0) {
Write-Host "[INFO] Bootstrap completed."
}
else {
Write-Host "[ERROR] Bootstrap failed." -ForegroundColor Red
$runServer = $false
}
}
if ($runServer) {
$resourcesArgs = @()
if ($RESOURCES_FILE -ne "") { $resourcesArgs = @('-resources', $RESOURCES_FILE) }
if ($DEBUG_MODE) {
Write-Host "[INFO] Starting $PRODUCT_NAME Server in DEBUG mode..."
Write-Host "[INFO] Application will run on: https://localhost:$BACKEND_PORT"
Write-Host "[INFO] Remote debugger will listen on: localhost:$DEBUG_PORT"
Write-Host ""
Write-Host "[INFO] Connect using remote debugging configuration:" -ForegroundColor Gray
Write-Host " Host: 127.0.0.1, Port: $DEBUG_PORT" -ForegroundColor Gray
Write-Host ""
# Export BACKEND_PORT for the child process (mirrors the non-debug branch)
$env:BACKEND_PORT = $BACKEND_PORT
# Start Delve in headless mode
$dlvArgs = @(
'exec'
"--listen=:$DEBUG_PORT"
'--headless=true'
'--api-version=2'
'--accept-multiclient'
'--continue'
$serverExecPath
'--'
) + $resourcesArgs
$proc = Start-Process -FilePath dlv -ArgumentList $dlvArgs -WorkingDirectory $scriptDir -NoNewWindow -PassThru
}
else {
Write-Host "[INFO] Starting $PRODUCT_NAME Server ..."
# Export BACKEND_PORT for the child process
$env:BACKEND_PORT = $BACKEND_PORT
$proc = Start-Process -FilePath $serverExecPath -ArgumentList $resourcesArgs -WorkingDirectory $scriptDir -NoNewWindow -PassThru
}
Write-Host ""
Write-Host "[INFO] Server running. PID: $($proc.Id)"
Write-Host ""
Write-Host "[INFO] Frontend Apps:"
Write-Host " [GATE] Gate (Login/Register): https://localhost:$BACKEND_PORT/gate"
Write-Host " [DEV] Console (System Management): https://localhost:$BACKEND_PORT/console"
Write-Host ""
Write-Host "Press Ctrl+C to stop the server."
# Wait for the background process. This will block until the process exits.
Wait-Process -Id $proc.Id
}
}
finally {
Write-Host "`n[STOP] Stopping server..."
if ($proc -and -not $proc.HasExited) {
try { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } catch { }
}
if ($consentProc -and -not $consentProc.HasExited) {
try {
# Stop child processes first (the consent-server binary started by start.ps1)
Get-CimInstance Win32_Process -Filter "ParentProcessId = $($consentProc.Id)" -ErrorAction SilentlyContinue |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Stop-Process -Id $consentProc.Id -Force -ErrorAction SilentlyContinue
} catch { }
}
}
# Propagate a failed bootstrap (seed-only or bootstrap-and-serve), then exit cleanly
# after a seed-only run.
if ($script:bootstrapExitCode -ne 0) { exit $script:bootstrapExitCode }
if ($BOOTSTRAP_MODE) { exit 0 }