#пробег по всем файлам сессиий
foreach ($file in $lockFiles) {
#текущее время
$cStamp = Get-Date -UFormat "%s"
$cStamp = [double]::Parse($cStamp)
#время из файла
$fStamp = ($file.BaseName -split '_')[1]
$fStamp = $fStamp -replace "-",","
$fStamp = [double]::Parse($fStamp)
#вычисление разницы
[double]$difference = [math]::Round($($cStamp - $fStamp), 3)
#пометка просроченной сессии
$leaked = $difference -ge $stdTime
if ($file -match $pattern) {
if ($leaked) {
$old += $file #просроченные сессии
} else {
$active += $file #активные(соответствующие паттерну именования и не имеющие пометки leaked)
}
} else {
$nonformat += $file #файлы сессии с нестандартным именем(например старый формат именования(вдруг этот блок кода доживет до прода))
}
}
Write-Host "Активные: " -ForegroundColor Green
foreach ($file in $active) {
#имя арма из названия файла
$name = (($file.BaseName -replace '\.upload', '') -split '_')[2]
$content = Get-Content -Path $file.FullName | ConvertFrom-Json
#получение расчетного времени из файла блокировки
$calcTime = [double]::Parse($content.time)
$calcHours = [math]::Floor($calcTime / 3600)
$calcMinutes = [math]::Floor(($calcTime % 3600) / 60)
$calcSeconds = [math]::Floor($calcTime % 60)
$calcMmilliseconds = [math]::Round(($calcTime % 1) * 1000)
#получение текущего времени
$cStamp = Get-Date -UFormat "%s"
$cStamp = [double]::Parse($cStamp)
#получение из имени файла времени начала загрузки
$fStamp = ($file.BaseName -split '_')[1]
$fStamp = $fStamp -replace "-",","
$fStamp = [double]::Parse($fStamp)
$dateTime = [datetime]::new(1970, 1, 1, 0, 0, 0, [System.DateTimeKind]::Utc).AddSeconds($fStamp)
#расчет прошедшшего времени с округлением
[double]$passed = [math]::Round($($cStamp - $fStamp), 3)
$pHours = [math]::Floor($passed / 3600)
$pMinutes = [math]::Floor(($passed % 3600) / 60)
$pSeconds = [math]::Floor($passed % 60)
$pMmilliseconds = [math]::Round(($passed % 1) * 1000)
#расчет оставшегося времени с округлением
[double]$remain = [math]::Round($($calcTime - ($cStamp - $fStamp)), 3)
if ($remain -ge 0) {
$rHours = [math]::Floor($remain / 3600)
$rMinutes = [math]::Floor(($remain % 3600) / 60)
$rSeconds = [math]::Floor($remain % 60)
$rMmilliseconds = [math]::Round(($remain % 1) * 1000)
} else {
$rHours = 0
$rMinutes = 0
$rSeconds = 0
$rMmilliseconds = 0
}
#получение объема данных из файла блокировки
$content_size = ($content.size -replace '\.', ',')
$size = [double]::Parse($content_size)
$sMb = 0
$sGb = 0
if ($size -ge 1024){
$sGb = [math]::Floor($size / 1024)
$sMb = $size % 1024
} else { $sMb = $size }
Write-Host "АРМ - $name" -ForegroundColor Magenta
Write-Host "Дата и время начала сессии: $dateTime"
Write-Host "Требуемое время на загрузку: $calcHours час, $calcMinutes мин, $calcSeconds сек, $calcMmilliseconds миллисек"
Write-Host "Прошло - $pHours час, $pMinutes мин, $pSeconds сек, $pMmilliseconds миллисек"
Write-Host "Осталось - $rHours час, $rMinutes мин, $rSeconds сек, $rMmilliseconds миллисек"
Write-Host "Объем данных: $sGb гБ, $sMb мБ`n`Количество файлов: $($content.count)"
$sessionData = @{
"Name" = $name
"Count" = $content.count
"Size" = $size
"Remain" = $remain
"Passed" = $passed
"Starts" = $fStamp
"Calc" = $calcTime
}
$session += $sessionData
#duplex
#queue based on time, and datasize
#$global:formattedTime
}
Write-Host "Устаревшие: " -ForegroundColor Yellow
foreach ($file in $old) {
$name = (($file.BaseName -replace '\.upload', '') -split '_')[2]
Write-Host "АРМ - $name" -ForegroundColor Red
}
Write-Host "Имеющие старый формат: " -ForegroundColor Yellow
foreach ($file in $nonformat) {
$name = (($file.BaseName -replace '\.upload', '') -split '_')[2]
Write-Host "АРМ - $name" -ForegroundColor Red
}
return $session
}
function FreeServerCheck {
param ([string[]]servers)serverSessions = @()
sessions=@foreach(serv in servers) {
sharePath = "\serv\usertemp"sPath = SmbConnect -path sharePath
#проверка флага
flag = FlagCheck -path sharePath−checktrue
if (flag -eq "completed") {
Write-Host "Данные уже скопированы на serv. Флаг - completed" -ForegroundColor Green
exit 0
} elseif (flag -eq "error") {
Write-Host "Предыдущая сессия копирования на serv завершилась неудачно. Флаг - error" -ForegroundColor Yellow
#здесь должен быть кусок кода на удаление файлов оставшихся после неудачной сессии и удаление флага, но пока выход
exit 0
} else {
Write-Host "Файл флага отсутствует на $serv" -ForegroundColor Green
}
code
#расчет времени загрузки на этот сервер исходя из пропускной способности
$calculatedTime = CalculateUploadTime -path $sPath -server $serv
Write-Host "Расчетное время загрузки данных на $serv - $calculatedTime сек"
#подсчет файлов блокировки
$lockfileCount = @(Get-ChildItem -Path "$sPath\locks" -Filter "*.upload.lock").Count
Write-Host "На сервере $serv сессий выгрузки - $lockfileCount, из них"
#получение всей инфы о сессиях
$serverSessions = Parse-LockFiles -server $serv
#кладем в общий словарь сессий по серверам
$sessions.Add($serv, $serverSessions)
$server = $serv
}
return $sessions
$freeServers = @()
$timePerServer = 8*60*60
$maxFreeTime = -1
$targetServer = ""
foreach ($server in $servers) {
$sharePath = "\\$server\user_temp"
$qPath = SmbConnect -path $sharePath
$queueFiles = Get-ChildItem -Path "$qPath\queue" -Filter "queue_*.upload.queue"
$totalCalculatedTime = 0
foreach ($queueFile in $queueFiles) {
$queueInfo = Get-Content -Path $queueFile.FullName | ConvertFrom-Json
$totalCalculatedTime += $queueInfo.CalculatedTime
}
$freeTime = $timePerServer - ($totalCalculatedTime + $global:formattedTime)
if ($freeTime -gt 0) {
$freeServers += @{
Server = $server
FreeTime = $freeTime
}
# Обновляем информацию о сервере с наибольшим свободным временем
if ($freeTime -gt $maxFreeTime) {
$maxFreeTime = $freeTime
$targetServer = $server
}
}
}
if ($freeServers.Count -ge 1) {
Write-Host "Свободные серверы:"
$freeServers
Write-Host "Выбранный сервер с наибольшим свободным временем: $targetServer"
return $targetServer
} else {
Write-Host "Нет свободных серверов для выгрузки на этот сеанс"
exit 1
}
}
This PowerShell script consists of several functions designed to interact with servers, particularly for the purpose of handling lock-files associated with file upload sessions. It's structured to manage and monitor file transfers, especially in checking the status of lock-files and managing queueing for file uploads on multiple servers. Here's a breakdown of the key functions:
Parse-LockFiles
Purpose: To parse lock-files in a specific directory on a server and classify them into active, old, or non-standard format sessions.
Parameters: Takes a single parameter, $server, specifying which server to connect to and parse lock-files from.
Functionality:
Connects to a shared path on the server.
Filters for lock-files with a specific pattern.
Determines whether each session is active, old (leaked), or has a non-standard name format based on the timestamp encoded in the file names.
For active sessions, it additionally calculates the time elapsed, remaining time for the upload, and displays information about the upload data size and count of files.
Groups file sessions into appropriate categories.
FreeServerCheck
Purpose: To evaluate servers for available upload capacity based on existing sessions and calculated upload times.
Parameters: Accepts an array of server names, $servers, to check.
Functionality:
Iterates through each server to check flag status indicating the outcome of previous activities.
Estimates the time required for uploading data to each server based on its capacity.
Counts and categorizes existing lock-files using the Parse-LockFiles function.
Accumulates session data from all evaluated servers and selects one based on set criteria (though the selection process is described but not explicitly shown in the code).
CheckQueue
Purpose: Determines available servers for uploading by analyzing queue files for pending upload sessions and selects the server with the maximum remaining free time.
Parameters: Takes an array of servers, $servers, to evaluate.
Functionality:
Parses queue files on each server to sum up the calculated time needed for pending uploads.
Calculates the free time available on each server by subtracting the sum of pending upload times from the total designated upload time available per server.
Chooses the server with the highest amount of free time as the target server for uploads.
The script is well-structured for scalability and flexibility, allowing for efficient monitoring and management of file uploads across multiple servers in a network environment. Each function encapsulates a distinct portion of the workflow, from parsing and evaluating individual session lock-files to selecting the optimal server for new upload sessions based on current and pending workloads.