Shutting down and draining sessions on AWS machines in RDS farm

Posted on Sat 12 December 2015 in MS RDS on AWS • 5 min read

  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
<#
.SYNOPSIS
Function for writing the log
#>
Function Write-Log
{
  Param(
      [int]$level
  ,   [string]$Message
  ,   [ValidateSet("Info", "Warning", "Error")][string]$severity = 'Info'
  ,   [string]$logname = $rdslog
  ,   [string]$color = "white"
  )
  $time = get-date
  Add-Content $logname -value ("{0} - [{1}] {2}" -f $time, $severity, $Message)
  if ($interactive) {
      switch ($severity)
      {
          'Error' {$color = 'Red'}
          'Warning' {$color = 'Yellow'}
      }
      if ($level -le $VerboseLogging)
      {
          if ($color -match "Red|Yellow")
          {
              Write-Host ("{0} - [{1}] {2}" -f $time, $severity, $Message)
              -ForegroundColor $color -BackgroundColor Black
              if ($severity -eq 'Error') {

                  throw $Message
              }
          }
          else
          {
              Write-Host ("{0} - [{1}] {2}" -f $time, $severity, $Message) -ForegroundColor $color
          }
      }
  }
  else
  {
      switch ($severity)
      {
          'Info' {Write-Verbose -Message $Message}
          'Warning' {Write-Warning -Message $Message}
          'Error' {
              throw $Message
          }
      }
  }
}

<#
.SYNOPSIS
Function for writing the usage log
#>
Function Write-UsageLog
{
  Param(
      [string]$collectionName,
      [int]$corecount,
      [int]$vmcount,
      [string]$logfilename=$rdsusagelog
  )
  $time=get-date
  Add-Content $logfilename -value ("{0}, {1}, {2}, {3}" -f $time, $collectionName,
  $corecount, $vmcount)
}

Function Get-InstancesInCollection{
<#
.SYNOPSIS
Gets instances in collection
.DESCRIPTION
Get instances to be used in start/stop processing
.EXAMPLE
$getInstancesInCollection = Get-InstancesInCollection

The code for the instance state, as a 16-bit unsigned integer. The high byte is an
opaque internal value and should be ignored. The low byte is set based on the state represented.
The valid values are 0 (pending), 16 (running), 32 (shutting-down), 48 (terminated),
64 (stopping), and 80 (stopped).
#>
  begin {
      Import-Module -Name RemoteDesktop

      $ConnectionBrokerFQDN = "rdcb.example.lan"
      $Collections=Get-RDSessionCollection -ConnectionBroker $ConnectionBrokerFQDN
      -ErrorAction Continue
      Set-DefaultAWSRegion eu-central-1
      $RDHosts = Get-RDSessionHost -CollectionName Collection1 -ConnectionBroker
      $ConnectionBrokerFQDN -ErrorAction Continue
      $CollectionUserSessions=Get-RDUserSession -ConnectionBroker $ConnectionBrokerFQDN
      -CollectionName $collection.CollectionName -ErrorAction Continue
      $CollectionTS = Get-RDUserSession -ConnectionBroker $ConnectionBrokerFQDN -CollectionName
      Collection1 -ErrorAction Continue
      $CollectionTSSortUnique = $CollectionTS | Group-Object HostServer
  }
  process{
      write-verbose "Getting instances"
      $awsCollection = @()
      foreach($cols in $CollectionTS) {
          $aws = New-Object -TypeName PSObject
          $instance = Get-EC2Instance -Filter @( @{name='tag:Name'; values=$cols.HostServer};
              @{name='instance-state-code'; values = 16} )
          | Select-Object -ExpandProperty instances
          $aws | Add-Member -Type NoteProperty
          -Name InstanceId -Value $instance.instanceId
          $aws | Add-Member -Type NoteProperty
          -Name HostServer -Value $cols.HostServer
          $aws | Add-Member -Type NoteProperty
          -Name UserName -Value $cols.UserName
          $awsCollection += $aws
      }
      return $awsCollection
  }
}
Function Get-EmptyInstancesInCollection{
<#
.SYNOPSIS
Gets empty instances in collection
.DESCRIPTION
Get empty instances to be used in start/stop processing
.EXAMPLE
$getEmpty = Get-EmptyInstancesInCollection
#>


  begin {
      Import-Module -Name RemoteDesktop
      $ConnectionBrokerFQDN = "rdcb.example.lan"
      $Collections=Get-RDSessionCollection -ConnectionBroker $ConnectionBrokerFQDN
      -ErrorAction Continue
      Set-DefaultAWSRegion eu-central-1
      $RDHosts = Get-RDSessionHost -CollectionName Collection1 -ConnectionBroker
      $ConnectionBrokerFQDN -ErrorAction Continue
      $CollectionUserSessions=Get-RDUserSession -ConnectionBroker $ConnectionBrokerFQDN
      -CollectionName $collection.CollectionName -ErrorAction Continue
      $CollectionTS = Get-RDUserSession -ConnectionBroker $ConnectionBrokerFQDN -CollectionName
      Collection1 -ErrorAction Continue
      $CollectionTSSortUnique = $CollectionTS | Group-Object HostServer
  }
  process{
      $emptyCollection = @()
      $RDHGroup = $RDHosts | Group-Object -Property SessionHost
      $CollectionTSGroup = $CollectionTS | Group-Object -Property HostServer
      $CompareItems = Compare-Object $RDHGroup $CollectionTSGroup -IncludeEqual
      $SelectInstancesWithUsers = Get-InstancesInCollection | Select-Object HostServer
      foreach($ci in $CompareItems){
          if(($ci | Select-Object -ExpandProperty SideIndicator) -eq "<="){
              $realVal = $ci | Select-Object -ExpandProperty InputObject | Select-Object Name
              $emptycoll = New-Object -TypeName PSObject
              $emptycoll | Add-Member -Type NoteProperty
              -Name HostServer -Value $realVal[0].Name

              $emptyCollection += $emptycoll
          }

      }
      return $emptyCollection
  }
}


<#
.SYNOPSIS
Function for creating variable from XML
#>
Function Set-ScriptVariable ($Name,$Value)
{
  Invoke-Expression ("$Script:" + $Name + " = "" + $Value + """)
}


<#
.SYNOPSIS
Function for schedulaing start-stop of EC2 instances and setting RD Hosts
in drain mode according to number of users.
#>
Function SuperSizeMe{

  begin {
      Import-Module -Name RemoteDesktop
      $getEmpty = Get-EmptyInstancesInCollection
      #$CurrentPath=Split-Path $script:MyInvocation.MyCommand.Path
      $CurrentPath ="."
      #XMl Configuration File Path
      $XMLPath = "$CurrentPath\schedule.xml"

      #Log path
      $rdslog="$CurrentPath\RDSScale.log"

      #usage log path
      $rdsusagelog="$CurrentPath\RDSUsage.log"


      ###### Verify XML file ######
      If (Test-Path $XMLPath) {
          write-verbose "Found $XMLPath"
          write-verbose "Validating file..."
          try {
              $Variable = [XML] (Get-Content $XMLPath)
          }
          catch {
              $Validate = $false
              Write-Error "$XMLPath is invalid. Check XML syntax - Unable to proceed"
              Write-Log 3 "$XMLPath is invalid. Check XML syntax - Unable to proceed" "Error"
              exit 1
          }
      }
      Else {
          $Validate = $false
          write-error "Missing $XMLPath - Unable to proceed"
          Write-Log 3 "Missing $XMLPath - Unable to proceed" "Error"
          exit 1
      }

      ##### Load XML Configuration values as variables #########
      Write-Verbose "loading values from Config.xml"
      $Variable=[XML] (Get-Content "$XMLPath")
      $Variable.RDSScale.RDSScaleSettings | ForEach-Object {$_.Variable} | Where-Object
      {$_.Name -ne $null} | ForEach-Object {Set-ScriptVariable -Name $_.Name -Value $_.Value}
  }


  process{
      #Construct Begin time and End time for the Peak period
      $CurrentDateTime=Get-Date
      $BeginPeakDateTime=[DateTime]::Parse($CurrentDateTime.ToShortDateString()+' '+$BeginPeakTime)
      $EndPeakDateTime=[DateTime]::Parse($CurrentDateTime.ToShortDateString()+' '+$EndPeakTime)

      #get the available collections in the RDS
      try{
          $Collections=Get-RDSessionCollection -ConnectionBroker $ConnectionBrokerFQDN -ErrorAction Continue
      }
      catch
      {
          Write-Log 1 "Failed to retrieve RDS collections: $($_.exception.message)" "Error"
          Exit 1
      }
      #check the number of running session hosts
      $collectiongroup = ($CollectionUserSessions) |Group HostServer| Sort-Object count
      $numberOfRunningHost=$collectiongroup.Length

      if($CurrentDateTime -gt $BeginPeakDateTime -and $CurrentDateTime -lt $EndPeakDateTime){
          echo "Peak time baby!"
          if($numberOfRunningHost -lt $MaximumNumberOfInstances){
          try{
              foreach($cols in $CollectionTS) {
                  $instance = Get-EC2Instance -Filter @( @{name='tag:Name'; values=$cols.HostServer};
                          @{name='instance-state-code'; values = 80} )
                      | Select-Object -ExpandProperty instances

                  Start-EC2Instance -InstanceId $instance.InstanceId
              }
          } catch{
                  write-log 1 "Failed to start EC2 instance $($_.exception.message)" "Error"
                  Exit 1
              }
          }
      }
      if($CurrentDateTime -lt $BeginPeakDateTime -and $CurrentDateTime -gt $EndPeakDateTime ){
          #Stop some instances

          foreach($ge in $getEmpty){
              $instance = Get-EC2Instance -Filter @( @{name='tag:Name'; values=$ge.HostServer};
                      @{name='instance-state-code'; values = 16} )
                  | Select-Object -ExpandProperty instances
              try{
                  Stop-EC2Instance -Instance $instance.InstanceId
              }
              catch {
                  write-log $($_.exception.message)
              }
          }
          echo "Before peak time"
          if($numberOfRunningHost -ge $MaximumNumberOfInstances -and $numberOfRunningHost
          -gt $MinimumNumberOfInstances){
              $sortToKill = Get-InstancesInCollection | Group-Object HostServer | Sort-Object count
              echo $sortToKill[0]
                  try{
                  Set-RDSessionHost -SessionHost $sortToKill[0].Name -NewConnectionAllowed
                  NotUntilReboot -ConnectionBroker $ConnectionBrokerFQDN -ErrorAction Continue
              }
              catch{
                  write-log 1 "Failed to set drain mode on session host: $($sortToKill[0].Name)
                  with error: $($_.exception.message)" "Error"
                  Exit 1
              }
          }
      }
  }
}

It will parse an XML file, which you could easily switch out with anything else, and then use the values for peak time and so on to scale.