Advertisement
Guest User

Untitled

a guest
Sep 1st, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.87 KB | None | 0 0
  1. # Billing-Subscriptions runbook
  2. # Version 0.7
  3.  
  4. workflow Billing-Subscriptions
  5. {
  6. param
  7. (
  8. [Parameter(Mandatory=$false)]
  9. [String] $SubscriptionID,
  10. [Parameter(Mandatory=$true)]
  11. [String] $VMMJOBID
  12. )
  13.  
  14. # Connection to access VMM server.
  15. $VmmConnection = Get-AutomationConnection -Name 'VmmConnection'
  16. $VmmServerName = $VmmConnection.ComputerName
  17.  
  18. $SecurePassword = ConvertTo-SecureString -AsPlainText -String $VmmConnection.Password -Force
  19. $VmmCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $VmmConnection.Username, $SecurePassword
  20.  
  21. # Connection data to access MsSQL server.
  22. $MsSQLCred = Get-AutomationPSCredential -Name 'MsSQL-BillingDB'
  23. [string] $MsSQLLogin = $MsSQLCred.Username
  24. $MsSQLPassword = $MsSQLCred.Password
  25. [string] $MsSQLDatabase = Get-AutomationVariable -Name 'MsSQL-Billing-Database'
  26. [string] $MsSQLServer = Get-AutomationVariable -Name 'MsSQL-Billing-Server'
  27.  
  28.  
  29. inlinescript {
  30.  
  31. Write-output "Start Inline"
  32.  
  33. # Import VMM module.
  34. Import-Module virtualmachinemanager
  35.  
  36. # Connect to VMM server.
  37. Get-SCVMMServer -ComputerName $Using:VmmServerName -ForOnBehalfOf
  38.  
  39. ### VARS DB Settings
  40. $SQLserver = $USING:MsSQLServer
  41. $SQLDatabase = $USING:MsSQLDatabase
  42. $SQLuser = $USING:MsSQLLogin
  43. $SQLSecurePassword = $USING:MsSQLPassword
  44. # We need unsecure password to connect DB
  45. $SQLBSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SQLSecurePassword)
  46. $SQLUnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($SQLBSTR)
  47.  
  48. ### MsSQL CONNECTION
  49. $Connection = New-Object System.Data.SQLClient.SQLConnection
  50. $Connection.ConnectionString = "Server = '$SQLServer';database='$SQLDatabase'; User ID = '$SQLuser'; Password = '$SQLUnsecurePassword';trusted_connection=true; Integrated Security=false"
  51. $Connection.Open()
  52. $Command = New-Object System.Data.SQLClient.SQLCommand
  53. $Command.Connection = $Connection
  54. $dataTable = New-Object -TypeName System.Data.DataTable
  55. ###
  56.  
  57. # if vmmjobid eq 0 - it sheduled task
  58.  
  59. if ($USING:vmmjobid -ne "0") {
  60.  
  61. $job = Get-SCJob -ID $USING:vmmjobid
  62.  
  63. ## Check Job Status
  64.  
  65. $JobStatus=$Job.Status
  66.  
  67. #Wait Until Task Completed
  68. while ($JobStatus -eq "Running") {
  69. write-output "Start Sleep"
  70. start-sleep 5
  71. $JobStatus=$Job.Status
  72. }
  73. #Test Job Result
  74. if ($JobStatus -eq "Failed") {
  75. write-output "Job Failed!"
  76. write-output JOBid:$job.ID
  77. break
  78. }
  79.  
  80. $Owner = $Job.Owner
  81. write-output $Owner
  82.  
  83. } else {
  84.  
  85. $owner = $USUNG:SubscriptionID #if $SubscriptionID eq $null - $owner eq $null too
  86. $TaskType = "Sheduled"
  87.  
  88. }
  89.  
  90. function GetVmHdd(){
  91.  
  92. $VHDs=Get-SCVirtualHardDisk -VM $vm
  93.  
  94. #OBJ When we will return (Size in MB)
  95. $VHD_Prop = @{'VHD_Count'=0;'VHD_STD_SIZE'=0;'VHD_FAST_Size'=0;'VHD_Ultra_Size'=0}
  96. $VHD_Return = New-Object –TypeName PSObject -Property $VHD_Prop
  97.  
  98. #OBJ Internal
  99. $VHD_Work = "" | SELECT VHD_STD_List,VHD_FAST_List,VHD_ULTRA_List
  100.  
  101. $VHD_Return.VHD_Count = ($VHDs).Count
  102.  
  103. # Looking for disk in SQL
  104.  
  105. foreach ($VHD in $VHDs) {
  106.  
  107. [string]$StorageType = $NULL #Clearing var
  108.  
  109. ### Get Disk Storage Type
  110. $SqlQuery = "SELECT StorageType FROM Disks WHERE DiskID like '"+$VHD.ID+"'"
  111. $Command.CommandText = $SqlQuery
  112. $result = $command.ExecuteReader()
  113. $dataTable.Load($result)
  114. $StorageType = $dataTable.StorageType
  115. $datatable.Clear()
  116. $result.Close()
  117. ###
  118.  
  119. ### Calculating Summary Storage Usage
  120.  
  121. if ($StorageType -eq "Standard" -OR $StorageType -eq "" -OR $StorageType -eq "System") {
  122.  
  123. $VHD_Return.VHD_STD_SIZE+=($VHD.MaximumSize/1048576) #Add Standard Disk Size in MB
  124.  
  125. }
  126.  
  127. if ($StorageType -eq "Fast") {
  128.  
  129. $VHD_Return.VHD_FAST_SIZE+=($VHD.MaximumSize/1048576) #Add Fast Disk Size in MB
  130.  
  131. }
  132.  
  133. if ($StorageType -eq "Ultra") {
  134.  
  135. $VHD_Return.VHD_ULTRA_SIZE+=($VHD.MaximumSize/1048576) #Add Ultra Disk Size in MB
  136.  
  137. }
  138.  
  139. }
  140.  
  141. return $VHD_Return
  142. }
  143.  
  144. function WriteDataToDB() {
  145.  
  146. $Command.CommandText = "INSERT INTO Subscriptions (timestamp, SubscriptionID, Name, CPU, RAM, VHDStd, VHDFast, VHDUltra, WindowsVM, IPAddress, TaskType, Date) `
  147. VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')" `
  148. -f $timestamp, $Role.ID, $Role.Name, $SummRes.SummCPU, $SummRes.SummRAM, $SummRes.SummVHDStd, $SummRes.SummVHDFast, $SummRes.SummVHDUltra, $SummRes.SummOSWindows, $SummRes.SummExtAddr, $TaskType, $Date
  149.  
  150. $Command.ExecuteNonQuery() | out-null
  151.  
  152. #Debug
  153. #write-Output $Role.ID $Role.Name $SummRes.SummCPU $SummRes.SummRAM $SummRes.SummVHDStd $SummRes.SummVHDFast $SummRes.SummVHDUltra $SummRes.SummOSWindows $SummRes.SummExtAddr $TaskType
  154.  
  155. }
  156.  
  157. #Start task for correcting subscriprion data (if VM stopped from OS)
  158. if ($TaskType -eq "Sheduled") {
  159.  
  160. $jobs = Get-ScJob -Newest 1| ? Name -eq "Refresh Virtual Machine State" #Get all update Jobs Lash hour
  161.  
  162. foreach ($job in $jobs) {
  163. $fulljob = Get-job -job $job -full
  164.  
  165. if (($fulljob.AuditRecords.new).Value -eq "Stopped") { # If VM Stopped
  166.  
  167. $VMid = ($fulljob.AuditRecords.objectdata).ID
  168. $VM = Get-SCVirtualMachine -ID $VMid
  169.  
  170. if ($VM.UserRole.ToString() -ne "Administrator") { #It not Administrator VMs
  171.  
  172. $Role = Get-ScUserRole -ID $VM.UserRoleID
  173.  
  174. $SummRes = "" | SELECT SummCPU, SummRAM, SummVHDStd, SummVHDFast, SummVHDUltra, SummOSWindows, SummExtAddr
  175.  
  176. #If user stopeed VM - CPU and RAM usage == 0, so we should show it in billing
  177. $SummRes.SummCPU = $VM.CPUCount*(-1)
  178. $SummRes.SummRAM = $VM.Memory*(-1)
  179.  
  180. $TaskType = "Correcting"
  181.  
  182. #Job end time to Unix time
  183. $BigBang = Get-Date -Date "01/01/1970"
  184. (New-TimeSpan -Start $BigBang -End $job.EndTime).TotalSeconds
  185. $timestamp = (Get-Date).ToFileTime()
  186.  
  187. $date = '{0:s}' -f $job.EndTime
  188.  
  189. WriteDataToDB
  190.  
  191. }
  192. }
  193. }
  194.  
  195. $Role = $NULL
  196. $TaskType = "Sheduled"
  197.  
  198. }
  199.  
  200. #Get all owner subscriptions
  201. $Roles = Get-SCUserRole | ? {$_.Name -like "$owner*" -AND $_.Name -ne "Administrator"}
  202.  
  203. foreach ($Role in $Roles) {
  204.  
  205. $VMs = Get-SCVirtualMachine | ? UserRoleID -eq $Role.ID #Get VMs for Subscription
  206.  
  207. ###$Userrole = Get-SCUserRole -ID $Role.ID -VMMServer $SCVMMSERVER
  208.  
  209. ###$VMs =Get-SCVirtualMachine -OnBehalfOfUserRole $Userrole -OnBehalfOfUser $Userrole.Name -VMMServer $SCVMMSERVER #Get VMs for Subscription
  210.  
  211. if ($VMs) {
  212.  
  213. $SummRes = "" | SELECT SummCPU, SummRAM, SummVHDStd, SummVHDFast, SummVHDUltra, SummOSWindows, SummExtAddr
  214.  
  215. Foreach ($VM in $VMs) {
  216.  
  217. #Get HDD_Count, HDD_Std, HDD_Fast, HDD_Ultra and SUMM
  218. $VHD_ARR = GetVMHdd
  219. $SummRes.SummVHDStd += $VHD_ARR.VHD_STD_SIZE
  220. $SummRes.SummVHDFast += $VHD_ARR.VHD_FAST_Size
  221. $SummRes.SummVHDUltra += $VHD_ARR.VHD_Ultra_Size
  222. #
  223.  
  224. #$HDD_ARR #Debug
  225.  
  226. # If VM Status eq Stopeed - set CPU and RAM usage = "0"
  227.  
  228. if ($vm.Status -eq "Stopped" -OR $vm.Status -eq "PowerOff") {
  229.  
  230. $CPUCount = 0
  231. $Memory = 0
  232.  
  233. } else {
  234.  
  235. $CPUCount = $VM.CPUCount
  236. $Memory = $VM.Memory
  237.  
  238. }
  239.  
  240. #SUMM CPU and RAM Usage
  241. $SummRes.SummCPU += $CPUCount
  242. $SummRes.SummRAM += $Memory
  243.  
  244. # Summ Windows VMs
  245. if ($VM.OperatingSystem.Name -like "*windows*") {
  246.  
  247. $SummRes.SummOSWindows += 1
  248.  
  249. }
  250.  
  251. }
  252.  
  253. if (!$SummRes.SummOSWindows) { $SummRes.SummOSWindows = 0 }
  254.  
  255. # Get External IPs Usage
  256.  
  257. $SummRes.SummExtAddr = 0
  258.  
  259. $Networks = Get-SCVMNetwork | ? {$_.UserRoleId -eq $Role.ID -AND $_.VMNetworkGateways -ne $null }
  260.  
  261. if ($Networks) {
  262.  
  263. foreach ($Network in $Networks) {
  264.  
  265. $GW = Get-SCVMNetworkGateway -VMNetwork $Network
  266. $IPs = (Get-SCNATConnection -VMNetworkGateway $GW).Count
  267. $SummRes.SummExtAddr += $IPs
  268.  
  269. }
  270.  
  271. }
  272. $timestamp = Get-Date -UFormat %s
  273. $date = Get-Date -Format s
  274.  
  275. WriteDataToDB
  276.  
  277. }
  278. }
  279.  
  280. #CLOSE DB Connection
  281. $Connection.Close()
  282.  
  283. } -PSComputerName $VmmServerName -PSCredential $VmmCredential
  284.  
  285. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement