-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathamazon-cloudwatch-agent-ctl.ps1
More file actions
464 lines (401 loc) · 17.1 KB
/
Copy pathamazon-cloudwatch-agent-ctl.ps1
File metadata and controls
464 lines (401 loc) · 17.1 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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT
Param (
[Parameter(Mandatory = $false)]
[string]$Action,
[Parameter(Mandatory = $false)]
[switch]$Help,
[Parameter(Mandatory = $false)]
[string]$ConfigLocation = '',
[Parameter(Mandatory = $false)]
[switch]$Start = $false,
[Parameter(Mandatory = $false)]
[string]$Mode = 'ec2',
[Parameter(Mandatory = $false)]
[string]$LogLevel = '',
[Parameter(Mandatory = $false)]
[switch]$d = $false,
[parameter(ValueFromRemainingArguments=$true)]
$unsupportedVars
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = "Stop"
$UsageString = @"
usage: amazon-cloudwatch-agent-ctl.ps1 -a
stop|start|status|fetch-config|append-config|remove-config|set-log-level
[-m ec2|onPremise|onPrem|auto]
[-c default|all|ssm:<parameter-store-name>|file:<file-path>]
[-s]
[-d]
[-l INFO|DEBUG|WARN|ERROR|OFF]
e.g.
1. apply a SSM parameter store config on EC2 instance and restart the agent afterwards:
amazon-cloudwatch-agent-ctl.ps1 -a fetch-config -m ec2 -c ssm:AmazonCloudWatch-Config.json -s
2. append a local json config file on onPremise host and restart the agent afterwards:
amazon-cloudwatch-agent-ctl.ps1 -a append-config -m onPremise -c file:c:\config.json -s
3. query agent status:
amazon-cloudwatch-agent-ctl.ps1 -a status
4. apply a SSM parameter store config with dual-stack endpoints:
amazon-cloudwatch-agent-ctl.ps1 -d -a fetch-config -m ec2 -c ssm:AmazonCloudWatch-Config.json -s
-a: action
stop: stop amazon-cloudwatch-agent if running.
start: start amazon-cloudwatch-agent if configuration is available.
status: get the status of both agent processes.
fetch-config: apply config for agent, followed by -c. Target config can be based on location (ssm parameter store name, file name), or 'default'.
append-config: append json config with the existing json configs if any, followed by -c. Target config can be based on the location (ssm parameter store name, file name), or 'default'.
remove-config: remove config for agent, followed by -c. Target config can be based on the location (ssm parameter store name, file name), or 'all'.
set-log-level: sets the log level, followed by -l to provide the level in all caps.
-m: mode
ec2: indicate this is on ec2 host.
onPremise, onPrem: indicate this is on onPremise host.
auto: use ec2 metadata to determine the environment, may not be accurate if ec2 metadata is not available for some reason on EC2.
-c: amazon-cloudwatch-agent configuration
default: default configuration for quick trial.
ssm:<parameter-store-name>: ssm parameter store name.
file:<file-path>: file path on the host.
all: all existing configs. Only apply to remove-config action.
-s: optionally restart after configuring the agent configuration
this parameter is used for 'fetch-config', 'append-config', 'remove-config' action only.
-d: enable dual-stack endpoints for AWS API calls during config download
this parameter is used for 'fetch-config', 'append-config' actions only.
-l: log level to set the agent to INFO, DEBUG, WARN, ERROR, or OFF
this parameter is used for 'set-log-level' only.
"@
$CWAServiceName = 'AmazonCloudWatchAgent'
$CWAServiceDisplayName = 'Amazon CloudWatch Agent'
$CWADirectory = 'Amazon\AmazonCloudWatchAgent'
$AllConfig = 'all'
$CWAProgramFiles = "${Env:ProgramFiles}\${CWADirectory}"
if ($Env:ProgramData) {
$CWAProgramData = "${Env:ProgramData}\${CWADirectory}"
} else {
# Windows 2003
$CWAProgramData = "${Env:ALLUSERSPROFILE}\Application Data\${CWADirectory}"
}
$CWALogDirectory = "${CWAProgramData}\Logs"
$CWARestartFile ="${CWAProgramData}\restart"
$VersionFile ="${CWAProgramFiles}\CWAGENT_VERSION"
$CVLogFile="${CWALogDirectory}\configuration-validation.log"
# The windows service registration assumes exactly this .toml file path and name
$TOML="${CWAProgramData}\amazon-cloudwatch-agent.toml"
$OTEL_YAML="${CWAProgramData}\amazon-cloudwatch-agent.yaml"
$JSON="${CWAProgramData}\amazon-cloudwatch-agent.json"
$JSON_DIR = "${CWAProgramData}\Configs"
$COMMON_CONIG="${CWAProgramData}\common-config.toml"
$ENV_CONFIG="${CWAProgramData}\env-config.json"
$EC2 = $false
# WMI is unavailable on Nano, CIM is unavailable on 2003
$CIM = $false
Function StartAll() {
Write-Output "`r`n****** Processing amazon-cloudwatch-agent ******"
AgentStart -service_name $CWAServiceName -service_display_name $CWAServiceDisplayName
}
Function AgentStart() {
Param (
[Parameter(Mandatory = $true)]
[string]$service_name,
[Parameter(Mandatory = $true)]
[string]$service_display_name
)
if (${service_name} -eq $CWAServiceName -And !(Test-Path -LiteralPath "${TOML}")) {
Write-Output "amazon-cloudwatch-agent is not configured. Applying amazon-cloudwatch-agent default configuration."
$ConfigLocation = 'default'
CWAConfig -multi_config 'default'
}
$svc = Get-Service -Name "${service_name}" -ErrorAction SilentlyContinue
if (!$svc) {
$startCommand = "`"${CWAProgramFiles}\start-amazon-cloudwatch-agent.exe`""
New-Service -Name "${service_name}" -DisplayName "${service_display_name}" -Description "${service_display_name}" -DependsOn LanmanServer -BinaryPathName "${startCommand}" | Out-Null
# object returned by New-Service gives errors so retrieve it again
$svc = Get-Service -Name "${service_name}"
# Configure the service to restart on crashes. It's unclear how to do this through WMI or CIM interface so using sc.exe
# Restarts immediately on the first two crashes then gives a 2 second sleep after any subsequent crash.
& sc.exe failure "${service_name}" reset= 86400 actions= restart/0/restart/0/restart/2000 | Out-Null
if ($CIM) {
& sc.exe failureflag "${service_name}" 1 | Out-Null
}
}
$svc | Start-Service
Write-Output "$service_name has been started"
}
Function StopAll() {
Write-Output "`r`n****** Processing amazon-cloudwatch-agent ******"
AgentStop -service_name $CWAServiceName
}
Function AgentStop() {
Param (
[Parameter(Mandatory = $true)]
[string]$service_name
)
$svc = Get-Service -Name "${service_name}" -ErrorAction SilentlyContinue
if ($svc) {
$svc | Stop-Service
}
Write-Output "$service_name has been stopped"
}
Function PrepRestartAll() {
AgentPrepRestart -service_name $CWAServiceName -restart_file $CWARestartFile
}
Function AgentPrepRestart() {
Param (
[Parameter(Mandatory = $true)]
[string]$restart_file,
[Parameter(Mandatory = $true)]
[string]$service_name
)
if ((Runstatus -service_name $service_name) -eq 'running') {
Write-Output $null > $restart_file
}
}
Function CondRestartAll() {
AgentCondRestart -service_name $CWAServiceName -service_display_name $CWAServiceDisplayName -restart_file $CWARestartFile
}
Function AgentCondRestart() {
Param (
[Parameter(Mandatory = $true)]
[string]$restart_file,
[Parameter(Mandatory = $true)]
[string]$service_name,
[Parameter(Mandatory = $true)]
[string]$service_display_name
)
if (Test-Path -LiteralPath "${restart_file}") {
AgentStart -service_name $service_name -service_display_name $service_display_name
Remove-Item -LiteralPath "${restart_file}"
}
}
Function PreunAll() {
AgentPreun -service_name $CWAServiceName
}
Function AgentPreun() {
Param (
[Parameter(Mandatory = $true)]
[string]$service_name
)
AgentStop -service_name $service_name
if ($CIM) {
$svc = Get-CimInstance -ClassName Win32_Service -Filter "name='${service_name}'"
$svc | Invoke-CimMethod -MethodName 'delete' | Out-Null
} else {
$svc = Get-WmiObject -Class Win32_Service -Filter "name='${service_name}'"
$svc.delete() | Out-Null
}
}
Function StatusAll() {
$cwa_status = Runstatus -service_name ${CWAServiceName}
$cwa_starttime = GetStarttime -service_name ${CWAServiceName}
$cwa_config_status = 'configured'
if (!(Test-Path -LiteralPath "${TOML}")) {
$cwa_config_status = 'not configured'
}
$version = ([IO.File]::ReadAllText("${VersionFile}")).Trim()
Write-Output "{"
Write-Output " `"status`": `"${cwa_status}`","
Write-Output " `"starttime`": `"${cwa_starttime}`","
Write-Output " `"configstatus`": `"${cwa_config_status}`","
Write-Output " `"version`": `"${version}`""
Write-Output "}"
}
Function GetStarttime() {
Param (
[Parameter(Mandatory = $true)]
[string]$service_name
)
$timefmt=''
if ($CIM) {
$svc = Get-CimInstance -ClassName Win32_Service -Filter "name='${service_name}'"
} else {
$svc = Get-WmiObject -Class Win32_Service -Filter "name='${service_name}'"
}
if ($svc) {
$agentPid = $svc.ProcessId
$process = Get-Process -Id "${agentPid}"
$processStart = $process.StartTime
if ($processStart) {
$timefmt = Get-Date -Date ${processStart} -Format "s"
}
}
return $timefmt
}
# Translate platform status names to those used across all CWAgent's platforms
Function Runstatus() {
Param (
[Parameter(Mandatory = $true)]
[string]$service_name
)
$running = $false
$svc = Get-Service -Name "${service_name}" -ErrorAction SilentlyContinue
if ($svc -and ($svc.Status -eq 'running')) {
$running = $true
}
if ($running) {
return 'running'
} else {
return 'stopped'
}
}
Function ConfigAll() {
Param (
[Parameter(Mandatory = $false)]
[string]$multi_config = 'default'
)
if ($ConfigLocation) {
Write-Output "****** processing amazon-cloudwatch-agent ******"
CWAConfig -multi_config ${multi_config}
}
}
Function CWAConfig() {
Param (
[Parameter(Mandatory = $false)]
[string]$multi_config = 'default'
)
$param_mode="ec2"
if (!$EC2) {
$param_mode="onPremise"
}
if ($ConfigLocation -eq $AllConfig -And $multi_config -ne 'remove') {
Write-Output "Ignore amazon-cloudwatch-agent's configuration ${AllConfig} as it is only supported by action `"remove-config`""
return
}
if ($ConfigLocation -eq $AllConfig) {
Remove-Item -Path "${JSON_DIR}\*" -Force -ErrorAction SilentlyContinue
} else {
$downloader_cmd = "`"${CWAProgramFiles}\config-downloader.exe`" --output-dir `"${JSON_DIR}`" --download-source `"${ConfigLocation}`" --mode `"${param_mode}`" --config `"${COMMON_CONIG}`" --multi-config `"${multi_config}`""
if ($d -and $multi_config -ne 'remove') {
$downloader_cmd += " --dualstack"
}
& cmd /c $downloader_cmd
CheckCMDResult
}
$jsonDirContent = Get-ChildItem "${JSON_DIR}" | Measure-Object
if ($jsonDirContent.count -eq 0) {
Write-Output "All amazon-cloudwatch-agent configurations have been removed"
Remove-Item "${TOML}" -Force -ErrorAction SilentlyContinue
Remove-Item "${OTEL_YAML}" -Force -ErrorAction SilentlyContinue
} else {
Write-Output "Start configuration validation..."
& cmd /c "`"$CWAProgramFiles\config-translator.exe`" --input ${JSON} --input-dir ${JSON_DIR} --output ${TOML} --mode ${param_mode} --config ${COMMON_CONIG} --multi-config ${multi_config} 2>&1"
CheckCMDResult
# Let command pass so we can check return code and give user-friendly error-message
$ErrorActionPreference = "Continue"
& cmd /c "`"${CWAProgramFiles}\amazon-cloudwatch-agent.exe`" --schematest --config ${TOML} 2>&1" | Out-File $CVLogFile
if ($LASTEXITCODE -ne 0) {
Write-Output "Configuration validation second phase failed"
Write-Output "======== Error Log ========"
cat $CVLogFile
exit 1
} else {
Write-Output "Configuration validation second phase succeeded"
}
$ErrorActionPreference = "Stop"
Write-Output "Configuration validation succeeded"
# for translator:
# default: only process .tmp files
# append: process both existing files and .tmp files
# remove: only process existing files
# At this point, all json configs have been validated
# multi_config:
# default: delete non .tmp file, rename .tmp file
# append: rename .tmp file
# remove: no-op
if ($multi_config -eq 'default') {
Remove-Item "${JSON}" -Force -ErrorAction SilentlyContinue
Remove-Item -Path "${JSON_DIR}\*" -Exclude "*.tmp" -Force -ErrorAction SilentlyContinue
Get-ChildItem "${JSON_DIR}\*.tmp" | Rename-Item -NewName { $_.name -Replace '\.tmp$','' }
} elseif ($multi_config -eq 'append') {
Get-ChildItem "${JSON_DIR}\*.tmp" | ForEach-Object {
$newName = $_.name -Replace '\.tmp$',''
$destination = Join-Path -Path $_.Directory.FullName -ChildPath "${newName}"
Move-Item -Path $_.FullName -Destination "${destination}" -Force
}
}
}
if ($Start) {
AgentStop -service_name $CWAServiceName
AgentStart -service_name $CWAServiceName -service_display_name $CWAServiceDisplayName
}
}
# For exes(non cmlet) the $ErrorActionPreference won't help if run cmd result failed,
# We have to check the $LASTEXITCODE everytime.
Function CheckCMDResult($ErrorMessage, $SuccessMessage) {
if ($LASTEXITCODE -ne 0) {
if (![string]::IsNullOrEmpty($ErrorMessage)) {
Write-Output $ErrorMessage
}
exit 1
} else {
if (![string]::IsNullOrEmpty($SuccessMessage)) {
Write-Output $SuccessMessage
}
}
}
# TODO Occasionally metadata service isn't available and this gives a false negative - might
# be a better way to probe
# http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/identify_ec2_instances.html
# Ultimately though an optional 'ec2-override' flag seems necessary for easier testing
Function CWATestEC2() {
$error.clear()
$request = [System.Net.WebRequest]::Create('http://169.254.169.254/')
$request.Timeout = 5
try {
$response = $request.GetResponse()
$response.Close()
} catch {
return $false
}
return !$error
}
Function SetLogLevelAll() {
switch -exact ($LogLevel) {
INFO { }
DEBUG { }
ERROR { }
WARN { }
OFF { }
default {
Write-Output "Invalid log level: ${LogLevel}`n${UsageString}"
Exit 1
}
}
& cmd /c "`"${CWAProgramFiles}\amazon-cloudwatch-agent.exe`" --setenv CWAGENT_LOG_LEVEL=${LogLevel} --envconfig ${ENV_CONFIG} 2>&1"
CheckCMDResult "" "Set CWAGENT_LOG_LEVEL to ${LogLevel}"
}
Function main() {
if (Get-Command 'Get-CimInstance' -CommandType Cmdlet -ErrorAction SilentlyContinue) {
$CIM = $true
}
if ($unsupportedVars) {
Write-Output "Ignore unsupported params: $unsupportedVars`n${UsageString}"
}
if ($Help) {
Write-Output "${UsageString}"
exit 0
}
switch -exact ($Mode) {
ec2 { $EC2 = $true }
onPremise { $EC2 = $false }
onPrem { $EC2 = $false }
auto { $EC2 = CWATestEC2 }
default {
Write-Output "Invalid mode: ${Mode}`n${UsageString}"
Exit 1
}
}
switch -exact ($Action) {
stop { StopAll }
start { StartAll }
fetch-config { ConfigAll }
append-config { ConfigAll -multi_config 'append' }
remove-config { ConfigAll -multi_config 'remove' }
status { StatusAll }
prep-restart { PrepRestartAll }
cond-restart { CondRestartAll }
preun { PreunAll }
set-log-level { SetLogLevelAll }
default {
Write-Output "Invalid action: ${Action}`n${UsageString}"
Exit 1
}
}
}
main