'Use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm

Option Explicit
'##################################################################################
'GLOBAL DECLARATIONS - MODIFY ACCORDING TO YOUR ENVIRONMENT
'CLUSTER GROUP WHICH CONTAINS MIIS SQL AND SCRIPT RESOURCES
Dim miisgroup
miisgroup = "miis"
Dim miisServiceAccount
miisServiceAccount = "fabrikam\miissrvc"
Dim miisServiceAccountPwd
miisServiceAccountPwd = "pass@word2"
Dim miisEncryptKey
miisEncryptKey = "c:\miiskey\key.bin"
Dim miisServiceStartupTime  'time in seconds for MIIS Service to come up
miisServiceStartupTime = 170

'###################################################################################
Dim activeNode
Dim prefferedOwners
Dim miisActivateCmd


Function Open()
Dim WshNetwork

 Resource.LogInformation("Entering Open() for group" & Resource.Name)
 Set WshNetwork = CreateObject("WSCript.Network")
 activeNode = WshNetwork.ComputerName
 prefferedOwners = GetPrefferedOwners()
 miisActivateCmd = "miisactivate " & miisEncryptKey & " " & miisServiceAccount & " " & miisServiceAccountPwd & " /q"
 Resource.LogInformation("MIISActivate Command - " & miisActivateCmd)
 Open = True
 
End Function

Function Online( )
Dim Node
Dim WshShell
Dim oExec
Dim oWait

   
       Resource.LogInformation("Entering Online()")
      
       'Ensurting that MIIS Service is not running on other preffered nodes of the cluster grp
       For Each Node In prefferedOwners
        If (Node <> activeNode) And (CheckMIISServiceStatus(Node) = True) Then
            StopRunningProfiles(Node)
         StopMIISService(Node)
  End If
       Next
        
       'Check if MIIS Service is already running on the active Node, if yes just exit
       If CheckMIISServiceStatus(activeNode) = True Then
          Exit Function
       End If
      
       'Run MIISActivate on the Active Cluster Noded
       Resource.LogInformation("About to execute:" & miisActivateCmd)
       Set WshShell = CreateObject("WScript.Shell")
       Set oExec = WshShell.Exec(miisActivateCmd)
    '   ... Allow time for operation to complete...
    Dim i
    For i = 0 To miisServiceStartupTime
      Resource.LogInformation("Waiting for MIIS Service to come-up...")
         Set oWait = WshShell.Exec("sleep 1000") '1 second
         If CheckMIISServiceStatus(activeNode) = True Then
          Resource.LogInformation("MIIS Service Started by MIISMonitor Script")
          Exit For
         End if
       Next
      
       If CheckMIISServiceStatus(activeNode) = False Then
        Resource.LogInformation("Failed to MIISActivate on Node:" & activeNode)
        Online = False
        Exit Function
       End If
     
End Function

Function LooksAlive() 
 
  If CheckMIISServiceStatus(activeNode) = True Then
       Resource.LogInformation("MIIS Service LooksAlive")
       LooksAlive = True
  Else
      Resource.LogInformation("MIIS Service Failed")
       LooksAlive = False
  End If

End Function

Function IsAlive()
'Perform various MIIS calls to ensure that it is alive
 If GetNumberOfMVRecords(activeNode) = True Then
    Resource.LogInformation("MIIS Service is Alive")
    IsAlive = True
 Else
    Resource.LogInformation("MIIS Service failed isAlive check")
    IsAlive = False
 End If
 
End Function

Function Offline()

    Resource.LogInformation("Entering Offline()")
    Resource.LogInformation("About to stop MIIS Service on node:" & activeNode)
    StopRunningProfiles(activeNode) 
 StopMIISService(activeNode)

End Function

Function Terminate()

 Terminate = True 

End Function

Function Close()

    Close = True
   
End Function

Function GetPrefferedOwners()
Const HKEY_LOCAL_MACHINE = &H80000002
Dim oReg
Dim strKeyPath
Dim arrSubKeys
Dim strValueName
Dim strValue
Dim arrValues
Dim subkey
Dim strPrefferedNodes()
Dim i
i = 0
 
 Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
    activeNode & "\root\default:StdRegProv")
 
 strKeyPath = "Cluster\Groups\"
 oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
 
 For Each subkey In arrSubKeys
     strKeyPath = "Cluster\Groups\" & subkey
  strValueName = "Name"
  oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
  If strValue = miisgroup Then
   strValueName = "PreferredOwners"
   oReg.GetMultiStringValue HKEY_LOCAL_MACHINE,strKeyPath, _
      strValueName,arrValues
   For Each strValue In arrValues
       strKeyPath = "Cluster\Nodes\" & strValue
    strValueName = "NodeName"
    oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
    ReDim Preserve strPrefferedNodes(i)
    strPrefferedNodes(i) = strValue
    i = i + 1
   Next
  End If
 Next

 GetPrefferedOwners = strPrefferedNodes
 
End Function

Function CheckMIISServiceStatus(Node)
On Error Resume Next

  Dim objWMIService
  Dim strWMIQuery
  Dim colServices
 
  Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & Node & "\root\cimv2")
  strWMIQuery = "Select * from Win32_Service where Name = 'miiserver' and State = 'running'"
  Set colServices = objWMIService.ExecQuery(strWMIQuery)
  If Err.Number <> 0 Then
    Resource.LogInformation("Unable to complete WMI call in CheckMIISServiceStatus, error code " & Err.Number)
    CheckMIISService = False
    Exit Function
  End If
 
  If colServices.Count = 1 Then
       CheckMIISServiceStatus = True
  Else
       CheckMIISServiceStatus = False
  end If

End Function

Function StopMIISService(Node)
On Error Resume Next
Dim objWMIService
Dim colServiceList
Dim objService

 Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & Node & "\root\cimv2")
 Set colServiceList = objWMIService.ExecQuery _
    ("Select * from Win32_Service where Name='miiserver' and State = 'running'")
       
 For Each objService In colServiceList
     objService.StopService()
     If Err.Number <> 0 Then
     Resource.LogInformation("Unable to complete WMI call to stop MIIS during StopMIISService, error code " & Err.Number)
    End If
 Next

End Function

Function StopRunningProfiles(Node)
On Error Resume Next
Dim objWMIService
Dim Runs
Dim Run
Dim ManagementAgent
 
 'First stop all running jobs
    Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & Node & "\root\MicrosoftIdentityIntegrationServer")
 Set Runs = objWMIService.ExecQuery("Select * From MIIS_RunHistory where RunStatus = 'in-progress'")

 For Each Run in Runs
     Resource.LogInformation("Stopping " & Run.MaName & " profile " & Run.RunProfile)
  Set ManagementAgent = objWMIService.Get("MIIS_ManagementAgent.Name='" & Run.MaName & "'")
  ManagementAgent.Stop()
  If Err.Number <> 0 Then
     Resource.LogInformation("Unable to complete WMI to get Run History call during StopRunningProfiles, error code " & Err.Number)
    End If
 Next

End Function

Function GetNumberOfMVRecords(Node)
On Error Resume Next
Dim Service
Dim Server
Dim numOfMvObjects

 Set Service = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & Node & "\root\MicrosoftIdentityIntegrationServer")
 Set Server = Service.Get("MIIS_Server.Name='MIIS_Server1'")
 numOfMvObjects = Server.NumMvObjects()
    If numOfMvObjects = "connection-failure" Or numOfMvObjects = "call-failure:0x80230621" Then
    Resource.LogInformation("Unable to complete WMI call in isAlive, error code " & Err.Number)
    GetNumberOfMVRecords = False
    Exit Function
   Else
    Resource.LogInformation("Count of Metaverse Objects = " & numOfMvObjects)
    GetNumberOfMVRecords = True
   End If 

End Function