forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWmiCallsV2.cs
More file actions
3007 lines (2664 loc) · 131 KB
/
WmiCallsV2.cs
File metadata and controls
3007 lines (2664 loc) · 131 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2;
using log4net;
using System.Globalization;
using System.Management;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CloudStack.Plugin.WmiWrappers.ROOT.CIMV2;
using System.IO;
using System.Net.NetworkInformation;
using System.Net;
namespace HypervResource
{
public class WmiCallsV2 : IWmiCallsV2
{
public static String CloudStackUserDataKey = "cloudstack-vm-userdata";
/// <summary>
/// Defines the migration types.
/// </summary>
public enum MigrationType
{
VirtualSystem = 32768,
Storage = 32769,
Staged = 32770,
VirtualSystemAndStorage = 32771
};
/// <summary>
/// Defines migration transport types.
/// </summary>
public enum TransportType
{
TCP = 5,
SMB = 32768
};
public static void Initialize()
{
// Trigger assembly load into curren appdomain
}
private static ILog logger = LogManager.GetLogger(typeof(WmiCallsV2));
/// <summary>
/// Returns ping status of the given ip
/// </summary>
public static String PingHost(String ip)
{
return "Success";
}
/// <summary>
/// Returns ComputerSystem lacking any NICs and VOLUMEs
/// </summary>
public ComputerSystem AddUserData(ComputerSystem vm, string userData)
{
// Obtain controller for Hyper-V virtualisation subsystem
VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService();
// Create object to hold the data.
KvpExchangeDataItem kvpItem = KvpExchangeDataItem.CreateInstance();
kvpItem.LateBoundObject["Name"] = WmiCallsV2.CloudStackUserDataKey;
kvpItem.LateBoundObject["Data"] = userData;
kvpItem.LateBoundObject["Source"] = 0;
logger.Debug("VM " + vm.Name + " gets userdata " + userData);
// Update the resource settings for the VM.
System.Management.ManagementBaseObject kvpMgmtObj = kvpItem.LateBoundObject;
System.Management.ManagementPath jobPath;
String kvpStr = kvpMgmtObj.GetText(System.Management.TextFormat.CimDtd20);
uint ret_val = vmMgmtSvc.AddKvpItems(new String[] { kvpStr }, vm.Path, out jobPath);
// If the Job is done asynchronously
if (ret_val == ReturnCode.Started)
{
JobCompleted(jobPath);
}
else if (ret_val != ReturnCode.Completed)
{
var errMsg = string.Format(
"Failed to update VM {0} (GUID {1}) due to {2} (ModifyVirtualSystem call), existing VM not deleted",
vm.ElementName,
vm.Name,
ReturnCode.ToString(ret_val));
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
return vm;
}
/// <summary>
/// Returns ComputerSystem lacking any NICs and VOLUMEs
/// </summary>
public ComputerSystem CreateVM(string name, long memory_mb, int vcpus)
{
// Obtain controller for Hyper-V virtualisation subsystem
VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService();
// Create VM with correct name and default resources
ComputerSystem vm = CreateDefaultVm(vmMgmtSvc, name);
// Update the resource settings for the VM.
// Resource settings are referenced through the Msvm_VirtualSystemSettingData object.
VirtualSystemSettingData vmSettings = GetVmSettings(vm);
// For memory settings, there is no Dynamic Memory, so reservation, limit and quantity are identical.
MemorySettingData memSettings = GetMemSettings(vmSettings);
memSettings.LateBoundObject["VirtualQuantity"] = memory_mb;
memSettings.LateBoundObject["Reservation"] = memory_mb;
memSettings.LateBoundObject["Limit"] = memory_mb;
// Update the processor settings for the VM, static assignment of 100% for CPU limit
ProcessorSettingData procSettings = GetProcSettings(vmSettings);
procSettings.LateBoundObject["VirtualQuantity"] = vcpus;
procSettings.LateBoundObject["Reservation"] = vcpus;
procSettings.LateBoundObject["Limit"] = 100000;
ModifyVmResources(vmMgmtSvc, vm, new String[] {
memSettings.LateBoundObject.GetText(TextFormat.CimDtd20),
procSettings.LateBoundObject.GetText(TextFormat.CimDtd20)
});
logger.InfoFormat("VM with display name {0} has GUID {1}", vm.ElementName, vm.Name);
logger.DebugFormat("Resources for vm {0}: {1} MB memory, {2} vcpus", name, memory_mb, vcpus);
return vm;
}
/// <summary>
/// Create a (synthetic) nic, and attach it to the vm
/// </summary>
/// <param name="vm"></param>
/// <param name="mac"></param>
/// <param name="vlan"></param>
/// <returns></returns>
public SyntheticEthernetPortSettingData CreateNICforVm(ComputerSystem vm, string mac)
{
logger.DebugFormat("Creating nic for VM {0} (GUID {1})", vm.ElementName, vm.Name);
// Obtain controller for Hyper-V networking subsystem
var vmNetMgmtSvc = GetVirtualSwitchManagementService();
// Create NIC resource by cloning the default NIC
var synthNICsSettings = SyntheticEthernetPortSettingData.GetInstances(vmNetMgmtSvc.Scope, "InstanceID LIKE \"%Default\"");
// Assert
if (synthNICsSettings.Count != 1)
{
var errMsg = string.Format("Internal error, coudl not find default SyntheticEthernetPort instance");
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
var defaultSynthNICSettings = synthNICsSettings.OfType<SyntheticEthernetPortSettingData>().First();
var newSynthNICSettings = new SyntheticEthernetPortSettingData((ManagementBaseObject)defaultSynthNICSettings.LateBoundObject.Clone());
// Assign configuration to new NIC
string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' })));
newSynthNICSettings.LateBoundObject["ElementName"] = vm.ElementName;
newSynthNICSettings.LateBoundObject["Address"] = normalisedMAC;
newSynthNICSettings.LateBoundObject["StaticMacAddress"] = "TRUE";
newSynthNICSettings.LateBoundObject["VirtualSystemIdentifiers"] = new string[] { "{" + Guid.NewGuid().ToString() + "}" };
newSynthNICSettings.CommitObject();
// Insert NIC into vm
string[] newResources = new string[] { newSynthNICSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20)};
ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm );
// assert
if (newResourcePaths.Length != 1)
{
var errMsg = string.Format(
"Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}",
vm.ElementName,
vm.Name,
newResourcePaths.Length);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
return new SyntheticEthernetPortSettingData(newResourcePaths[0]);
}
public const string IDE_CONTROLLER = "Microsoft:Hyper-V:Emulated IDE Controller";
public const string SCSI_CONTROLLER = "Microsoft:Hyper-V:Synthetic SCSI Controller";
public const string HARDDISK_DRIVE = "Microsoft:Hyper-V:Synthetic Disk Drive";
public const string ISO_DRIVE = "Microsoft:Hyper-V:Synthetic DVD Drive";
// TODO: names harvested from Msvm_ResourcePool, not clear how to create new instances
public const string ISO_DISK = "Microsoft:Hyper-V:Virtual CD/DVD Disk"; // For IDE_ISO_DRIVE
public const string HARDDISK_DISK = "Microsoft:Hyper-V:Virtual Hard Disk"; // For IDE_HARDDISK_DRIVE
/// <summary>
/// Create new VM. By default we start it.
/// </summary>
public ComputerSystem DeployVirtualMachine(dynamic jsonObj, string systemVmIso)
{
var vmInfo = jsonObj.vm;
string vmName = vmInfo.name;
var nicInfo = vmInfo.nics;
int vcpus = vmInfo.cpus;
int memSize = vmInfo.maxRam / 1048576;
string errMsg = vmName;
var diskDrives = vmInfo.disks;
var bootArgs = vmInfo.bootArgs;
// assert
errMsg = vmName + ": missing disk information, array empty or missing, agent expects *at least* one disk for a VM";
if (diskDrives == null)
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
// assert
errMsg = vmName + ": missing NIC information, array empty or missing, agent expects at least an empty array.";
if (nicInfo == null )
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
// For existing VMs, return when we spot one of this name not stopped. In the meantime, remove any existing VMs of same name.
ComputerSystem vmWmiObj = null;
while ((vmWmiObj = GetComputerSystem(vmName)) != null)
{
logger.WarnFormat("Create request for existing vm, name {0}", vmName);
if (vmWmiObj.EnabledState == EnabledState.Disabled)
{
logger.InfoFormat("Deleting existing VM with name {0}, before we go on to create a VM with the same name", vmName);
DestroyVm(vmName);
}
else if (vmWmiObj.EnabledState == EnabledState.Enabled)
{
string infoMsg = string.Format("Create VM discovered there exists a VM with name {0}, state {1}",
vmName,
EnabledState.ToString(vmWmiObj.EnabledState));
logger.Info(infoMsg);
return vmWmiObj;
}
else
{
errMsg = string.Format("Create VM failing, because there exists a VM with name {0}, state {1}",
vmName,
EnabledState.ToString(vmWmiObj.EnabledState));
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
}
// Create vm carcase
logger.DebugFormat("Going ahead with create VM {0}, {1} vcpus, {2}MB RAM", vmName, vcpus, memSize);
var newVm = CreateVM(vmName, memSize, vcpus);
// Add a SCSI controller for attaching/detaching data volumes.
AddScsiController(newVm);
foreach (var diskDrive in diskDrives)
{
string vhdFile = null;
string diskName = null;
string isoPath = null;
VolumeObjectTO volInfo = VolumeObjectTO.ParseJson(diskDrive.data);
TemplateObjectTO templateInfo = TemplateObjectTO.ParseJson(diskDrive.data);
if (volInfo != null)
{
// assert
errMsg = vmName + ": volume missing primaryDataStore for disk " + diskDrive.ToString();
if (volInfo.primaryDataStore == null)
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
diskName = volInfo.name;
// assert
errMsg = vmName + ": can't deal with DataStore type for disk " + diskDrive.ToString();
if (volInfo.primaryDataStore == null)
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
errMsg = vmName + ": Malformed PrimaryDataStore for disk " + diskDrive.ToString();
if (String.IsNullOrEmpty(volInfo.primaryDataStore.Path))
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
errMsg = vmName + ": Missing folder PrimaryDataStore for disk " + diskDrive.ToString() + ", missing path: " + volInfo.primaryDataStore.Path;
if (!Directory.Exists(volInfo.primaryDataStore.Path))
{
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
vhdFile = volInfo.FullFileName;
if (!System.IO.File.Exists(vhdFile))
{
errMsg = vmName + ": non-existent volume, missing " + vhdFile + " for drive " + diskDrive.ToString();
logger.Error(errMsg);
throw new ArgumentException(errMsg);
}
logger.Debug("Going to create " + vmName + " with attached voluem " + diskName + " at " + vhdFile);
}
else if (templateInfo != null && templateInfo.nfsDataStoreTO != null)
{
NFSTO share = templateInfo.nfsDataStoreTO;
// The share is mapped, now attach the iso
isoPath = Utils.NormalizePath(Path.Combine(share.UncPath, templateInfo.path));
}
string driveType = diskDrive.type;
string ideCtrllr = "0";
string driveResourceType = null;
switch (driveType) {
case "ROOT":
ideCtrllr = "0";
driveResourceType = HARDDISK_DRIVE;
break;
case "ISO":
ideCtrllr = "1";
driveResourceType = ISO_DRIVE;
break;
case "DATADISK":
break;
default:
// TODO: double check exception type
errMsg = string.Format("Unknown disk type {0} for disk {1}, vm named {2}",
string.IsNullOrEmpty(driveType) ? "NULL" : driveType,
string.IsNullOrEmpty(diskName) ? "NULL" : diskName, vmName);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
logger.DebugFormat("Create disk type {1} (Named: {0}), on vm {2} {3}", diskName, driveResourceType, vmName,
string.IsNullOrEmpty(vhdFile) ? " no disk to insert" : ", inserting disk" + vhdFile);
if (driveType.Equals("DATADISK"))
{
AttachDisk(vmName, vhdFile, (string)diskDrive.diskSeq);
}
else
{
AddDiskDriveToIdeController(newVm, vhdFile, ideCtrllr, driveResourceType);
if (isoPath != null)
{
AttachIso(vmName, isoPath);
}
}
}
int nicCount = 0;
int enableState = 2;
// Add the Nics to the VM in the deviceId order.
foreach (var nc in nicInfo)
{
foreach (var nic in nicInfo)
{
int nicid = nic.deviceId;
Int32 networkRateMbps = nic.networkRateMbps;
string mac = nic.mac;
string vlan = null;
string isolationUri = nic.isolationUri;
string broadcastUri = nic.broadcastUri;
string nicIp = nic.ip;
string nicNetmask = nic.netmask;
if ( (broadcastUri != null ) || (isolationUri != null && isolationUri.StartsWith("vlan://")))
{
if (broadcastUri != null && broadcastUri.StartsWith("storage"))
{
vlan = broadcastUri.Substring("storage://".Length);
}
else
{
vlan = isolationUri.Substring("vlan://".Length);
}
int tmp;
if (vlan.Equals("untagged", StringComparison.CurrentCultureIgnoreCase) ) {
// recevied vlan is untagged, don't parse for the vlan in the isolation uri
vlan = null;
}
else if (!int.TryParse(vlan, out tmp))
{
// TODO: double check exception type
errMsg = string.Format("Invalid VLAN value {0} for on vm {1} for nic uuid {2}", isolationUri, vmName, nic.uuid);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
}
if (nicid == nicCount)
{
if (nicIp.Equals("0.0.0.0") && nicNetmask.Equals("255.255.255.255"))
{
// this is the extra nic added to VR.
vlan = null;
enableState = 3;
}
// Create network adapter
var newAdapter = CreateNICforVm(newVm, mac);
String switchName ="";
if (nic.name != null)
{
switchName = nic.name;
}
EthernetPortAllocationSettingData portSettings = null;
// connection to vswitch
portSettings = AttachNicToPort(newVm, newAdapter, switchName, enableState);
//reset the flag for other nics
enableState = 2;
// set vlan
if (vlan != null)
{
SetPortVlan(vlan, portSettings);
}
if (networkRateMbps > 0)
{
SetBandWidthLimit((ulong)networkRateMbps, portSettings);
}
logger.DebugFormat("Created adapter {0} on port {1}, {2}",
newAdapter.Path, portSettings.Path, (vlan == null ? "No VLAN" : "VLAN " + vlan));
// logger.DebugFormat("Created adapter {0} on port {1}, {2}",
// newAdapter.Path, portSettings.Path, (vlan == null ? "No VLAN" : "VLAN " + vlan));
}
}
nicCount++;
}
// pass the boot args for the VM using KVP component.
// We need to pass the boot args to system vm's to get them configured with cloudstack configuration.
// Add new user data
var vm = GetComputerSystem(vmName);
if (bootArgs != null && !String.IsNullOrEmpty((string)bootArgs))
{
String bootargs = bootArgs;
AddUserData(vm, bootargs);
}
// call patch systemvm iso only for systemvms
if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-"))
{
if (systemVmIso != null && systemVmIso.Length != 0)
{
patchSystemVmIso(vmName, systemVmIso);
}
}
logger.DebugFormat("Starting VM {0}", vmName);
SetState(newVm, RequiredState.Enabled);
// Mark the VM as created by cloudstack tag
TagVm(newVm);
// we need to reboot to get the hv kvp daemon get started vr gets configured.
if (vmName.StartsWith("r-") || vmName.StartsWith("s-") || vmName.StartsWith("v-"))
{
System.Threading.Thread.Sleep(90000);
}
logger.InfoFormat("Started VM {0}", vmName);
return newVm;
}
public static Boolean pingResource(String ip)
{
PingOptions pingOptions = null;
PingReply pingReply = null;
IPAddress ipAddress = null;
Ping pingSender = new Ping();
int numberOfPings = 6;
int pingTimeout = 1000;
int byteSize = 32;
byte[] buffer = new byte[byteSize];
ipAddress = IPAddress.Parse(ip);
pingOptions = new PingOptions();
for (int i = 0; i < numberOfPings; i++)
{
pingReply = pingSender.Send(ipAddress, pingTimeout, buffer, pingOptions);
if (pingReply.Status == IPStatus.Success)
{
System.Threading.Thread.Sleep(30000);
return true;
}
else
{
// wait for the second boot and then return with suces
System.Threading.Thread.Sleep(30000);
}
}
return false;
}
private EthernetPortAllocationSettingData AttachNicToPort(ComputerSystem newVm, SyntheticEthernetPortSettingData newAdapter, String vSwitchName, int enableState)
{
// Get the virtual switch
VirtualEthernetSwitch vSwitch = GetExternalVirtSwitch(vSwitchName);
//check the the recevied vSwitch is the same as vSwitchName.
if (!vSwitchName.Equals("") && !vSwitch.ElementName.Equals(vSwitchName))
{
var errMsg = string.Format("Internal error, coudl not find Virtual Switch with the name : " +vSwitchName);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
// Create port for adapter
var defaultEthernetPortSettings = EthernetPortAllocationSettingData.GetInstances(vSwitch.Scope, "InstanceID LIKE \"%Default\"");
// assert
if (defaultEthernetPortSettings.Count != 1)
{
var errMsg = string.Format("Internal error, coudl not find default EthernetPortAllocationSettingData instance");
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
var defaultEthernetPortSettingsObj = defaultEthernetPortSettings.OfType<EthernetPortAllocationSettingData>().First();
var newEthernetPortSettings = new EthernetPortAllocationSettingData((ManagementBaseObject)defaultEthernetPortSettingsObj.LateBoundObject.Clone());
newEthernetPortSettings.LateBoundObject["Parent"] = newAdapter.Path.Path;
newEthernetPortSettings.LateBoundObject["HostResource"] = new string[] { vSwitch.Path.Path };
newEthernetPortSettings.LateBoundObject["EnabledState"] = enableState; //3 disabled 2 Enabled
// Insert NIC into vm
string[] newResources = new string[] { newEthernetPortSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) };
ManagementPath[] newResourcePaths = AddVirtualResource(newResources, newVm);
// assert
if (newResourcePaths.Length != 1)
{
var errMsg = string.Format(
"Failed to properly insert a single NIC on VM {0} (GUID {1}): number of resource created {2}",
newVm.ElementName,
newVm.Name,
newResourcePaths.Length);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
return new EthernetPortAllocationSettingData(newResourcePaths[0]);
}
/// this method is to add a dvd drive and attach the systemvm iso.
///
public void patchSystemVmIso(String vmName, String systemVmIso)
{
ComputerSystem vmObject = GetComputerSystem(vmName);
AddDiskDriveToIdeController(vmObject, "", "1", ISO_DRIVE);
AttachIso(vmName, systemVmIso);
}
public void AttachDisk(string vmName, string diskPath, string addressOnController)
{
logger.DebugFormat("Got request to attach disk {0} to vm {1}", diskPath, vmName);
ComputerSystem vm = GetComputerSystem(vmName);
if (vm == null)
{
logger.DebugFormat("VM {0} not found", vmName);
return;
}
else
{
ManagementPath newDrivePath = GetDiskDriveOnScsiController(vm, addressOnController);
if (newDrivePath == null)
{
newDrivePath = AttachDiskDriveToScsiController(vm, addressOnController);
}
InsertDiskImage(vm, diskPath, HARDDISK_DISK, newDrivePath);
}
}
/// </summary>
/// <param name="vm"></param>
/// <param name="cntrllerAddr"></param>
/// <param name="driveResourceType">IDE_HARDDISK_DRIVE or IDE_ISO_DRIVE</param>
public ManagementPath AddDiskDriveToIdeController(ComputerSystem vm, string vhdfile, string cntrllerAddr, string driveResourceType)
{
logger.DebugFormat("Creating DISK for VM {0} (GUID {1}) by attaching {2}",
vm.ElementName,
vm.Name,
vhdfile);
// Determine disk type for drive and assert drive type valid
string diskResourceSubType = null;
switch(driveResourceType) {
case HARDDISK_DRIVE:
diskResourceSubType = HARDDISK_DISK;
break;
case ISO_DRIVE:
diskResourceSubType = ISO_DISK;
break;
default:
var errMsg = string.Format(
"Unrecognised disk drive type {0} for VM {1} (GUID {2})",
string.IsNullOrEmpty(driveResourceType) ? "NULL": driveResourceType,
vm.ElementName,
vm.Name);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
ManagementPath newDrivePath = AttachNewDrive(vm, cntrllerAddr, driveResourceType);
// If there's not disk to insert, we are done.
if (String.IsNullOrEmpty(vhdfile))
{
logger.DebugFormat("No disk to be added to drive, disk drive {0} is complete", newDrivePath.Path);
}
else
{
InsertDiskImage(vm, vhdfile, diskResourceSubType, newDrivePath);
}
return newDrivePath;
}
public void DetachDisk(string displayName, string diskFileName)
{
logger.DebugFormat("Got request to detach virtual disk {0} from vm {1}", diskFileName, displayName);
ComputerSystem vm = GetComputerSystem(displayName);
if (vm == null)
{
logger.DebugFormat("VM {0} not found", displayName);
return;
}
else
{
RemoveStorageImage(vm, diskFileName);
}
}
/// <summary>
/// Removes a disk image from a drive, but does not remove the drive itself.
/// </summary>
/// <param name="vm"></param>
/// <param name="diskFileName"></param>
private void RemoveStorageImage(ComputerSystem vm, string diskFileName)
{
// Obtain StorageAllocationSettingData for disk
StorageAllocationSettingData.StorageAllocationSettingDataCollection storageSettingsObjs = StorageAllocationSettingData.GetInstances();
StorageAllocationSettingData imageToRemove = null;
foreach (StorageAllocationSettingData item in storageSettingsObjs)
{
if (item.HostResource == null || item.HostResource.Length != 1)
{
continue;
}
string hostResource = item.HostResource[0];
if (Path.Equals(hostResource, diskFileName))
{
imageToRemove = item;
break;
}
}
// assert
if (imageToRemove == null)
{
var errMsg = string.Format(
"Failed to remove disk image {0} from VM {1} (GUID {2}): the disk image is not attached.",
diskFileName,
vm.ElementName,
vm.Name);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
RemoveStorageResource(imageToRemove.Path, vm);
logger.InfoFormat("Removed disk image {0} from VM {1} (GUID {2}): the disk image is not attached.",
diskFileName,
vm.ElementName,
vm.Name);
}
private ManagementPath AttachNewDrive(ComputerSystem vm, string cntrllerAddr, string driveType)
{
// Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it.
VirtualSystemSettingData vmSettings = GetVmSettings(vm);
var ctrller = GetIDEControllerSettings(vmSettings, cntrllerAddr);
// A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type
string defaultDriveQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", driveType);
var newDiskDriveSettings = CloneResourceAllocationSetting(defaultDriveQuery);
// Set IDE controller and address on the controller for the new drive
newDiskDriveSettings.LateBoundObject["Parent"] = ctrller.Path.ToString();
newDiskDriveSettings.LateBoundObject["AddressOnParent"] = "0";
newDiskDriveSettings.CommitObject();
// Add this new disk drive to the VM
logger.DebugFormat("Creating disk drive type {0}, parent IDE controller is {1} and address on controller is {2}",
newDiskDriveSettings.ResourceSubType,
newDiskDriveSettings.Parent,
newDiskDriveSettings.AddressOnParent);
string[] newDriveResource = new string[] { newDiskDriveSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) };
ManagementPath[] newDrivePaths = AddVirtualResource(newDriveResource, vm);
// assert
if (newDrivePaths.Length != 1)
{
var errMsg = string.Format(
"Failed to add disk drive type {3} to VM {0} (GUID {1}): number of resource created {2}",
vm.ElementName,
vm.Name,
newDrivePaths.Length,
driveType);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
logger.DebugFormat("New disk drive type {0} WMI path is {1}s",
newDiskDriveSettings.ResourceSubType,
newDrivePaths[0].Path);
return newDrivePaths[0];
}
private ManagementPath AddScsiController(ComputerSystem vm)
{
// A description of the controller is created by modifying a clone of the default ResourceAllocationSettingData for scsi controller
string scsiQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", SCSI_CONTROLLER);
var scsiSettings = CloneResourceAllocationSetting(scsiQuery);
scsiSettings.LateBoundObject["ElementName"] = "SCSI Controller";
scsiSettings.CommitObject();
// Insert SCSI controller into vm
string[] newResources = new string[] { scsiSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) };
ManagementPath[] newResourcePaths = AddVirtualResource(newResources, vm);
// assert
if (newResourcePaths.Length != 1)
{
var errMsg = string.Format(
"Failed to add scsi controller to VM {0} (GUID {1}): number of resource created {2}",
vm.ElementName,
vm.Name,
newResourcePaths.Length);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
logger.DebugFormat("New controller type {0} WMI path is {1}s",
scsiSettings.ResourceSubType,
newResourcePaths[0].Path);
return newResourcePaths[0];
}
private ManagementPath GetDiskDriveOnScsiController(ComputerSystem vm, string addrOnController)
{
VirtualSystemSettingData vmSettings = GetVmSettings(vm);
var wmiObjCollection = GetResourceAllocationSettings(vmSettings);
foreach (ResourceAllocationSettingData wmiObj in wmiObjCollection)
{
if (wmiObj.ResourceSubType == HARDDISK_DRIVE)
{
ResourceAllocationSettingData parent = new ResourceAllocationSettingData(new ManagementObject(wmiObj.Parent));
if (parent.ResourceSubType == SCSI_CONTROLLER && wmiObj.AddressOnParent == addrOnController)
{
return wmiObj.Path;
}
}
}
return null;
}
private ManagementPath AttachDiskDriveToScsiController(ComputerSystem vm, string addrOnController)
{
// Disk drives are attached to a 'Parent' Scsi controller.
VirtualSystemSettingData vmSettings = GetVmSettings(vm);
var ctrller = GetScsiControllerSettings(vmSettings);
// A description of the drive is created by modifying a clone of the default ResourceAllocationSettingData for that drive type
string defaultDriveQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", HARDDISK_DRIVE);
var newDiskDriveSettings = CloneResourceAllocationSetting(defaultDriveQuery);
// Set IDE controller and address on the controller for the new drive
newDiskDriveSettings.LateBoundObject["Parent"] = ctrller.Path.ToString();
newDiskDriveSettings.LateBoundObject["AddressOnParent"] = addrOnController;
newDiskDriveSettings.CommitObject();
// Add this new disk drive to the VM
logger.DebugFormat("Creating disk drive type {0}, parent IDE controller is {1} and address on controller is {2}",
newDiskDriveSettings.ResourceSubType,
newDiskDriveSettings.Parent,
newDiskDriveSettings.AddressOnParent);
string[] newDriveResource = new string[] { newDiskDriveSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) };
ManagementPath[] newDrivePaths = AddVirtualResource(newDriveResource, vm);
// assert
if (newDrivePaths.Length != 1)
{
var errMsg = string.Format(
"Failed to add disk drive type {3} to VM {0} (GUID {1}): number of resource created {2}",
vm.ElementName,
vm.Name,
newDrivePaths.Length,
HARDDISK_DRIVE);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
logger.DebugFormat("New disk drive type {0} WMI path is {1}s",
newDiskDriveSettings.ResourceSubType,
newDrivePaths[0].Path);
return newDrivePaths[0];
}
private void InsertDiskImage(ComputerSystem vm, string diskImagePath, string diskResourceSubType, ManagementPath drivePath)
{
// A description of the disk is created by modifying a clone of the default ResourceAllocationSettingData for that disk type
string defaultDiskQuery = String.Format("ResourceSubType LIKE \"{0}\" AND InstanceID LIKE \"%Default\"", diskResourceSubType);
var newDiskSettings = CloneStorageAllocationSetting(defaultDiskQuery);
// Set file containing the disk image
newDiskSettings.LateBoundObject["Parent"] = drivePath.Path;
// V2 API uses HostResource to specify image, see http://msdn.microsoft.com/en-us/library/hh859775(v=vs.85).aspx
newDiskSettings.LateBoundObject["HostResource"] = new string[] { diskImagePath };
newDiskSettings.CommitObject();
// Add the new Msvm_StorageAllocationSettingData object as a virtual hard disk to the vm.
string[] newDiskResource = new string[] { newDiskSettings.LateBoundObject.GetText(System.Management.TextFormat.CimDtd20) };
ManagementPath[] newDiskPaths = AddStorageResource(newDiskResource, vm);
// assert
if (newDiskPaths.Length != 1)
{
var errMsg = string.Format(
"Failed to add disk image type {3} to VM {0} (GUID {1}): number of resource created {2}",
vm.ElementName,
vm.Name,
newDiskPaths.Length,
diskResourceSubType);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
logger.InfoFormat("Created disk {2} for VM {0} (GUID {1}), image {3} ",
vm.ElementName,
vm.Name,
newDiskPaths[0].Path,
diskImagePath);
}
/// <summary>
/// Create Msvm_StorageAllocationSettingData corresponding to the ISO image, and
/// associate this with the VM's DVD drive.
/// </summary>
private void AttachIso(ComputerSystem vm, string isoPath)
{
// Disk drives are attached to a 'Parent' IDE controller. We IDE Controller's settings for the 'Path', which our new Disk drive will use to reference it.
VirtualSystemSettingData vmSettings = GetVmSettings(vm);
var driveWmiObj = GetDvdDriveSettings(vmSettings);
InsertDiskImage(vm, isoPath, ISO_DISK, driveWmiObj.Path);
}
private static ResourceAllocationSettingData CloneResourceAllocationSetting(string wmiQuery)
{
var defaultDiskDriveSettingsObjs = ResourceAllocationSettingData.GetInstances(wmiQuery);
// assert
if (defaultDiskDriveSettingsObjs.Count != 1)
{
var errMsg = string.Format("Failed to find Msvm_ResourceAllocationSettingData for the query {0}", wmiQuery);
var ex = new WmiException(errMsg);
logger.Error(errMsg, ex);
throw ex;
}
ResourceAllocationSettingData defaultDiskDriveSettings = defaultDiskDriveSettingsObjs.OfType<ResourceAllocationSettingData>().First();
return new ResourceAllocationSettingData((ManagementBaseObject)defaultDiskDriveSettings.LateBoundObject.Clone());
}
// Modify the systemvm nic's VLAN id
public void ModifyVmVLan(string vmName, String vlanid, String mac)
{
int enableState = 2;
bool enable = true;
ComputerSystem vm = GetComputerSystem(vmName);
SyntheticEthernetPortSettingData[] nicSettingsViaVm = GetEthernetPortSettings(vm);
// Obtain controller for Hyper-V virtualisation subsystem
VirtualSystemManagementService vmMgmtSvc = GetVirtualisationSystemManagementService();
EthernetPortAllocationSettingData networkAdapter = null;
string normalisedMAC = string.Join("", (mac.Split(new char[] { ':' })));
int index = 0;
foreach (SyntheticEthernetPortSettingData item in nicSettingsViaVm)
{
if (normalisedMAC.ToLower().Equals(item.Address.ToLower()))
{
break;
}
index++;
}
String vSwitchName = "";
VirtualEthernetSwitch vSwitch = GetExternalVirtSwitch(vSwitchName);
EthernetPortAllocationSettingData[] ethernetConnections = GetEthernetConnections(vm);
networkAdapter = ethernetConnections[index];
networkAdapter.LateBoundObject["EnabledState"] = enableState; //3 disabled 2 Enabled
networkAdapter.LateBoundObject["HostResource"] = new string[] { vSwitch.Path.Path };
ModifyVmResources(vmMgmtSvc, vm, new String[] {
networkAdapter.LateBoundObject.GetText(TextFormat.CimDtd20)
});
EthernetSwitchPortVlanSettingData vlanSettings = GetVlanSettings(ethernetConnections[index]);
if (vlanid.Equals("untagged", StringComparison.CurrentCultureIgnoreCase))
{
// recevied vlan is untagged, don't parse for the vlan in the isolation uri
vlanid = null;
}
if (vlanSettings == null)
{
// when modifying nic to not connected don't create vlan
if (enable)
{
if (vlanid != null)
{
SetPortVlan(vlanid, networkAdapter);
}
}
}
else
{
if (enable)
{
if (vlanid != null)
{
//Assign vlan configuration to nic
vlanSettings.LateBoundObject["AccessVlanId"] = vlanid;
vlanSettings.LateBoundObject["OperationMode"] = 1;
ModifyFeatureVmResources(vmMgmtSvc, vm, new String[] {
vlanSettings.LateBoundObject.GetText(TextFormat.CimDtd20)});
}
}
else
{
var virtSysMgmtSvc = GetVirtualisationSystemManagementService();
// This method will remove the vlan settings present on the Nic
ManagementPath jobPath;
var ret_val = virtSysMgmtSvc.RemoveFeatureSettings(new ManagementPath[] { vlanSettings.Path },
out jobPath);
// If the Job is done asynchronously
if (ret_val == ReturnCode.Started)
{
JobCompleted(jobPath);
}
else if (ret_val != ReturnCode.Completed)
{
var errMsg = string.Format(
"Failed to remove vlan resource {0} from VM {1} (GUID {2}) due to {3}",
vlanSettings.Path,
vm.ElementName,
vm.Name,