Skip to content

Commit e77ab38

Browse files
committed
Fixing the implementation for AttachCommand and DetachCommand in hyperv agent.
Also implemented RebootCommand for rebooting an instance on hyperv host.
1 parent 7095ea2 commit e77ab38

4 files changed

Lines changed: 260 additions & 30 deletions

File tree

‎plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/CloudStackTypes.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,27 @@ public static NFSTO ParseJson(dynamic json)
279279
}
280280
}
281281

282+
public class DiskTO
283+
{
284+
public string type;
285+
public TemplateObjectTO templateObjectTO = null;
286+
287+
public static DiskTO ParseJson(dynamic json)
288+
{
289+
DiskTO result = null;
290+
if (json != null)
291+
{
292+
result = new DiskTO()
293+
{
294+
templateObjectTO = TemplateObjectTO.ParseJson(json.data),
295+
type = (string)json.type,
296+
};
297+
}
298+
299+
return result;
300+
}
301+
}
302+
282303
enum VolumeType
283304
{
284305
UNKNOWN,
@@ -589,6 +610,7 @@ public class CloudStackTypes
589610
public const string SwiftTO = "com.cloud.agent.api.to.SwiftTO";
590611
public const string VirtualMachineTO = "com.cloud.agent.api.to.VirtualMachineTO";
591612
public const string VolumeTO = "com.cloud.agent.api.to.VolumeTO";
613+
public const string DiskTO = "com.cloud.agent.api.to.DiskTO";
592614
public const string InternalErrorException = "com.cloud.exception.InternalErrorException";
593615
public const string HostType = "com.cloud.host.Host.Type";
594616
public const string HypervisorType = "com.cloud.hypervisor.Hypervisor.HypervisorType";

‎plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResourceController.cs‎

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,19 @@ public JContainer AttachCommand([FromBody]dynamic cmd)
196196
try
197197
{
198198
string vmName = (string)cmd.vmName;
199-
result = true;
199+
DiskTO disk = DiskTO.ParseJson(cmd.disk);
200+
TemplateObjectTO dataStore = disk.templateObjectTO;
201+
202+
if (dataStore.nfsDataStoreTO != null)
203+
{
204+
NFSTO share = dataStore.nfsDataStoreTO;
205+
Utils.connectToRemote(share.UncPath, share.Domain, share.User, share.Password);
206+
207+
// The share is mapped, now attach the iso
208+
string isoPath = Path.Combine(share.UncPath.Replace('/', Path.DirectorySeparatorChar), dataStore.path);
209+
wmiCallsV2.AttachIso(vmName, isoPath);
210+
result = true;
211+
}
200212
}
201213
catch (Exception sysEx)
202214
{
@@ -229,7 +241,18 @@ public JContainer DetachCommand([FromBody]dynamic cmd)
229241
try
230242
{
231243
string vmName = (string)cmd.vmName;
232-
result = true;
244+
DiskTO disk = DiskTO.ParseJson(cmd.disk);
245+
TemplateObjectTO dataStore = disk.templateObjectTO;
246+
247+
if (dataStore.nfsDataStoreTO != null)
248+
{
249+
NFSTO share = dataStore.nfsDataStoreTO;
250+
// The share is mapped, now attach the iso
251+
string isoPath = Path.Combine(share.UncPath.Replace('/', Path.DirectorySeparatorChar),
252+
dataStore.path.Replace('/', Path.DirectorySeparatorChar));
253+
wmiCallsV2.DetachDisk(vmName, isoPath);
254+
result = true;
255+
}
233256
}
234257
catch (Exception sysEx)
235258
{
@@ -247,6 +270,49 @@ public JContainer DetachCommand([FromBody]dynamic cmd)
247270
}
248271
}
249272

273+
// POST api/HypervResource/RebootCommand
274+
[HttpPost]
275+
[ActionName(CloudStackTypes.RebootCommand)]
276+
public JContainer RebootCommand([FromBody]dynamic cmd)
277+
{
278+
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
279+
{
280+
logger.Info(CloudStackTypes.RebootCommand + cmd.ToString());
281+
282+
string details = null;
283+
bool result = false;
284+
285+
try
286+
{
287+
string vmName = (string)cmd.vmName;
288+
var sys = wmiCallsV2.GetComputerSystem(vmName);
289+
if (sys == null)
290+
{
291+
details = CloudStackTypes.RebootCommand + " requested unknown VM " + vmName;
292+
logger.Error(details);
293+
}
294+
else
295+
{
296+
wmiCallsV2.SetState(sys, RequiredState.Reset);
297+
result = true;
298+
}
299+
}
300+
catch (Exception sysEx)
301+
{
302+
details = CloudStackTypes.RebootCommand + " failed due to " + sysEx.Message;
303+
logger.Error(details, sysEx);
304+
}
305+
306+
object ansContent = new
307+
{
308+
result = result,
309+
details = details
310+
};
311+
312+
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.RebootAnswer);
313+
}
314+
}
315+
250316
// POST api/HypervResource/DestroyCommand
251317
[HttpPost]
252318
[ActionName(CloudStackTypes.DestroyCommand)]

‎plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/Utils.cs‎

Lines changed: 166 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -66,30 +66,30 @@ public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, N
6666
bool isSuccess = LogonUser(cifsShareDetails.User, cifsShareDetails.Domain, cifsShareDetails.Password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
6767
using (WindowsImpersonationContext remoteIdentity = new WindowsIdentity(token).Impersonate())
6868
{
69-
String dest = "";
70-
if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx"))
71-
{
72-
dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare);
73-
dest = dest.Replace('/', Path.DirectorySeparatorChar);
74-
}
75-
// if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use
76-
// In the clean setup, first copy command wont be having the filename it contains onlyu dir path.
77-
// we need to scan the folder point and then copy the file to destination.
78-
else if (!filePathRelativeToShare.EndsWith(".vhd") || !filePathRelativeToShare.EndsWith(".vhdx"))
79-
{
80-
// scan the folder and get the vhd filename.
81-
String uncPath = Path.Combine(cifsShareDetails.UncPath, Path.Combine(filePathRelativeToShare.Split('/')));
82-
//uncPath = uncPath.Replace("/", "\\");
83-
DirectoryInfo dir = new DirectoryInfo(uncPath);
84-
FileInfo[] vhdFiles = dir.GetFiles("*.vhd*");
85-
if (vhdFiles.Length > 0)
86-
{
87-
FileInfo file = vhdFiles[0];
88-
dest = file.FullName;
89-
}
90-
}
91-
s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile);
69+
String dest = "";
70+
if (filePathRelativeToShare.EndsWith(".iso") || filePathRelativeToShare.EndsWith(".vhd") || filePathRelativeToShare.EndsWith(".vhdx"))
71+
{
72+
dest = Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare);
73+
dest = dest.Replace('/', Path.DirectorySeparatorChar);
74+
}
75+
// if the filePathRelativeToShare string don't have filename and only a dir point then find the vhd files in that folder and use
76+
// In the clean setup, first copy command wont be having the filename it contains onlyu dir path.
77+
// we need to scan the folder point and then copy the file to destination.
78+
else if (!filePathRelativeToShare.EndsWith(".vhd") || !filePathRelativeToShare.EndsWith(".vhdx"))
79+
{
80+
// scan the folder and get the vhd filename.
81+
String uncPath = Path.Combine(cifsShareDetails.UncPath, Path.Combine(filePathRelativeToShare.Split('/')));
82+
//uncPath = uncPath.Replace("/", "\\");
83+
DirectoryInfo dir = new DirectoryInfo(uncPath);
84+
FileInfo[] vhdFiles = dir.GetFiles("*.vhd*");
85+
if (vhdFiles.Length > 0)
86+
{
87+
FileInfo file = vhdFiles[0];
88+
dest = file.FullName;
89+
}
90+
}
9291

92+
s_logger.Info(CloudStackTypes.CopyCommand + ": copy " + Path.Combine(cifsShareDetails.UncPath, filePathRelativeToShare) + " to " + destFile);
9393
File.Copy(dest, destFile, true);
9494
remoteIdentity.Undo();
9595
}
@@ -103,6 +103,32 @@ public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, N
103103
}
104104
}
105105

106+
public static void connectToRemote(string remoteUNC, string domain, string username, string password)
107+
{
108+
NETRESOURCE nr = new NETRESOURCE();
109+
nr.dwType = RESOURCETYPE_DISK;
110+
nr.lpRemoteName = remoteUNC.Replace('/', Path.DirectorySeparatorChar);
111+
if (domain != null)
112+
{
113+
username = domain + @"\" + username;
114+
}
115+
116+
int ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
117+
if (ret != NO_ERROR)
118+
{
119+
throw new ArgumentException("net use of share " + remoteUNC + "failed with "+ getErrorForNumber(ret));
120+
}
121+
}
122+
123+
public static void disconnectRemote(string remoteUNC)
124+
{
125+
int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false);
126+
if (ret != NO_ERROR)
127+
{
128+
throw new ArgumentException("net disconnect of share " + remoteUNC + "failed with " + getErrorForNumber(ret));
129+
}
130+
}
131+
106132
// from http://stackoverflow.com/a/2541569/939250
107133
#region imports
108134
[DllImport("advapi32.dll", SetLastError = true)]
@@ -113,9 +139,16 @@ public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, N
113139

114140
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
115141
public extern static bool DuplicateToken(IntPtr existingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle);
142+
143+
[DllImport("Mpr.dll")]
144+
private static extern int WNetUseConnection(IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags,
145+
string lpAccessName, string lpBufferSize, string lpResult);
146+
147+
[DllImport("Mpr.dll")]
148+
private static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);
116149
#endregion
117150

118-
#region logon consts
151+
#region consts
119152
// logon types
120153
const int LOGON32_LOGON_INTERACTIVE = 2;
121154
const int LOGON32_LOGON_NETWORK = 3;
@@ -126,6 +159,115 @@ public static void DownloadCifsFileToLocalFile(string filePathRelativeToShare, N
126159
const int LOGON32_PROVIDER_WINNT50 = 3;
127160
const int LOGON32_PROVIDER_WINNT40 = 2;
128161
const int LOGON32_PROVIDER_WINNT35 = 1;
162+
163+
const int RESOURCE_CONNECTED = 0x00000001;
164+
const int RESOURCE_GLOBALNET = 0x00000002;
165+
const int RESOURCE_REMEMBERED = 0x00000003;
166+
167+
const int RESOURCETYPE_ANY = 0x00000000;
168+
const int RESOURCETYPE_DISK = 0x00000001;
169+
const int RESOURCETYPE_PRINT = 0x00000002;
170+
171+
const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
172+
const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
173+
const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
174+
const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
175+
const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
176+
const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;
177+
178+
const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
179+
const int RESOURCEUSAGE_CONTAINER = 0x00000002;
180+
181+
182+
const int CONNECT_INTERACTIVE = 0x00000008;
183+
const int CONNECT_PROMPT = 0x00000010;
184+
const int CONNECT_REDIRECT = 0x00000080;
185+
const int CONNECT_UPDATE_PROFILE = 0x00000001;
186+
const int CONNECT_COMMANDLINE = 0x00000800;
187+
const int CONNECT_CMD_SAVECRED = 0x00001000;
188+
189+
const int CONNECT_LOCALDRIVE = 0x00000100;
129190
#endregion
191+
192+
#region Errors
193+
const int NO_ERROR = 0;
194+
195+
const int ERROR_ACCESS_DENIED = 5;
196+
const int ERROR_ALREADY_ASSIGNED = 85;
197+
const int ERROR_BAD_DEVICE = 1200;
198+
const int ERROR_BAD_NET_NAME = 67;
199+
const int ERROR_BAD_PROVIDER = 1204;
200+
const int ERROR_CANCELLED = 1223;
201+
const int ERROR_EXTENDED_ERROR = 1208;
202+
const int ERROR_INVALID_ADDRESS = 487;
203+
const int ERROR_INVALID_PARAMETER = 87;
204+
const int ERROR_INVALID_PASSWORD = 1216;
205+
const int ERROR_MORE_DATA = 234;
206+
const int ERROR_NO_MORE_ITEMS = 259;
207+
const int ERROR_NO_NET_OR_BAD_PATH = 1203;
208+
const int ERROR_NO_NETWORK = 1222;
209+
210+
const int ERROR_BAD_PROFILE = 1206;
211+
const int ERROR_CANNOT_OPEN_PROFILE = 1205;
212+
const int ERROR_DEVICE_IN_USE = 2404;
213+
const int ERROR_NOT_CONNECTED = 2250;
214+
const int ERROR_OPEN_FILES = 2401;
215+
216+
private struct ErrorClass
217+
{
218+
public int num;
219+
public string message;
220+
public ErrorClass(int num, string message)
221+
{
222+
this.num = num;
223+
this.message = message;
224+
}
225+
}
226+
227+
private static ErrorClass[] ERROR_LIST = new ErrorClass[] {
228+
new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"),
229+
new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"),
230+
new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"),
231+
new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"),
232+
new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"),
233+
new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"),
234+
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
235+
new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"),
236+
new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"),
237+
new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"),
238+
new ErrorClass(ERROR_MORE_DATA, "Error: More Data"),
239+
new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"),
240+
new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"),
241+
new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"),
242+
new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"),
243+
new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"),
244+
new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"),
245+
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
246+
new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"),
247+
new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"),
248+
};
249+
250+
private static string getErrorForNumber(int errNum)
251+
{
252+
foreach (ErrorClass er in ERROR_LIST)
253+
{
254+
if (er.num == errNum) return er.message;
255+
}
256+
return "Error: Unknown, " + errNum;
257+
}
258+
#endregion
259+
260+
[StructLayout(LayoutKind.Sequential)]
261+
private class NETRESOURCE
262+
{
263+
public int dwScope = 0;
264+
public int dwType = 0;
265+
public int dwDisplayType = 0;
266+
public int dwUsage = 0;
267+
public string lpLocalName = "";
268+
public string lpRemoteName = "";
269+
public string lpComment = "";
270+
public string lpProvider = "";
271+
}
130272
}
131273
}

‎plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/WmiCallsV2.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,7 @@ public static Boolean pingResource(String ip)
447447
pingReply = pingSender.Send(ipAddress, pingTimeout, buffer, pingOptions);
448448
if (pingReply.Status == IPStatus.Success)
449449
{
450+
System.Threading.Thread.Sleep(30000);
450451
return true;
451452
}
452453
else
@@ -591,11 +592,11 @@ private void RemoveStorageImageFromVm(ComputerSystem vm, string diskFileName)
591592
}
592593

593594
string hostResource = item.HostResource[0];
594-
if (!hostResource.Equals(diskFileName))
595+
if (Path.Equals(hostResource, diskFileName))
595596
{
596-
continue;
597+
imageToRemove = item;
598+
break;
597599
}
598-
imageToRemove = item;
599600
}
600601

601602
// assert
@@ -739,7 +740,6 @@ private void AttachIsoToVm(ComputerSystem vm, string isoPath)
739740
// 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.
740741
VirtualSystemSettingData vmSettings = GetVmSettings(vm);
741742
var driveWmiObj = GetDvdDriveSettings(vmSettings);
742-
743743
InsertDiskImage(vm, isoPath, IDE_ISO_DISK, driveWmiObj.Path);
744744
}
745745

0 commit comments

Comments
 (0)