# JJ Ollama Manager (Windows) — src/platform/windows/04_server.ps1 : 서버 관리 (기동 / 종료 / 재시작) # jj_ollama_manager.ps1 가 순서대로 불러옵니다 (직접 실행하지 않음). 원래 jj_ollama_manager.ps1 1309~1694줄 # 대화 전에 모델을 메모리에 미리 올리고 진행 상황 표시 # (첫 답변이 한참 안 나와 멈춘 것처럼 보이는 현상 방지) function Invoke-Preload([string]$RunTag) { $lm = Find-LoadedModel $RunTag @(Get-LoadedModels) if ($lm) { Write-C "${GREEN}✅ 이미 메모리에 올라가 있습니다 $(Format-LoadedTag $lm)${RESET}" return } Write-C "${CYAN}모델을 메모리에 올리는 중입니다... (큰 모델은 처음에 수십 초~몇 분 걸립니다)${RESET}" try { Add-Type -AssemblyName System.Net.Http -ErrorAction Stop $client = New-Object System.Net.Http.HttpClient $client.Timeout = [TimeSpan]::FromMinutes(30) $body = @{ model = $RunTag; prompt = '' } | ConvertTo-Json -Compress $content = New-Object System.Net.Http.StringContent($body, [Text.Encoding]::UTF8, 'application/json') $task = $client.PostAsync("$ApiUrl/api/generate", $content) } catch { Write-C "${YELLOW}미리 올리기를 시작하지 못했습니다. 대화를 시작하면 그때 올라갑니다.${RESET}" return } $sw = [Diagnostics.Stopwatch]::StartNew() $spin = @('|', '/', '-', '\') $i = 0 while (-not $task.IsCompleted) { $s = [int]$sw.Elapsed.TotalSeconds Write-Host -NoNewline ("`r {0} 적재 중... {1}초 경과 · Ollama 메모리 {2}GB " -f $spin[$i % 4], $s, (Get-OllamaMemGB)) $i++ [void]$task.Wait(1000) } Write-Host '' $sec = [int]$sw.Elapsed.TotalSeconds $errText = '' if ($task.IsFaulted -or $task.IsCanceled) { $errText = '응답 없음' } else { $resp = $task.Result $txt = '' try { $txt = $resp.Content.ReadAsStringAsync().Result } catch { } if (-not $resp.IsSuccessStatusCode -or $txt -match '"error"') { $errText = $txt if ($txt -match '"error"\s*:\s*"([^"]+)"') { $errText = $Matches[1] } } } $client.Dispose() if ($errText) { Write-C "${RED}❌ 메모리에 올리지 못했습니다: $errText${RESET}" Write-C "${YELLOW} 메모리가 부족하면 다른 모델을 내리거나 더 작은 태그를 써 보세요. (대화는 그대로 시도합니다)${RESET}" return } $lm = Find-LoadedModel $RunTag @(Get-LoadedModels) Write-C "${GREEN}✅ 적재 완료 (${sec}초) $(Format-LoadedTag $lm)${RESET}" } # 메모리에서 내리기 (원본·-ko 이름 모두) function Stop-LoadedModel([string]$Tag) { $base = Get-FullTag $Tag if (Test-KoVariant $base) { $base = $base.Substring(0, $base.Length - $KoSuffix.Length) } $names = @($base, "$base$KoSuffix") $hits = @(Get-LoadedModels | Where-Object { $names -contains (Get-FullTag $_.Name) }) if ($hits.Count -eq 0) { Write-C "${GRAY}'$base'은 메모리에 올라가 있지 않습니다.${RESET}"; return } $freed = 0 foreach ($h in $hits) { Write-C "${CYAN}'$($h.Name)'을 메모리에서 내리는 중...${RESET}" & $script:OllamaExe stop $h.Name 2>&1 | Out-Host $freed += [double]$h.SizeGB } Start-Sleep -Milliseconds 500 if (Find-LoadedModel $base @(Get-LoadedModels)) { Write-C "${YELLOW}아직 내려가는 중입니다. 잠시 후 첫 화면에서 다시 확인해 주세요.${RESET}" } else { Write-C "${GREEN}✅ 메모리에서 내렸습니다. (약 ${freed}GB 비움)${RESET}" } } # API 연결 (전체, 외부) function Get-ApiConnections { $c = @(Get-NetTCPConnection -LocalPort $ApiPort -State Established -ErrorAction SilentlyContinue) $ext = @($c | Where-Object { $_.RemoteAddress -notin @('127.0.0.1', '::1') } | ForEach-Object { $_.RemoteAddress } | Sort-Object -Unique) return [pscustomobject]@{ Total = $c.Count; External = @($c | Where-Object { $_.RemoteAddress -notin @('127.0.0.1', '::1') }).Count; Ips = ($ext -join ',') } } # Ollama 프로세스 메모리 합계(GB) function Get-OllamaMemGB { $p = @(Get-Process -Name 'ollama', 'ollama app', 'ollama_llama_server' -ErrorAction SilentlyContinue) if ($p.Count -eq 0) { return 0 } return [math]::Round((($p | Measure-Object -Property WorkingSet64 -Sum).Sum) / 1GB, 1) } # 최근 경고·오류 로그 function Get-RecentErrors([int]$Count = 2) { $f = Get-CurrentLogFile $lines = Read-LogTail $f $hit = @($lines | Where-Object { $_ -match '(?i)level=(ERROR|WARN)|panic|error:' } | Select-Object -Last $Count) return @($hit | ForEach-Object { if ($_.Length -gt 150) { $_.Substring(0, 150) } else { $_ } }) } # 모니터링 문구 # 메뉴 위쪽 상태 정보: 제목 줄 + 모니터링 (메인 메뉴와 모든 하위 메뉴 공통) function Get-StatusBlock { $title = "${BLUE}${BOLD}Windows Ollama 관리 시스템${RESET} ${GRAY}$(Get-Date -Format 'HH:mm:ss') 기준 · $(Get-HwSummary)${RESET}" return "$title`n$(Get-MonitorText)" } function Get-MonitorText([switch]$Full) { $L = New-Object System.Collections.Generic.List[string] # 서버 if (Test-Server) { $si = Get-ServerInfo $ver = '?' try { $ver = (Invoke-RestMethod -Uri "$ApiUrl/api/version" -TimeoutSec 2 -ErrorAction Stop).version } catch { } $up = '?' if ($si.StartTime) { $up = Format-Uptime ((Get-Date) - $si.StartTime) } $ctx = '기본값(스크립트 설정 미적용)' if ($si.Owner -eq '스크립트') { $c = Get-ServerCtx; if ($c) { $ctx = "$c" } else { $ctx = '?' } } $L.Add("${BOLD}서버${RESET} ${GREEN}● 실행 중${RESET} v$ver · PID $($si.ProcId) · 가동 $up · 기동: $($si.Owner)") $L.Add(" 주소 $($si.Bind) · 컨텍스트 $ctx") # 메모리에 올라간 모델 $loaded = @(Get-LoadedModels) if ($loaded.Count -eq 0) { $L.Add("${BOLD}모델${RESET} ${GRAY}메모리에 올라간 모델 없음${RESET}") } else { $first = $true foreach ($m in $loaded) { if ($m.Gpu -ge 100) { $where = 'GPU 100%' } elseif ($m.Gpu -le 0) { $where = 'CPU 100%' } else { $where = "CPU $(100 - $m.Gpu)%/GPU $($m.Gpu)%" } $remain = '' if ($m.Remain -eq 'inf') { $remain = ' · 계속 유지' } elseif ("$($m.Remain)" -ne '') { $remain = " · $($m.Remain)분 후 내림" } $cx = '' if ($m.Ctx) { $cx = " · 컨텍스트 $($m.Ctx)" } $prefix = ' ' if ($first) { $prefix = "${BOLD}모델${RESET} "; $first = $false } $L.Add("$prefix${CYAN}$($m.Name)${RESET} $($m.SizeGB)GB · $where$remain$cx") } } } else { $L.Add("${BOLD}서버${RESET} ${RED}● 중지됨${RESET} ${GRAY}('서버 기동'으로 켤 수 있습니다)${RESET}") $L.Add("${BOLD}모델${RESET} ${GRAY}메모리에 올라간 모델 없음${RESET}") } # 시스템 자원 $cpu = Get-CpuPercent $ram = Get-RamInfo $ramText = '?' if ($ram) { $ramText = "$($ram.UsedGB)/$($ram.TotalGB)GB ($($ram.Pct)%)" } $L.Add("${BOLD}자원${RESET} CPU $cpu% ($($script:HW.Threads)스레드) · 램 $ramText · Ollama $(Get-OllamaMemGB)GB · 디스크 남음 $(Get-FreeDiskGB)GB") # 모델 저장 위치 foreach ($sl in (Get-StorageLines)) { $L.Add($sl) } # 그래픽 카드 $gpus = @(Get-GpuUsage) if ($gpus.Count -eq 0) { $L.Add("${BOLD}GPU${RESET} ${GRAY}사용량 정보 없음 ($($script:HW.MainGpu))${RESET}") } else { $first = $true foreach ($g in $gpus) { $t = "$($g.Name): 사용률 $($g.Util)%" if ($g.TotalGB -gt 0) { $t += " · VRAM $($g.UsedGB)/$($g.TotalGB)GB" } else { $t += " · VRAM $($g.UsedGB)GB 사용" } if ($g.Temp) { $t += " · $($g.Temp)°C" } $prefix = ' ' if ($first) { $prefix = "${BOLD}GPU${RESET} "; $first = $false } $L.Add("$prefix$t") } } # 연결 $clients = @(Get-ActiveClients) $conn = Get-ApiConnections $ips = '' if ($conn.Ips) { $ips = ": $($conn.Ips)" } $L.Add("${BOLD}연결${RESET} 대화·도구 연동 $($clients.Count)개 · API 연결 $($conn.Total)개 (외부 $($conn.External)개$ips)") if ($Full) { foreach ($c in $clients) { $cmd = ($c.CommandLine -replace '^"[^"]*"\s*|^\S+\s*', 'ollama ') $L.Add((" PID {0,-7} {1}" -f $c.ProcessId, $cmd)) } } # Open WebUI (Podman) foreach ($wl in (Get-WebuiMonitorLines -Full:$Full)) { $L.Add($wl) } # ComfyUI (Podman) foreach ($cl in (Get-ComfyMonitorLines -Full:$Full)) { $L.Add($cl) } # 로그 $n = 1 if ($Full) { $n = 5 } $errs = @(Get-RecentErrors $n) if ($errs.Count -eq 0) { $L.Add("${BOLD}로그${RESET} ${GREEN}최근 경고·오류 없음${RESET}") } else { $first = $true foreach ($e in $errs) { $prefix = ' ' if ($first) { $prefix = "${BOLD}로그${RESET} "; $first = $false } $L.Add("$prefix${YELLOW}$e${RESET}") } } return ($L -join "`n") } # -------------------------------------------------- # 서버 관리 (기동 / 종료 / 재시작) # -------------------------------------------------- # 서버 쪽 프로세스만 종료 # (ollama 프로세스를 전부 종료하면 다른 창의 'ollama run' 대화까지 끊기므로 serve/runner만 골라 종료) function Stop-ServerProcesses { # 트레이 앱이 서버를 다시 띄우지 않도록 먼저 종료 Get-Process -Name 'ollama app' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue if (Test-Path $PidFile) { $savedPid = Get-Content $PidFile -ErrorAction SilentlyContinue | Select-Object -First 1 if ($savedPid) { Stop-Process -Id ([int]$savedPid) -Force -ErrorAction SilentlyContinue } Remove-Item $PidFile -Force -ErrorAction SilentlyContinue } foreach ($p in (Get-OllamaProcesses)) { if ($p.CommandLine -match '\s(serve|runner)(\s|$)') { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } } Get-Process -Name 'ollama_llama_server' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue Remove-Item $CtxFile -Force -ErrorAction SilentlyContinue } # 서버 쪽 프로세스가 남아 있는지 function Test-ServerProcesses { if (Get-Process -Name 'ollama app' -ErrorAction SilentlyContinue) { return $true } return (@(Get-OllamaProcesses | Where-Object { $_.CommandLine -match '\s(serve|runner)(\s|$)' }).Count -gt 0) } # 사용 중인 대화가 있으면 경고하고 계속할지 확인 function Confirm-NoActiveClients([string]$Action) { $clients = Get-ActiveClients if ($clients.Count -eq 0) { return $true } Write-C "${YELLOW}`n⚠️ 다른 창에서 아래 모델 대화/도구 연동이 실행 중입니다.${RESET}" foreach ($c in $clients) { $cmd = ($c.CommandLine -replace '^"[^"]*"\s*|^\S+\s*', 'ollama ') Write-C (" PID {0,-7} {1}" -f $c.ProcessId, $cmd) } Write-C "${YELLOW}서버를 ${Action}하면 위 대화의 연결이 끊깁니다.${RESET}`n" if (Confirm-Choice "그래도 서버를 ${Action}할까요?") { return $true } Write-C "${YELLOW}취소했습니다.${RESET}" return $false } # 서버 프로세스를 실제로 띄움 (기존 서버 확인·종료는 하지 않음) function Invoke-ServerLaunch([int]$Ctx = 0) { $p = $script:Perf if ($Ctx -le 0) { $Ctx = $p.ContextLength } Write-C "${GREEN}[1/2] 외부 접속 허용(${OllamaBind}) 환경으로 서버를 백그라운드에서 기동합니다...${RESET}" Write-C "${CYAN} 성능 설정: 컨텍스트 $Ctx, 동시 적재 모델 $($p.MaxLoaded)개, 유지 $($p.KeepAlive), KV 캐시 $($p.KvCacheType)${RESET}" # 서버 프로세스에만 넘길 환경 변수 설정 $env:OLLAMA_HOST = $OllamaBind $env:OLLAMA_NUM_PARALLEL = "$($p.NumParallel)" $env:OLLAMA_MAX_LOADED_MODELS = "$($p.MaxLoaded)" $env:OLLAMA_KEEP_ALIVE = $p.KeepAlive $env:OLLAMA_CONTEXT_LENGTH = "$Ctx" $env:OLLAMA_FLASH_ATTENTION = "$($p.FlashAttention)" $env:OLLAMA_KV_CACHE_TYPE = $p.KvCacheType if ($script:HW -and $script:HW.ForceCpu) { # GPU를 쓰지 않도록 CUDA 장치를 숨김 (VRAM이 작은 NVIDIA GPU에서 CUDA 오류 방지) $env:CUDA_VISIBLE_DEVICES = '-1' Write-C "${CYAN} GPU 끔: $($script:HW.AccelNote)${RESET}" } $proc = $null try { $proc = Start-Process -FilePath $script:OllamaExe -ArgumentList 'serve' -WindowStyle Hidden ` -RedirectStandardError $LogFile -RedirectStandardOutput $OutLogFile -PassThru -ErrorAction Stop Set-Content -Path $PidFile -Value $proc.Id Set-Content -Path $CtxFile -Value $Ctx } catch { Write-C "${RED}❌ 서버를 기동하지 못했습니다: $($_.Exception.Message)${RESET}" $env:OLLAMA_HOST = "127.0.0.1:$ApiPort" return $false } # 이 창의 클라이언트는 다시 로컬 주소로 $env:OLLAMA_HOST = "127.0.0.1:$ApiPort" Write-C "${GREEN}[2/2] 서버 응답을 기다립니다...${RESET}" for ($i = 0; $i -lt 20; $i++) { if (Test-Server) { Write-C "${GREEN}✅ 서버가 기동되었습니다. (PID: $($proc.Id))${RESET}" Write-C "${CYAN}로그 파일: ${LogFile}${RESET}" Write-C "${GRAY}처음 외부 접속을 허용하면 Windows 방화벽 허용 창이 뜰 수 있습니다.${RESET}" return $true } if ($proc.HasExited) { Write-C "${RED}❌ 서버 프로세스가 바로 종료되었습니다. 최근 로그:${RESET}" Read-LogTail $LogFile 4096 | Select-Object -Last 8 | ForEach-Object { Write-Host $_ } Remove-Item $PidFile, $CtxFile -Force -ErrorAction SilentlyContinue return $false } Start-Sleep -Seconds 1 } Write-C "${RED}❌ 20초 안에 서버가 응답하지 않았습니다. 로그를 확인해 주세요: ${LogFile}${RESET}" return $false } # 서버 기동 (꺼져 있을 때만) function Start-OllamaServer { if (Test-Server) { $si = Get-ServerInfo Write-C "${GREEN}`n✅ 서버가 이미 실행 중입니다. (기동: $($si.Owner), PID $($si.ProcId))${RESET}" if ($si.Owner -ne '스크립트') { Write-C "${GRAY}이 서버에는 스크립트의 성능 설정(외부 접속·컨텍스트 등)이 적용되지 않았을 수 있습니다.${RESET}" Write-C "${GRAY}설정을 적용하려면 '서버 재시작'을 사용하세요.${RESET}" } return $true } if (@(Get-NetTCPConnection -LocalPort $ApiPort -State Listen -ErrorAction SilentlyContinue).Count -gt 0) { Write-C "${RED}`n❌ 포트 ${ApiPort}을(를) 다른 프로그램이 쓰고 있지만 응답하지 않습니다. '서버 종료' 후 다시 기동해 주세요.${RESET}" return $false } Write-C '' return (Invoke-ServerLaunch $script:Perf.ContextLength) } # 서버 종료 function Stop-OllamaServer { if (-not (Test-Server) -and -not (Test-ServerProcesses)) { Write-C "${GREEN}`n서버가 이미 종료되어 있습니다.${RESET}" Remove-Item $PidFile, $CtxFile -Force -ErrorAction SilentlyContinue return } if (-not (Confirm-NoActiveClients '종료')) { return } Write-C "${YELLOW}`nOllama 서버를 종료합니다...${RESET}" Stop-ServerProcesses for ($i = 0; $i -lt 10; $i++) { if (-not (Test-Server)) { break } Start-Sleep -Seconds 1 } if (Test-Server) { Write-C "${RED}❌ 서버가 아직 응답합니다. 작업 관리자에서 ollama 프로세스를 확인해 주세요.${RESET}" } else { Write-C "${GREEN}✅ 서버가 종료되었습니다.${RESET}" } } # 서버 재시작 function Restart-OllamaServer([int]$Ctx = 0) { if ($Ctx -le 0) { $Ctx = $script:Perf.ContextLength } $script:LanIpKnown = $false # 내부망 IP 새로 알아내기 if (Test-Server) { if (-not (Confirm-NoActiveClients '재시작')) { return $false } } Write-C "${YELLOW}`n[재시작] 기존 Ollama 서버(트레이 앱 포함)를 종료합니다...${RESET}" Stop-ServerProcesses for ($i = 0; $i -lt 10; $i++) { if (@(Get-NetTCPConnection -LocalPort $ApiPort -State Listen -ErrorAction SilentlyContinue).Count -eq 0) { break } Start-Sleep -Seconds 1 } return (Invoke-ServerLaunch $Ctx) } # 모델 실행 전 서버 확인 (꺼져 있으면 물어보고 기동) function Confirm-Server { if (Test-Server) { return $true } Write-C "${YELLOW}`n⚠️ Ollama 서버가 꺼져 있습니다.${RESET}" if (Confirm-Choice '지금 서버를 기동할까요?') { return (Invoke-ServerLaunch $script:Perf.ContextLength) } Write-C "${YELLOW}서버를 기동하지 않았습니다. 메인 메뉴에서 먼저 '서버 기동'을 선택해 주세요.${RESET}" return $false } # 서버 상태 상세 function Show-ServerStatus { Write-C "${BLUE}`n================ 서버 상태 상세 ================${RESET}" Write-Host (Get-MonitorText -Full) if (Test-Server) { Write-C "`n${CYAN}[메모리에 올라간 모델 - ollama ps] (PROCESSOR 열에서 GPU/CPU 사용 비율 확인)${RESET}" & $script:OllamaExe ps Write-C "`n${CYAN}[설치된 모델 - ollama list]${RESET}" & $script:OllamaExe list } Write-C "`n모델 폴더: $(Get-ModelsDir)" Write-C "로그 파일: $(Get-CurrentLogFile)" Write-C "${BLUE}================================================${RESET}" }