-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsnapraid-script.ps1
More file actions
211 lines (169 loc) · 6.28 KB
/
Copy pathsnapraid-script.ps1
File metadata and controls
211 lines (169 loc) · 6.28 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
$LogFile = ".\logs\$(Get-Date -Format yyyy-MM-dd_HH-mm-ss).log"
$CredentialFile = ".\snapraid-script.cred"
$ConfigFile = ".\snapraid-script.psd1"
Try {
$Config = Import-PowerShellDataFile -Path $ConfigFile
$Credential = Import-CliXml -Path $CredentialFile
} Catch {}
function Send-Notification {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)][ValidateNotNullOrEmpty()][ValidateSet("SUCCESS", "FAILURE")][String] $Status
)
if( $Credential -eq $Null ){
return
}
$Params = @{
Subject = ("[$Status] Snapraid report")
SmtpServer = $Config.Email.SmtpServer
Port = $Config.Email.Port
UseSsl = $Config.Email.UseSsl
From = $Config.Email.From
To = $Config.Email.To
}
$RetryCount = 3
Do {
Try {
Send-MailMessage @Params -Attachments $LogFile -Credential $Credential -ErrorAction Stop
return
} Catch {
$RetryCount++
Start-Sleep -Seconds 60
}
} Until( $RetryCount -lt 4 )
}
function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline)][AllowEmptyString()][String] $Message
)
process {
$Format = "[{0}]: {1}"
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss:fff")
$Message -split "[\n\r]+" | %{ $Format -f ($Stamp, $_) } | %{ $_.TrimEnd() } | Write-Host
}
}
function Write-Header {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)][String] $Value,
[Parameter(Mandatory=$False)][Int] $Length = 48
)
$CenterOffset = ' ' * [math]::floor(($Length - $Value.Length) / 2)
Write-Log ('-' * $Length)
Write-Log ($CenterOffset + $Value)
Write-Log ('-' * $Length)
}
function Write-ExecutionInfo {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)][ValidateNotNull()][PSCustomObject] $Info,
[Parameter(Mandatory=$False)][Int] $Length = 48
)
Write-Log ('-' * $Length)
Write-Log ("Duration: {0:g}" -f $Info.Duration)
Write-Log ("ExitCode: {0}" -f $Info.ExitCode)
Write-Log ('-' * $Length)
}
function Check-SafeToRun {
if( !(($Process = Get-Process "snapraid" -ErrorAction SilentlyContinue) -eq $Null) ) {
Write-Log "Failed to start snapraid because another snapraid process is already running!"
Write-Log ($Process | Out-String)
Finalize -Status "FAILURE"
}
}
function Run-Snapraid {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)][ValidateNotNullOrEmpty()][String] $Command,
[Parameter(Mandatory=$False)][ValidateNotNullOrEmpty()][String[]] $Params
)
Write-Header ("{0} {1} {2}" -f $Config.Snapraid.Executable,$Command,"$Params")
Check-SafeToRun
$Output = ""
$TimeSpan = Measure-Command {
&$Config.Snapraid.Executable $Command $Params 2>&1 3>&1 4>&1 | %{ "$_" } | Tee-Object -Variable Output | Write-Log
}
$ExecutionInfo = [PSCustomObject]@{
ExitCode = $LastExitCode
Output = $Output
Duration = $TimeSpan
}
Write-ExecutionInfo $ExecutionInfo
if( $ExecutionInfo.ExitCode -eq 1 ){
Write-Log "Execution of '$Command' failed! Aborting."
Finalize -Status "FAILURE"
}
return $ExecutionInfo
}
function Get-DiffInfo {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True, ValueFromPipeline)][ValidateNotNull()][PSCustomObject] $ExecutionInfo
)
process {
$DiffInfo = @{}
$Regex = "^\s*(\d+)\s+(equal|added|removed|updated|moved|copied|restored)\s*$"
$ExecutionInfo.Output | Select-String $Regex -AllMatches | %{ $_.Matches[0] } | %{ $DiffInfo[$_.Groups[2].Value] = [int]$_.Groups[1].Value }
if( $DiffInfo.Keys.Count -eq 0 ) {
Write-Log "Diff command parsing failed!"
return $Null
}
$NumberOfChanges = ($DiffInfo.GetEnumerator() | Where-Object Key -notin "equal" | %{ $_.Value } | Measure-Object -Sum).Sum
$DiffInfo["total_changes"] = $NumberOfChanges
# Sync needed when there was any file changes or if 'diff' command returns 'sync required' exitcode (2)
$DiffInfo["needs_sync"] = ( &{ if( $NumberOfChanges -gt 0 -or $ExecutionInfo.ExitCode -eq 2 ) {$True} Else {$False}} )
return $DiffInfo
}
}
function Initialize {
Start-Transcript -Path $LogFile
if( $Config -eq $Null ) {
Write-Log "Failed to read configuration file!"
Stop-Transcript | Out-Null
Exit
}
if( $Config.Notification.OnSuccess -eq $True -or $Config.Notification.OnFailure -eq $True ) {
if( $Credential -eq $Null ) {
Write-Log "$CredentialFile file not found!"
Write-Log "Prompting user for new credentials..."
$Credential = Get-Credential -Message "Enter your smtp username and password:"
if( $Credential -eq $Null ) {
Write-Log "Canceled by user"
Exit
}
$Credential | Export-Clixml -Path $CredentialFile
Write-Log "Sending test notification..."
Finalize -Status "SUCCESS"
}
}
}
function Finalize {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)][ValidateNotNullOrEmpty()][ValidateSet("SUCCESS", "FAILURE")][String] $Status
)
Stop-Transcript | Out-Null
if( $Config.Notification.OnSuccess -eq $False -and $Status -eq "SUCCESS" ) {
Exit
} elseif( $Config.Notification.OnFailure -eq $False -and $Status -eq "FAILURE" ) {
Exit
}
Send-Notification -Status $Status
Exit
}
Initialize
Run-Snapraid -Command "touch"
$DiffInfo = Run-Snapraid -Command "diff" | Get-DiffInfo
if( $DiffInfo -eq $Null ) {
Finalize -Status "FAILURE"
} elseif( $Config.Snapraid.Diff.DeleteThreshold -gt 0 -and $DiffInfo["removed"] -gt $Config.Snapraid.Diff.DeleteThreshold ) {
Write-Log ("Number of removed files exceeds configured threshold! ({0} > {1})" -f $DiffInfo["removed"],$Config.Snapraid.Diff.DeleteThreshold)
Finalize -Status "FAILURE"
}
if( $DiffInfo["needs_sync"] -eq $True ) {
Run-Snapraid -Command "sync"
}
Run-Snapraid -Command "scrub" -Params "--plan",$Config.Snapraid.Scrub.Plan,"--older-than",$Config.Snapraid.Scrub.OlderThan | Out-Null
Run-Snapraid -Command "status" | Out-Null
Finalize -Status "SUCCESS"