-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_sync.ps1
More file actions
210 lines (191 loc) · 9.68 KB
/
run_sync.ps1
File metadata and controls
210 lines (191 loc) · 9.68 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
# Anschaungsbeispiel für ein PowerShell-Skript, das eine Datei-Synchronisation mit Robocopy durchführt.
# Dieses Skript ist ein Anschauunsbeispiel zum strukturieren Kopieren mit erweiterter Protokollierung
# und Authentisierung bei einer Quelle. Das Ziel wird nicht authentisiert und wird als berechtigt angenommen.
# ACHTUNG, WICHTIGER HINWEIS!
# Dieses Skript ist Teil der Projekt-Dokumentation und dient als Beispiel. Es darf nicht ohne Anpassungen in der Produktionsumgebung verwendet werden.
# Der Verfasser übernimmt keinerlei Verantwortung für Fehlerfreiheit, Vollständigkeit oder Eignung für einen bestimmten Zweck.
# Es gibt keinen Support, keine Gewährleistung und keine Haftung für Schäden, die durch die Verwendung dieses Skripts entstehen könnten.
# Bitte testen Sie ein Skript, das Sie auf dieser Grundlage erstellen, gründlich in einer sicheren Umgebung, bevor Sie
# es in einer Produktionsumgebung verwenden.
# SMB File Sync Main Script
param(
[string]$ConfigPath = "config/$(hostname).yml",
[switch]$DryRun
)
# Import modules
. "$PSScriptRoot/scripts/Utils.ps1"
. "$PSScriptRoot/scripts/Log-Handler.ps1"
. "$PSScriptRoot/scripts/Alert-Handler.ps1"
# Set timestampStart at the very top so it is always available for all log events
$timestampStart = Get-Date
# --- Konfigurationsauswahl ---
$hostname = $env:COMPUTERNAME
$hostConfig = "config/$hostname.yml"
$defaultConfig = "config/sync_config.yml"
$config = $null
if ($PSBoundParameters.ContainsKey('ConfigPath') -and $ConfigPath) {
if (Test-Path $ConfigPath) {
$config = Get-YamlContent -Path $ConfigPath
if (-not $config) {
Write-Host "Config not found or invalid: $ConfigPath"
Write-Host "Usage:`n powershell .\\run_sync.ps1 -ConfigPath <your_config.yml>"
exit 4
}
} else {
Write-Host "Config not found: $ConfigPath"
Write-Host "Usage:`n powershell .\\run_sync.ps1 -ConfigPath <your_config.yml>"
exit 4
}
} else {
if (Test-Path $hostConfig) {
$config = Get-YamlContent -Path $hostConfig
if ($config) {
$ConfigPath = $hostConfig
}
}
if (-not $config -and (Test-Path $defaultConfig)) {
$config = Get-YamlContent -Path $defaultConfig
if ($config) {
$ConfigPath = $defaultConfig
}
}
if (-not $config) {
Write-Host "No default config found or both configs invalid (tried: $hostConfig, $defaultConfig) and no specific config file passed.`n"
Write-Host "Usage:`n powershell .\\run_sync.ps1 -ConfigPath <your_config.yml>`n"
exit 3
}
}
# Prepare paths
$logDir = $config.logging.log_dir
$hostname = $env:COMPUTERNAME
$timestamp = Get-Date -Format "MMdd_HHmmss"
$lockFile = Join-Path $PSScriptRoot ("${hostname}_ROBOCOPY_IN_PROGRESS_${timestamp}.lock")
$progressFile = $lockFile
# Ensure log directory exists
New-DirectoryIfNotExists -directoryPath $logDir
# Lock file handling
$existingLock = Get-ChildItem -Path $PSScriptRoot -Filter "*_ROBOCOPY_IN_PROGRESS_*.lock" | Where-Object { $_.Name -like "${hostname}_ROBOCOPY_IN_PROGRESS_*.lock" }
if ($existingLock) {
Write-Host "Lock file exists for this host: $($existingLock.FullName). Exiting."
$timestampStart = Get-Date
$timestampEnd = $timestampStart
$status = "LOCKED"
$summary = "Copying aborted: This machine ($hostname) is already running a copy job."
$exitCode = 100
$robocopyCmd = ""
$logFormats = $config.logging.machine_log_format -split ','
foreach ($fmt in $logFormats) {
if ($fmt.Trim().ToLower() -eq 'json') {
Log-SyncResult -EventType "END" -Status $status -Summary $summary -Format $fmt.Trim() -LogDir $logDir -Hostname $hostname -TimestampStart $timestampStart -TimestampEnd $timestampEnd -ExitCode $exitCode -Command $robocopyCmd
} elseif ($fmt.Trim().ToLower() -eq 'csv') {
Log-SyncResult -EventType "END" -Status $status -Summary $summary -Format $fmt.Trim() -LogDir $logDir -Hostname $hostname -TimestampStart $timestampStart -TimestampEnd $timestampEnd -ExitCode $exitCode -Command $robocopyCmd
}
}
exit 2
}
Set-Content -Path $lockFile -Value "Locked by $hostname at $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') [PID: $PID]"
Write-Host "LOCK file created: $lockFile"
try {
Write-Host ("Remote Fileshare as configured: " + $config.job.source)
if ($config.auth.use_kerberos) {
$user = $config.auth.remote_domain_user
$share = $config.job.source
Write-Host ("Connecting to Remote Host $share using user account $user to mount data source.")
try {
$pw = [Environment]::GetEnvironmentVariable($config.auth.password_env_var)
if (-not $pw) { throw "Password env var not set: $($config.auth.password_env_var)" }
New-SmbDriveWithCreds -Share $share -User $user -Password $pw
} catch {
$mountError = $_.Exception.Message
Write-Host "Error: Could not mount remote share: $share"
$summary = "Fehler beim Mounten von ${share}: ${mountError}"
$timestampEnd = Get-Date
$status = "MOUNT_FAILED"
$exitCode = 101
$robocopyCmd = ""
$logFormats = $config.logging.machine_log_format -split ','
foreach ($fmt in $logFormats) {
if ($fmt.Trim().ToLower() -eq 'json') {
Log-SyncResult -EventType "END" -Status $status -Summary $summary -Format $fmt.Trim() -LogDir $logDir -Hostname $hostname -TimestampStart $timestampStart -TimestampEnd $timestampEnd -ExitCode $exitCode -Command $robocopyCmd
} elseif ($fmt.Trim().ToLower() -eq 'csv') {
Log-SyncResult -EventType "END" -Status $status -Summary $summary -Format $fmt.Trim() -LogDir $logDir -Hostname $hostname -TimestampStart $timestampStart -TimestampEnd $timestampEnd -ExitCode $exitCode -Command $robocopyCmd
}
}
Remove-FileIfExists -filePath $lockFile
exit 101
}
}
$robocopyCmd = "robocopy `"$($config.job.source)`" `"$($config.job.destination)`" $($config.job.robocopy_flags)"
Write-Host ("About to run: " + $robocopyCmd)
# Write progress file (start)
Add-Content -Path $lockFile -Value "`ncopy launched on $hostname with robocopy $robocopyCmd"
# Alert on start
if ($config.alerts.enabled -and $config.alerts.on_start) {
Send-StartAlert -SmtpServer $config.alerts.smtp_server -From $config.alerts.from -To $config.alerts.to -Command $robocopyCmd
}
# Logging START event (nur CSV!)
$logFormats = $config.logging.machine_log_format -split ','
foreach ($fmt in $logFormats) {
if ($fmt.Trim().ToLower() -eq 'csv') {
Log-SyncResult -EventType "START" -Status "STARTED" -Summary "Sync started." -Format $fmt.Trim() -LogDir $logDir -Hostname $hostname -TimestampStart $timestampStart
}
}
# Robocopy execution
$exitCode = 999
$status = "ABORTED"
$summary = ""
if ($DryRun) {
$status = "DRYRUN"
$summary = "Dry run: robocopy would be executed as: $robocopyCmd"
Write-Host $summary
} else {
$maxMinutes = $config.job.max_runtime_minutes
$startTime = Get-Date
$timeout = $false
$robocopyFlagsArray = $config.job.robocopy_flags -split ' '
$robocopyArgs = @($config.job.source, $config.job.destination) + $robocopyFlagsArray
Write-Host "Robocopy output:"
$robocopyBuffer = @()
& robocopy.exe @robocopyArgs | Tee-Object -Variable robocopyBuffer
$robocopyResult = $robocopyBuffer -join "`n"
$exitCode = $LASTEXITCODE
$summary = "Robocopy exit code: $exitCode"
if ($timeout) {
$status = "ABORTED"
$summary = "Timeout after $maxMinutes minutes. Partial output:\n$summary"
Write-Host "Robocopy aborted due to timeout."
} elseif ($exitCode -eq 0 -or $exitCode -eq 1) {
$status = "COMPLETED"
Write-Host "Robocopy completed successfully. Exit code: $exitCode"
} else {
$status = "ABORTED"
Write-Host "Robocopy did not complete successfully. Exit code: $exitCode"
}
}
# Logging END event (immer für alle Formate)
$timestampEnd = Get-Date
$robocopyStats = $null
if ($status -eq "COMPLETED") {
$robocopyStats = Parse-RobocopyStats -RobocopyOutput $robocopyResult
}
foreach ($fmt in $logFormats) {
if ($fmt.Trim().ToLower() -eq 'json') {
Log-SyncResult -EventType "END" -Status $status -Summary $summary -Format $fmt.Trim() -LogDir $logDir -Hostname $hostname -TimestampStart $timestampStart -TimestampEnd $timestampEnd -ExitCode $exitCode -Command $robocopyCmd -RobocopyStats $robocopyStats
} elseif ($fmt.Trim().ToLower() -eq 'csv') {
Log-SyncResult -EventType "END" -Status $status -Summary $summary -Format $fmt.Trim() -LogDir $logDir -Hostname $hostname -TimestampStart $timestampStart -TimestampEnd $timestampEnd -ExitCode $exitCode -Command $robocopyCmd -RobocopyStats $robocopyStats
}
}
Write-Host "Logs written to: $logDir"
# Alerting
if ($config.alerts.enabled) {
if ($status -eq "ABORTED" -and $config.alerts.on_abort) {
Send-AbortAlert -SmtpServer $config.alerts.smtp_server -From $config.alerts.from -To $config.alerts.to -ErrorMessage $summary
} elseif ($status -eq "COMPLETED" -and $config.alerts.on_complete) {
Send-CompleteAlert -SmtpServer $config.alerts.smtp_server -From $config.alerts.from -To $config.alerts.to -Summary $summary
}
}
} finally {
Remove-FileIfExists -filePath $lockFile
Write-Host "LOCK file removed: $lockFile"
Remove-FileIfExists -filePath $progressFile
}