Advertisement
Guest User

Untitled

a guest
Jul 8th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.28 KB | None | 0 0
  1. param(
  2. [String]$Environment = "local",
  3. [String]$Application = "test-app",
  4. [String]$Command = "scp",
  5. [ValidateSet("All", "File", "Console", "None")]
  6. [String]$LogOutput = "Console"
  7. )
  8.  
  9. Set-StrictMode -Version Latest
  10. $ErrorActionPreference = "Stop"
  11.  
  12. $scriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
  13. . "${scriptRoot}powershellcommon.ps1"
  14. . "${scriptRoot}powershellpackage.ps1"
  15. . "${scriptRoot}powershelloneshot.ps1"
  16.  
  17. $env:sshUser = getUser
  18. $env:logOutput = "Console"
  19.  
  20. ##- DynamicParameter.
  21. # Parameter with set validation based on an array provided at runtime.
  22. function DynamicParameter {
  23. param (
  24. $name,
  25. $completionValues
  26. )
  27. $attributeCollection = New-Object Collections.ObjectModel.Collection[System.Attribute]
  28.  
  29. $parameterAttribute = New-Object Management.Automation.ParameterAttribute
  30. $parameterAttribute.Mandatory = $true
  31. $attributeCollection.Add($parameterAttribute)
  32.  
  33. $validateSetAttribute = New-Object Management.Automation.ValidateSetAttribute($completionValues)
  34. $attributeCollection.Add($validateSetAttribute)
  35.  
  36. $runtimeParameter = New-Object `
  37. Management.Automation.RuntimeDefinedParameter($name, [string], $attributeCollection)
  38. return $runtimeParameter
  39. }
  40. #-##
  41.  
  42. ##- Spoc.
  43. function Spoc {
  44. ##- Parameters.
  45. [CmdletBinding()]
  46. param (
  47. [ValidateSet("All", "File", "Console", "None")]
  48. [String]$LogOutput = "Console"
  49. )
  50. DynamicParam {
  51. $runtimeParameters = New-Object Management.Automation.RuntimeDefinedParameterDictionary
  52.  
  53. $environmentCompletions = $(Get-ChildItem -Path ".configurations" -Directory | Select-Object -ExpandProperty Name)
  54. $environmentParameter = DynamicParameter "Environment" $environmentCompletions
  55. $runtimeParameters.Add("Environment", $environmentParameter)
  56.  
  57. $applicationCompletions = $(Get-ChildItem -Path ".configurationstest" | Select-Object -ExpandProperty Name | % { $_.replace(".ps1", "") })
  58. $applicationCompletions += "test-app"
  59. $applicationCompletions += "test-app-zip"
  60. $applicationParameter = DynamicParameter "Application" $applicationCompletions
  61. $runtimeParameters.Add("Application", $applicationParameter)
  62.  
  63. $commandCompletions = $(Get-ChildItem -Path ".commands*.ps1" | Select-Object -ExpandProperty Name | % { $_.replace(".ps1", "") })
  64. $commandParameter = DynamicParameter "Command" $commandCompletions
  65. $runtimeParameters.Add("Command", $commandParameter)
  66.  
  67. return $runtimeParameters
  68. }
  69.  
  70. begin {
  71. $Environment = $PsBoundParameters["Environment"]
  72. $Application = $PsBoundParameters["Application"]
  73. $Command = $PsBoundParameters["Command"]
  74. }
  75. #-##
  76.  
  77. process {
  78.  
  79. ##- Parameter warnings.
  80. if($Environment -eq "local") {
  81. Warning "No environment parameter provided, using default value: local."
  82. }
  83. if($Application -eq "test-app") {
  84. Warning "No application parameter provided, using default value: test-app."
  85. }
  86. if($Command -eq "scp") {
  87. Warning "No command parameter provided, using default value: scp."
  88. }
  89. #-##
  90.  
  91. $env:sshUser = getUser
  92. $env:password = getPassword
  93. $logTargets = @("All", "File", "Console", "None")
  94. $env:logOutput = $LogOutput
  95.  
  96. . "${scriptRoot}configurations${Environment}${Application}.ps1"
  97. Invoke-Expression "${scriptRoot}commands${Command}.ps1"
  98. }
  99. }
  100. #-##
  101.  
  102. if(!($MyInvocation.InvocationName -eq ".")) {
  103. Spoc -Environment $Environment -Application $Application -Command $Command -LogOutput $LogOutput
  104. }
  105.  
  106. Set-StrictMode -Version Latest
  107. $ErrorActionPreference = "Stop"
  108.  
  109. ##- Logging functions.
  110. function global:Write {
  111. param (
  112. [Parameter(Mandatory)]
  113. [string]$logLevel,
  114. [Parameter(Mandatory)]
  115. [String]$message
  116. )
  117. $messageTime = $(Get-Date -format "HH:mm:ss dd.MM.yyyy")
  118. $color = "Gray"
  119. if($logLevel -eq "warning") {
  120. $color = "Yellow"
  121. }
  122. if($logLevel -eq "error") {
  123. $color = "Red"
  124. }
  125. if(($env:logOutput -eq "All") -or ($env:logOutput -eq "Console")) {
  126. Write-Host -ForegroundColor $color $message
  127. }
  128. if(($env:logOutput -eq "All") -or ($env:logOutput -eq "File")) {
  129. Write-Output "[${logLevel}][${messageTime}]${message}" | Out-File -Append "Z:worktmplauncher.txt"
  130. }
  131. }
  132.  
  133. function global:Info {
  134. ##- Parameters.
  135. param (
  136. [Parameter(Mandatory)]
  137. [AllowEmptyString()]
  138. [String]$message
  139. )
  140. #-##
  141. global:Write "info" $message
  142. }
  143.  
  144. function global:Warning {
  145. ##- Parameters.
  146. param (
  147. [Parameter(Mandatory)]
  148. [AllowEmptyString()]
  149. [String]$message
  150. )
  151. #-##
  152. global:Write "warning" $message
  153. }
  154.  
  155. function global:Error {
  156. ##- Parameters.
  157. param (
  158. [Parameter(Mandatory)]
  159. [AllowEmptyString()]
  160. [String]$message
  161. )
  162. #-##
  163. global:Write "error" $message
  164. }
  165.  
  166.  
  167. function global:ErrorExit {
  168. ##- Parameters.
  169. param (
  170. [Parameter(Mandatory)]
  171. [AllowEmptyString()]
  172. [String]$message
  173. )
  174. #-##
  175. global:Error $message
  176. throw
  177. }
  178. #-##
  179.  
  180. ##- Environment, user, password.
  181. function getUser() {
  182. return "${env:USERNAME}a"
  183. }
  184.  
  185. function getPassword() {
  186. $password = Read-Host -Prompt "Password" -AsSecureString
  187. $password = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
  188. $password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($password)
  189. return $password
  190. }
  191. #-##
  192.  
  193. ##- BaseRun.
  194. function BaseRun
  195. {
  196. ##- Parameters.
  197. param (
  198. [Parameter(Mandatory)]
  199. [String]$hostname,
  200. [Parameter(Mandatory)]
  201. [String]$command,
  202. [String]$arguments
  203. )
  204. #-##
  205.  
  206. ##- Process info.
  207. $procInfo = New-Object System.Diagnostics.ProcessStartInfo
  208. $procInfo.RedirectStandardOutput = $true
  209. $procInfo.RedirectStandardError = $true
  210. $procInfo.RedirectStandardInput = $true
  211. $procInfo.FileName = $command
  212. $procInfo.Arguments = $arguments
  213. $procInfo.UseShellExecute = $false
  214. #-##
  215.  
  216. $process = New-Object System.Diagnostics.Process
  217. $process.StartInfo = $procInfo
  218.  
  219. $global:hostname = $hostname
  220. $global:outputBuffer = New-Object System.Text.StringBuilder
  221.  
  222. try {
  223. ##- Register output and error event handlers.
  224. Register-ObjectEvent -InputObject $process `
  225. -EventName OutputDataReceived -SourceIdentifier processOutputDataReceived `
  226. -Action {
  227.  
  228. $data = $EventArgs.data
  229. if($data -ne $null) {
  230. if($data -notmatch "[sudo] password for.*") {
  231. $outputBuffer.Append("${data}`n")
  232. Info "[${hostname}][output] ${data}"
  233. }
  234. }
  235. } | Out-Null
  236.  
  237. Register-ObjectEvent -InputObject $process `
  238. -EventName ErrorDataReceived -SourceIdentifier processErrorDataReceived `
  239. -Action {
  240.  
  241. $data = $EventArgs.data
  242. if($data -ne $null) {
  243. $outputBuffer.Append("${data}`n")
  244. Error "[${hostname}][error] ${data}"
  245. }
  246. } | Out-Null
  247. #-##
  248.  
  249. [void]$process.Start()
  250.  
  251. ##- Input password.
  252. # Only input the password for plink.exe (non-local execution)
  253. # or for pscp.exe (local execution of scp).
  254. if (($hostname -ne "local") -or ($command -match "pscp.exe")) {
  255. if(!(Test-Path Env:sshUser)) {
  256. ErrorExit "No password provided, set `$env:password"
  257. }
  258. $inputStream = $process.StandardInput
  259. # A slightly longer timeout is needed to make sure that the app was started.
  260. Start-Sleep -m 2000
  261. $inputStream.Write("${env:password}`n")
  262. $inputStream.Close()
  263. }
  264. #-##
  265.  
  266. $process.BeginOutputReadLine()
  267. $process.BeginErrorReadLine()
  268.  
  269. $process.WaitForExit()
  270. }
  271. finally {
  272. Unregister-Event -SourceIdentifier processOutputDataReceived
  273. Unregister-Event -SourceIdentifier processErrorDataReceived
  274. }
  275.  
  276. # Return both the exit code and the command output.
  277. $process.ExitCode
  278. $outputBuffer.ToString()
  279. }
  280. #-##
  281.  
  282. ##- LocalRun.
  283. function LocalRun {
  284. ##- Parameters.
  285. param (
  286. [Parameter(Mandatory)]
  287. [String]$command,
  288. [bool]$captureOutput = $false
  289. )
  290. #-##
  291. Info "[local][command] $command"
  292.  
  293. $commandComponents = $command -split " "
  294. $command = $commandComponents[0]
  295. if($commandComponents.Count -gt 2) {
  296. $arguments = $commandComponents[1..$($commandComponents.Count - 1)] -join " "
  297. } else {
  298. $arguments = ""
  299. }
  300.  
  301. $baseRunResult = BaseRun "local" $command $arguments
  302.  
  303. if ($baseRunResult[0] -ne 0) {
  304. Start-Sleep -m 1000
  305. ErrorExit "Execution stopped due to an error, check the command output."
  306. }
  307.  
  308. if($captureOutput -eq $true) {
  309. return $baseRunResult[1]
  310. }
  311. }
  312. #-##
  313.  
  314. ##- Run.
  315. function Run {
  316. ##- Parameters.
  317. param (
  318. [Parameter(Mandatory)]
  319. [String]$sshHostname,
  320. [Parameter(Mandatory)]
  321. [String]$command,
  322. [bool]$captureOutput = $false
  323. )
  324. #-##
  325. Info "[${sshHostname}][command] $command"
  326.  
  327. $initialLogOutput = $env:logOutput
  328. # Silence the output so we don't echo the password.
  329. $env:logOutput = "None"
  330.  
  331. # Dummy plink connection to check the connectivity, password, etc.
  332. $plink = "C:ToolsPuTTYplink.exe"
  333. $plinkNonInteractiveArgs = "-batch -v -pw ${env:password}"
  334. $plinkInteractiveArgs = "-l ${env:sshUser} -t ${sshHostname} whoami"
  335. $plinkArguments = "${plinkNonInteractiveArgs} ${plinkInteractiveArgs}"
  336.  
  337. $sshCheck = BaseRun $sshHostname $plink $plinkArguments
  338.  
  339. $env:logOutput = $initialLogOutput
  340.  
  341. $lastLine = $($sshCheck -split "`n")[-2]
  342. if($lastLine -match "Host does not exist") {
  343. ErrorExit "Cannot connect to ${sshHostname}, host not found."
  344. }
  345. if($lastLine -match "Disconnected: User aborted at host key verification") {
  346. Error "Cannot authenticate to ${sshHostname}, server key not accepted."
  347. ErrorExit "Run ${plink} ${plinkInteractiveArgs} and accept the key."
  348. }
  349. if($lastLine -match "Disconnected: Unable to authenticate") {
  350. ErrorExit "Cannot authenticate to ${sshHostname}, wrong password."
  351. }
  352.  
  353. $baseRunResult = BaseRun $sshHostname "C:ToolsPuTTYplink.exe" `
  354. "-batch -l ${env:sshUser} -pw ${env:password} -t ${sshHostname} ${command}"
  355.  
  356. if ($baseRunResult[0] -ne 0) {
  357. Start-Sleep -m 1000
  358. ErrorExit "Execution stopped due to an error, check the command output."
  359. }
  360.  
  361. if($captureOutput -eq $true) {
  362. return $baseRunResult[1]
  363. }
  364. }
  365. #-##
  366.  
  367. ##- RunAsUser.
  368. function RunAsUser {
  369. ##- Parameters.
  370. param (
  371. [Parameter(Mandatory)]
  372. [String]$sshHostname,
  373. [Parameter(Mandatory)]
  374. [String]$applicationUser,
  375. [Parameter(Mandatory)]
  376. [String]$command,
  377. [bool]$captureOutput = $false
  378. )
  379. #-##
  380.  
  381. $command = "sudo su - ${applicationUser}<<END`n${command}`nEND"
  382.  
  383. $runResult = Run $sshHostname $command $captureOutput
  384.  
  385. if($captureOutput -eq $true) {
  386. return $runResult
  387. }
  388. }
  389. #-##
  390.  
  391. ##- Command line functions.
  392. function Local-Scp {
  393. ##- Parameters.
  394. param (
  395. [Parameter(Mandatory)]
  396. [String]$fileToCopy,
  397. [Parameter(Mandatory)]
  398. [String]$sourceServer,
  399. [Parameter(Mandatory)]
  400. [String]$sourceFolder,
  401. [Parameter(Mandatory)]
  402. [String]$targetFolder,
  403. [bool]$captureOutput = $false
  404. )
  405. #-##
  406.  
  407. $pscp = "C:ToolsPuTTYpscp.exe"
  408. $pscpArguments = "${env:sshUser}@${sourceServer}:${sourceFolder}/${fileToCopy} ${targetFolder}/${fileToCopy}"
  409.  
  410. $localRunResult = LocalRun "${pscp} ${pscpArguments}" $captureOutput
  411.  
  412. if($captureOutput -eq $true) {
  413. return $localRunResult
  414. }
  415. }
  416.  
  417. function Scp-File {
  418. ##- Parameters.
  419. param (
  420. [Parameter(Mandatory)]
  421. [String]$fileToCopy,
  422. [Parameter(Mandatory)]
  423. [String]$sourceServer,
  424. [Parameter(Mandatory)]
  425. [String]$sourceFolder,
  426. [Parameter(Mandatory)]
  427. [String]$targetServer,
  428. [Parameter(Mandatory)]
  429. [String]$targetFolder,
  430. [bool]$captureOutput = $false
  431. )
  432. #-##
  433.  
  434. $runResult = Run $targetServer `
  435. "scp ${sourceServer}:${sourceFolder}/${fileToCopy} ${targetFolder}" $captureOutput
  436. if($captureOutput -eq $true) {
  437. return $runResult
  438. }
  439. }
  440.  
  441. function Ssh-Command {
  442. ##- Parameters.
  443. param (
  444. [Parameter(Mandatory)]
  445. [String]$sshHostname,
  446. [Parameter(Mandatory)]
  447. [String]$command,
  448. [bool]$captureOutput = $false
  449. )
  450. #-##
  451.  
  452. $runResult = Run $sshHostname $command $captureOutput
  453.  
  454. if($captureOutput -eq $true) {
  455. return $runResult
  456. }
  457. }
  458.  
  459. function Ssh-CommandAsUser {
  460. ##- Parameters.
  461. param (
  462. [Parameter(Mandatory)]
  463. [String]$sshHostname,
  464. [Parameter(Mandatory)]
  465. [String]$applicationUser,
  466. [Parameter(Mandatory)]
  467. [String]$command,
  468. [bool]$captureOutput = $false
  469. )
  470. #-##
  471.  
  472. $runResult = RunAsUser $sshHostname $applicationUser $command $captureOutput
  473.  
  474. if($captureOutput -eq $true) {
  475. return $runResult
  476. }
  477. }
  478.  
  479. #-##
  480.  
  481. Set-StrictMode -Version Latest
  482. $ErrorActionPreference = "Stop"
  483.  
  484. ##- Scp.
  485. function Scp {
  486. ##- Parameters.
  487. param (
  488. [Parameter(Mandatory)]
  489. [String]$fileToCopy,
  490. [Parameter(Mandatory)]
  491. [String]$sourceServer,
  492. [Parameter(Mandatory)]
  493. [String]$sourceFolder,
  494. [Parameter(Mandatory)]
  495. [String]$targetServer,
  496. [Parameter(Mandatory)]
  497. [String]$targetFolder,
  498. [Parameter(Mandatory)]
  499. [String]$targetUser
  500. )
  501. #-##
  502.  
  503. Info "Starting to scp."
  504.  
  505. $intermediaryServer = "dummy-server"
  506.  
  507. # Short server name, used as a subfolder in /data/packages on ldps101.
  508. # Example: lcob, lbat, etc.
  509. $serverFolder = $($targetServer -split ".")[0] -replace "[0-9]*", ""
  510. $intermediaryFolder = "/data/packages/${serverFolder}/${targetUser}"
  511. Ssh-Command $intermediaryServer "mkdir -pv ${intermediaryFolder}"
  512.  
  513. Scp-File $fileToCopy $sourceServer $sourceFolder $intermediaryServer $intermediaryFolder
  514.  
  515. Ssh-Command $intermediaryServer "chmod -v ugo+rwx ${intermediaryFolder}/${fileToCopy}"
  516.  
  517. $scpTime = $(Get-Date -format yyyyMMdd)
  518. $targetTmpFolder = "/tmp/${serverFolder}/${targetUser}/${scpTime}"
  519. Ssh-Command $targetServer "mkdir -pv ${targetTmpFolder}"
  520.  
  521. Scp-File $fileToCopy $intermediaryServer $intermediaryFolder $targetServer $targetTmpFolder
  522. Ssh-CommandAsUser $targetServer $targetUser "mkdir -pv ${targetFolder}"
  523. Ssh-CommandAsUser $targetServer $targetUser "cp -v ${targetTmpFolder}/${fileToCopy} ${targetFolder}"
  524. Ssh-Command $targetServer "rm -rvf ${targetTmpFolder}"
  525.  
  526. Info "Finished scping."
  527. }
  528. #-##
  529.  
  530. ##- Backup.
  531. function Backup {
  532. ##- Parameters.
  533. param(
  534. [Parameter(Mandatory)]
  535. [String]$installationFolder,
  536. [Parameter(Mandatory)]
  537. [String]$newArchive,
  538. [Parameter(Mandatory)]
  539. [String]$exclusions,
  540. [Parameter(Mandatory)]
  541. [String]$applicationUser,
  542. [Parameter(Mandatory)]
  543. [String]$targetServer
  544. )
  545. #-##
  546.  
  547. Info "Starting to backup."
  548.  
  549. $tarListCommand = "tar --exclude=`"*/*`" -tvf ${installationFolder}/package-repo/${newArchive}"
  550. $zipListCommand = "zipinfo -1 ${installationFolder}/package-repo/${newArchive} -x `"*/**`""
  551.  
  552. $archiveInfo = @{
  553. ".tar" = @("tar -cvf", $tarListCommand);
  554. ".tar.gz" = @("tar -czvf", $tarListCommand);
  555. ".tar.bz2" = @("tar -cjvf", $tarListCommand);
  556. ".zip" = @("zip -r", $zipListCommand)
  557. }
  558. $index = 0
  559. foreach ($archiveType in $archiveInfo.GetEnumerator()) {
  560. if ($newArchive.EndsWith($archiveType.Name)) {
  561. $archiveListCommand = $archiveType.Value[1]
  562. $newArchiveBasename = $newArchive -replace $archiveType.Name, ""
  563. $archiveFormat = $archiveType.Name
  564. $archiveCommand = $archiveType.Value[0]
  565. } else {
  566. $index += 1
  567. }
  568. }
  569. if($index -ge $archiveInfo.Count) {
  570. ErrorExit "Unsupported archive format: ${newArchive}. Supported formats: tar, tar.gz, tar.bz2, zip."
  571. }
  572.  
  573. $archiveTime = $(Get-Date -format yyyyMMdd)
  574. $archiveName = "${newArchiveBasename}_${archiveTime}.bak${archiveFormat}"
  575.  
  576. $archiveListOutput = Ssh-CommandAsUser $targetServer $applicationUser $archiveListCommand $true
  577. $installationFolderListOutput = Ssh-CommandAsUser `
  578. $targetServer $applicationUser "ls -p1 ${installationFolder}" $true
  579.  
  580. # The files to archive are files that are both in the new tar and in the current installation.
  581. # We don't archive excluded files (temporary files, input files, output files, in general).
  582. $toArchiveList = ""
  583. foreach($archiveListFile in $archiveListOutput.Split("`r`n")) {
  584. $archiveListFile = $archiveListFile.Split(" ")[-1]
  585. if(($installationFolderListOutput.Split("`r`n") -contains $archiveListFile) -and
  586. ($exclusions.Split(",") -notcontains $archiveListFile)) {
  587. $toArchiveList += "$archiveListFile "
  588. }
  589. }
  590.  
  591. if ($toArchiveList -ne " ") {
  592. $archivePath = "${installationFolder}/package-repo/${archiveName}"
  593. $archiveCommand = "${archiveCommand} ${archivePath} ${toArchiveList}"
  594. Ssh-CommandAsUser $targetServer $applicationUser "cd ${installationFolder}; $archiveCommand"
  595. } else {
  596. Warning "Not archiving anything as the list of files to archive was empty."
  597. }
  598.  
  599. $oldBackupsCommand = "ls -1rt ${installationFolder}/package-repo | grep ${Application}"
  600. $oldBackups = Ssh-CommandAsUser $targetServer $applicationUser $oldBackupsCommand $true
  601. $oldBackups = $oldBackups -replace "${env:sshUser}'s password:", ""
  602. $initialOldBackupsList = $oldBackups.Split("`n")
  603.  
  604. # Remove empty lines in the output.
  605. $oldBackupsList = @()
  606. foreach ($oldBackup in $initialOldBackupsList) {
  607. if($oldBackup -ne "") {
  608. $oldBackupsList += $oldBackup
  609. }
  610. }
  611.  
  612. if($oldBackupsList.Count -gt 3) {
  613. # Ignore the last 2 elements: current backup and archive for the new deployment.
  614. $backupsToDelete = $oldBackupsList[0..($oldBackupsList.Count - 3)]
  615.  
  616. $cdCommand = "cd ${installationFolder}/package-repo"
  617. #Ssh-CommandAsUser $targetServer $applicationUser "${cdCommand}; rm -v ${backupsToDelete}"
  618. }
  619.  
  620. Info "Finished backing up."
  621. }
  622. #-##
  623.  
  624. ##- Clean.
  625. function Clean {
  626. ##- Parameters.
  627. param(
  628. [Parameter(Mandatory)]
  629. $targetFolder,
  630. [Parameter(Mandatory)]
  631. $applicationUser,
  632. [Parameter(Mandatory)]
  633. $targetServer
  634. )
  635. #-##
  636.  
  637. Info "Starting to clean."
  638.  
  639. $cleanCommand = "rm -rfv ${targetFolder}"
  640. Ssh-CommandAsUser $targetServer $applicationUser $cleanCommand
  641.  
  642. Info "Finished cleaning."
  643. }
  644. #-##
  645.  
  646. ##- Unpack.
  647. function Unpack {
  648. ##- Parameters.
  649. param(
  650. [Parameter(Mandatory)]
  651. $archiveName,
  652. [Parameter(Mandatory)]
  653. $installationFolder,
  654. [Parameter(Mandatory)]
  655. $applicationUser,
  656. [Parameter(Mandatory)]
  657. $targetServer
  658. )
  659. #-##
  660.  
  661. Info "Starting to unpack."
  662.  
  663. $archiveInfo = @{
  664. ".tar" = @("tar -xvf", "-C");
  665. ".tar.gz" = @("tar -xzvf", "-C");
  666. ".tar.bz2" = @("tar -xjvf", "-C");
  667. ".zip" = @("unzip -o", "-d")
  668. }
  669. $index = 0
  670. foreach ($archiveType in $archiveInfo.GetEnumerator()) {
  671. if ($archiveName.EndsWith($archiveType.Name)) {
  672. $unpackCommand = $archiveType.Value[0]
  673. $unpackFolderFlag = $archiveType.Value[1]
  674. $archiveUnpackCommand = "${unpackCommand} " +
  675. "${installationFolder}/package-repo/${archiveName} " +
  676. "${unpackFolderFlag} ${installationFolder}"
  677. } else {
  678. $index += 1
  679. }
  680. }
  681. if($index -ge $archiveInfo.Count) {
  682. ErrorExit "Unsupported archive format: ${archiveName}. Supported formats: tar, tar.gz, tar.bz2, zip."
  683. }
  684.  
  685. Ssh-CommandAsUser $targetServer $applicationUser $archiveUnpackCommand
  686.  
  687. Info "Finished unpacking."
  688. }
  689. #-##
  690.  
  691. Set-StrictMode -Version Latest
  692. $ErrorActionPreference = "Stop"
  693.  
  694. ##- Download-Folder.
  695. function Download-Folder {
  696. ##- Parameters.
  697. param (
  698. [Parameter(Mandatory)]
  699. [String]$sourceServer,
  700. [Parameter(Mandatory)]
  701. [String]$sourceUser,
  702. [Parameter(Mandatory)]
  703. [String]$sourceFolder,
  704. [String]$exclusions = "dummy-exclusion",
  705. [Parameter(Mandatory)]
  706. [String]$targetFolder
  707. )
  708. #-##
  709.  
  710. Info "Starting to download folder."
  711.  
  712. $archiveTime = $(Get-Date -format yyyyMMdd)
  713. $temporaryFolder = "/tmp/${sourceUser}${archiveTime}"
  714. Ssh-CommandAsUser $sourceServer $sourceUser "mkdir -pv ${temporaryFolder}"
  715.  
  716. $archiveCommand = "tar -czvf ${temporaryFolder}/archive.tar.gz ${sourceFolder}"
  717. Ssh-CommandAsUser $sourceServer $sourceUser $archiveCommand
  718.  
  719. Local-Scp "archive.tar.gz" $sourceServer $temporaryFolder $targetFolder
  720.  
  721. Ssh-CommandAsUser $sourceServer $sourceUser "rm -rvf ${temporaryFolder}"
  722.  
  723. Info "Finished downloading."
  724. }
  725. #-##
  726.  
  727. ##- Setup-Cobol
  728. function Setup-Cobol {
  729. ##- Parameters.
  730. param (
  731. [Parameter(Mandatory)]
  732. [ValidateSet("test", "hom1", "hom2", "hom3")]
  733. [String]$environment,
  734. [Parameter(Mandatory)]
  735. [String]$cobolPackageInfo
  736. )
  737. #-##
  738.  
  739. Info "Creating UC4 Cobol deployment package."
  740.  
  741. $cobolFolder = "T:PublicDEPLOYMENTCIBLE"
  742. #$cobolFolder = "Z:worktmpuc4"
  743. $cobolCsv="${cobolFolder}packages_deployment_UC4T.csv"
  744.  
  745. $environment = $environment.ToUpper()
  746. $cobolDate = $(Get-Date -format yyyyMMdd)
  747. $cobolPackageInfo = $cobolPackageInfo.Replace("date_of_delivery(YYYYMMDD)", $cobolDate)
  748. $cobolPackageInfo += ";$environment"
  749. $cobolPackageInfo = $cobolPackageInfo -replace "`r`n", ""
  750.  
  751. Info "Will write ${cobolPackageInfo} to ${cobolCsv}."
  752.  
  753. if(Test-Path $cobolCsv) {
  754. ErrorExit "Cobol file already exists, aborting."
  755. }
  756.  
  757. try {
  758. New-Item -ItemType Directory $cobolFolder
  759. } catch {
  760. }
  761.  
  762. $encoding = New-Object Text.AsciiEncoding
  763. $writer = New-Object IO.StreamWriter($cobolCsv, $false, $encoding)
  764. $writer.Write("${cobolPackageInfo}`n")
  765. $writer.Close()
  766.  
  767. Info "Wrote ${cobolPackageInfo} to ${cobolCsv}."
  768. }
  769. #-##
  770.  
  771. ##- Create-Branch
  772. function Create-Branch {
  773. ##- Parameters.
  774. param (
  775. [Parameter(Mandatory)]
  776. [String]$branchName
  777. )
  778. #-##
  779.  
  780. Info "Creating SVN branch."
  781.  
  782. $env:sshUser = getUser
  783. $env:password = getPassword
  784. $sshHostname = "dummy-server"
  785. $svnScript = "/home/dummy-user/utilities/svn.sh"
  786.  
  787. Ssh-Command -sshHostname $sshHostname -command "${svnScript} branch ${branchName} HEAD trunk"
  788.  
  789. Info "Finished creating SVN branch."
  790. }
  791. #-##
  792.  
  793. ##- Install-Script
  794. function Install-Script {
  795. ##- Parameters.
  796. param (
  797. [ValidateSet("dev", "test", "test2", "hom1", "hom2", "hom3", "sup", "prod")]
  798. [String]$environment = "test",
  799. [Parameter(Mandatory)]
  800. [String]$project,
  801. [String]$tnsString = "dummy-tns",
  802. [String]$user = "designer",
  803. [Parameter(Mandatory)]
  804. [String]$archive
  805. )
  806. #-##
  807.  
  808. Info "Installing SQL script."
  809.  
  810. $env:password = getPassword
  811.  
  812. # The environment should actually be uppercase, especially the directories.
  813. $environment = $environment.ToUpper()
  814.  
  815. if ($environment -eq "PROD") {
  816. Warning "Running on production, are you sure you want to run the script?"
  817. $production = Read-Host -Prompt "Enter `"PROD`" if you want to continue: "
  818. if ($production -ne "PROD") {
  819. ErrorExit "Production run cancelled by user."
  820. }
  821. }
  822.  
  823. $installDate = $(Get-Date -format yyyyMMdd)
  824.  
  825. $targetRootDir = "T:PhoenixITC-PRD-TSM1. Environnements11. DataChange"
  826. #$targetRootDir = "Z:worktmp"
  827.  
  828. $sourceRootDir = "Z:Downloads"
  829. $scriptDir = ${archive} -replace ".zip", ""
  830. $scriptVersion = 1
  831. $unversionedDir = "${targetRootDir}/${environment}/${project}/${installDate}/${scriptDir}"
  832. $targetDir="${unversionedDir}_${scriptVersion}"
  833.  
  834. while (Test-Path "${unversionedDir}_${scriptVersion}") {
  835. $scriptVersion += 1
  836. $targetDir="${unversionedDir}_${scriptVersion}"
  837. }
  838.  
  839. New-Item -ItemType Directory -Force -Verbose -Path $targetDir | Out-Null
  840. $originalLocation = Get-Location
  841. Set-Location -Verbose $targetDir
  842. Move-Item -verbose "${sourceRootDir}/${archive}" "${targetDir}"
  843. #Copy-Item -Verbose "${sourceRootDir}/${archive}" "${targetDir}"
  844.  
  845. Info "Unpacking SQL script archive."
  846. unzip.exe -o $archive
  847. if($LastExitCode -ne 0) {
  848. ErrorExit "Unzip failed with exit code: ${LastExitCode}"
  849. }
  850. Info "Finished unpacking SQL script archive."
  851.  
  852. $installScripts = Get-ChildItem "*instal*.sql" | Select -expand Name
  853. if(!$installScripts) {
  854. ErrorExit "No SQL install scripts found, aborting."
  855. }
  856. foreach($installScript in $installScripts) {
  857. Info "sqlplus ${user}/{env:password}@`"${tnsString}`" @${installScript}"
  858. Write-Output exit | sqlplus.exe ${user}/${env:password}@"${tnsString}" @$installScript
  859. if($LastExitCode -ne 0) {
  860. ErrorExit "SqlPlus failed with exit code: ${LastExitCode}"
  861. }
  862. }
  863.  
  864. $installLogs = Get-ChildItem "*.log" | Select -expand Name
  865. $timestampedLog = ""
  866. $timestampedLogNames = ""
  867. foreach($installLog in $installLogs) {
  868. $timestampedLog = $installLog -replace ".log", ""
  869. $timestampedLog += "${environment}_${installDate}_${scriptVersion}.log"
  870.  
  871. Move-Item -Verbose $installLog $timestampedLog
  872. $timestampedLogNames += $timestampedLog
  873. }
  874.  
  875. # Put log file name in the Windows clipboard.
  876. Write-Output $timestampedLogNames | clip.exe
  877.  
  878. # Open Windows Explorer with the log already selected.
  879. try {
  880. Get-Command explorer.exe | Out-Null
  881. explorer.exe "/e,/select,`"${timestampedLog}`""
  882. if($LastExitCode -ne 0) {
  883. ErrorExit "Explorer failed with exit code: ${LastExitCode}"
  884. }
  885. } catch {
  886. ErrorExit "Explorer not found?!?"
  887. }
  888.  
  889. Set-Location -verbose $originalLocation
  890.  
  891. Info "Finished installing SQL script."
  892. }
  893. #-##
  894.  
  895. ##- Wait
  896. function Wait {
  897. Info "Press any key to continue."
  898. $host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") | Out-Null
  899. Info "Key pressed, continuing."
  900. }
  901. #-##
  902.  
  903. $SOURCE_SERVER="dummy-server"
  904. $ARCHIVE_NAME="test-app-1.0.0.tar.gz"
  905. $APPLICATION_FOLDER="test-app"
  906. $INSTALLATION_FOLDER="/home/dummy-user"
  907. $INSTALLATION_SERVER="dummy-server"
  908. $SU_USER="dummy-user"
  909.  
  910. # Configuration values for the scp command.
  911. $SCP_FILE_TO_COPY=${ARCHIVE_NAME}
  912. $SCP_SOURCE_FOLDER="${INSTALLATION_FOLDER}/todeploy"
  913. $SCP_TARGET_FOLDER="${INSTALLATION_FOLDER}/package-repo"
  914. $SCP_SOURCE_SERVER=${SOURCE_SERVER}
  915. $SCP_TARGET_SERVER=${INSTALLATION_SERVER}
  916. $SCP_TARGET_USER=${SU_USER}
  917.  
  918. # Configuration values for the archive command.
  919. $BACKUP_INSTALLATION_FOLDER=${INSTALLATION_FOLDER}
  920. $BACKUP_NEW_ARCHIVE=${ARCHIVE_NAME}
  921. $BACKUP_EXCLUSIONS="dummy-exclusion"
  922. $BACKUP_APPLICATION_USER=${SU_USER}
  923. $BACKUP_TARGET_SERVER=${INSTALLATION_SERVER}
  924.  
  925. # Configuration values for the clean command.
  926. $CLEAN_TARGET_FOLDER="${INSTALLATION_FOLDER}/${APPLICATION_FOLDER}"
  927. $CLEAN_APPLICATION_USER=${SU_USER}
  928. $CLEAN_TARGET_SERVER=${INSTALLATION_SERVER}
  929.  
  930. # Configuration values for the deploy command.
  931. $UNPACK_INSTALLATION_FOLDER=${INSTALLATION_FOLDER}
  932. $UNPACK_ARCHIVE_NAME=${ARCHIVE_NAME}
  933. $UNPACK_APPLICATION_USER=${SU_USER}
  934. $UNPACK_TARGET_SERVER=${INSTALLATION_SERVER}
  935.  
  936. Scp $SCP_FILE_TO_COPY $SCP_SOURCE_SERVER $SCP_SOURCE_FOLDER `
  937. $SCP_TARGET_SERVER $SCP_TARGET_FOLDER $SCP_TARGET_USER
  938.  
  939. Backup $BACKUP_INSTALLATION_FOLDER $BACKUP_NEW_ARCHIVE $BACKUP_EXCLUSIONS `
  940. $BACKUP_APPLICATION_USER $BACKUP_TARGET_SERVER
  941.  
  942. Clean $CLEAN_TARGET_FOLDER $CLEAN_APPLICATION_USER $CLEAN_TARGET_SERVER
  943.  
  944. Unpack $UNPACK_ARCHIVE_NAME $UNPACK_INSTALLATION_FOLDER `
  945. $UNPACK_APPLICATION_USER $UNPACK_TARGET_SERVER
  946.  
  947. Invoke-Expression ".commandsscp.ps1"
  948. Invoke-Expression ".commandsbackup.ps1"
  949. Invoke-Expression ".commandsunpack.ps1"
  950.  
  951. Invoke-Expression ".commandsscp.ps1"
  952. Invoke-Expression ".commandsbackup.ps1"
  953. Invoke-Expression ".commandsunpack.ps1"
  954.  
  955. Invoke-Expression ".commandsscp.ps1"
  956. Invoke-Expression ".commandsbackup.ps1"
  957. Invoke-Expression ".commandsclean.ps1"
  958. Invoke-Expression ".commandsunpack.ps1"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement