datapath-windows: Add WMI Script that updates Hyper-V friendly port names.
[cascardo/ovs.git] / datapath-windows / misc / OVS.psm1
1 <#
2 Copyright 2014 Cloudbase Solutions Srl
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 #>
16
17 $hvassembly = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.HyperV.PowerShell")
18
19 function Set-VMNetworkAdapterOVSPort
20 {
21     [CmdletBinding()]
22     param
23     (
24         [parameter(Mandatory=$true, ValueFromPipeline=$true)]
25         [Microsoft.HyperV.PowerShell.VMNetworkAdapter]$VMNetworkAdapter,
26
27         [parameter(Mandatory=$true)]
28         [string]$OVSPortName
29     )
30     process
31     {
32         $ns = "root\virtualization\v2"
33         $EscapedId = $VMNetworkAdapter.Id.Replace('\', '\\')
34         $sd = gwmi -namespace $ns -class Msvm_EthernetPortAllocationSettingData -Filter "InstanceId like '$EscapedId%'"
35
36         if($sd)
37         {
38             $sd.ElementName = $OVSPortName
39
40             $vsms = gwmi -namespace $ns -class Msvm_VirtualSystemManagementService
41             $retVal = $vsms.ModifyResourceSettings(@($sd.GetText(1)))
42             try
43             {
44                 Check-WMIReturnValue $retVal
45             }
46             catch
47             {
48                 throw "Assigning OVS port '$OVSPortName' failed"
49             }
50         }
51     }
52 }
53
54 function Check-WMIReturnValue($retVal)
55 {
56     if ($retVal.ReturnValue -ne 0)
57     {
58         if ($retVal.ReturnValue -eq 4096)
59         {
60             do
61             {
62                 $job = [wmi]$retVal.Job
63             }
64             while ($job.JobState -eq 4)
65
66             if ($job.JobState -ne 7)
67             {
68                 throw "Job Failed"
69             }
70         }
71         else
72         {
73             throw "Job Failed"
74         }
75     }
76 }