Skip to content

Commit b78aee8

Browse files
anshulgangwardevdeep
authored andcommitted
CLOUDSTACK-6401: [hyper-v] fixed correct host state, if host is up and hyper-v agent is down then the host state will be shown as up(actual host state) in cloudstack
1 parent d45ee3e commit b78aee8

4 files changed

Lines changed: 161 additions & 2 deletions

File tree

‎plugins/hypervisors/hyperv/DotNet/ServerResource/HypervResource/HypervResource.csproj‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,11 @@
8787
<None Include="packages.config" />
8888
</ItemGroup>
8989
<ItemGroup>
90+
<None Include="heartbeat.bat">
91+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
92+
</None>
93+
</ItemGroup>
94+
<ItemGroup>
9095
<ProjectReference Include="..\WmiWrappers\WmiWrappers.csproj">
9196
<Project>{db824727-bdc3-437c-a364-7a811d8a160f}</Project>
9297
<Name>WmiWrappers</Name>

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

Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,21 @@ public void setPrimaryStorage(string id, string path)
107107
config.Save(ConfigurationSaveMode.Modified);
108108
ConfigurationManager.RefreshSection("appSettings");
109109
}
110+
111+
public List<string> getAllPrimaryStorages()
112+
{
113+
List<string> poolPaths = new List<string>();
114+
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
115+
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
116+
foreach (string key in settings.AllKeys)
117+
{
118+
if (key.Contains("primary_storage_"))
119+
{
120+
poolPaths.Add(settings[key].Value);
121+
}
122+
}
123+
return poolPaths;
124+
}
110125
}
111126

112127
/// <summary>
@@ -775,16 +790,67 @@ public JContainer CheckOnHostCommand([FromBody]dynamic cmd)
775790
using (log4net.NDC.Push(Guid.NewGuid().ToString()))
776791
{
777792
logger.Info(CloudStackTypes.CheckOnHostCommand + Utils.CleanString(cmd.ToString()));
793+
string details = "host is not alive";
794+
bool result = true;
795+
try
796+
{
797+
foreach (string poolPath in config.getAllPrimaryStorages())
798+
{
799+
if (IsHostAlive(poolPath, (string)cmd.host.privateNetwork.ip))
800+
{
801+
result = false;
802+
details = "host is alive";
803+
break;
804+
}
805+
}
806+
}
807+
catch (Exception e)
808+
{
809+
logger.Error("Error Occurred in " + CloudStackTypes.CheckOnHostCommand + " : " + e.Message);
810+
}
811+
778812
object ansContent = new
779813
{
780-
result = true,
781-
details = "resource is alive",
814+
result = result,
815+
details = details,
782816
contextMap = contextMap
783817
};
784818
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.CheckOnHostAnswer);
785819
}
786820
}
787821

822+
private bool IsHostAlive(string poolPath, string privateIp)
823+
{
824+
bool hostAlive = false;
825+
try
826+
{
827+
string hbFile = Path.Combine(poolPath, "hb-" + privateIp);
828+
FileInfo file = new FileInfo(hbFile);
829+
using (StreamReader sr = file.OpenText())
830+
{
831+
string epoch = sr.ReadLine();
832+
string[] dateTime = epoch.Split('@');
833+
string[] date = dateTime[0].Split('-');
834+
string[] time = dateTime[1].Split(':');
835+
DateTime epochTime = new DateTime(Convert.ToInt32(date[0]), Convert.ToInt32(date[1]), Convert.ToInt32(date[2]), Convert.ToInt32(time[0]),
836+
Convert.ToInt32(time[1]), Convert.ToInt32(time[2]), DateTimeKind.Utc);
837+
DateTime currentTime = DateTime.UtcNow;
838+
DateTime ThreeMinuteLaterEpoch = epochTime.AddMinutes(3);
839+
if (currentTime.CompareTo(ThreeMinuteLaterEpoch) < 0)
840+
{
841+
hostAlive = true;
842+
}
843+
sr.Close();
844+
}
845+
}
846+
catch (Exception e)
847+
{
848+
logger.Info("Exception occurred in verifying host " + e.Message);
849+
}
850+
851+
return hostAlive;
852+
}
853+
788854
// POST api/HypervResource/CheckSshCommand
789855
// TODO: create test
790856
[HttpPost]
@@ -956,6 +1022,27 @@ public JContainer ModifyStoragePoolCommand([FromBody]dynamic cmd)
9561022
contextMap = contextMap
9571023
};
9581024

1025+
if (result)
1026+
{
1027+
try
1028+
{
1029+
if ((bool)cmd.add)
1030+
{
1031+
logger.Info("Adding HeartBeat Task to task scheduler for pool " + (string)cmd.pool.uuid);
1032+
Utils.AddHeartBeatTask((string)cmd.pool.uuid, hostPath, config.PrivateIpAddress);
1033+
}
1034+
else
1035+
{
1036+
logger.Info("Deleting HeartBeat Task from task scheduler for pool " + (string)cmd.pool.uuid);
1037+
Utils.RemoveHeartBeatTask(cmd.pool.uuid);
1038+
}
1039+
}
1040+
catch (Exception e)
1041+
{
1042+
logger.Error("Error occurred in adding/delete HeartBeat Task to/from Task Scheduler : " + e.Message);
1043+
}
1044+
}
1045+
9591046
return ReturnCloudStackTypedJArray(ansContent, CloudStackTypes.ModifyStoragePoolAnswer);
9601047
}
9611048
}
@@ -2151,6 +2238,7 @@ public JContainer StartupCommand([FromBody]dynamic cmdArray)
21512238

21522239
// Insert networking details
21532240
string privateIpAddress = strtRouteCmd.privateIpAddress;
2241+
config.PrivateIpAddress = privateIpAddress;
21542242
string subnet;
21552243
System.Net.NetworkInformation.NetworkInterface privateNic = GetNicInfoFromIpAddress(privateIpAddress, out subnet);
21562244
strtRouteCmd.privateIpAddress = privateIpAddress;

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,18 @@
2424
using System.Security.Principal;
2525
using System.Text;
2626
using System.Threading.Tasks;
27+
using System.Diagnostics;
28+
using System.Reflection;
2729

2830
namespace HypervResource
2931
{
3032
public class Utils
3133
{
3234
private static ILog s_logger = LogManager.GetLogger(typeof(Utils));
3335

36+
private const string TASK_PREFIX = "cloudstack-heartbeat-";
37+
private const string BATCH_FILE = "heartbeat.bat";
38+
3439
/// <summary>
3540
/// Associate CloudStack object's content with a fully qualified type name.
3641
/// </summary>
@@ -174,6 +179,44 @@ public static string CleanString(string stringToClean)
174179
return cleanString;
175180
}
176181

182+
public static void AddHeartBeatTask(string poolGuid, string poolPath, string hostPrivateIp)
183+
{
184+
string taskName = TASK_PREFIX + poolGuid;
185+
UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
186+
string alocation = Uri.UnescapeDataString(uri.Path);
187+
string batchFileLocation = Path.Combine(Path.GetDirectoryName(alocation), BATCH_FILE);
188+
string hbFile = Path.Combine(poolPath, "hb-" + hostPrivateIp);
189+
ExecuteTask("schtasks.exe", "/Create /RU \"SYSTEM\" /SC MINUTE /MO 1 /TN " + taskName + " /F /TR \"" + batchFileLocation + " " + hbFile + "\"");
190+
}
191+
192+
public static void RemoveHeartBeatTask(string poolGuid)
193+
{
194+
string taskName = TASK_PREFIX + poolGuid;
195+
ExecuteTask("schtasks.exe", "/Delete /TN " + taskName + " /F");
196+
}
197+
198+
public static void ExecuteTask(string command, string args)
199+
{
200+
ProcessStartInfo startInfo = new ProcessStartInfo();
201+
startInfo.CreateNoWindow = false;
202+
startInfo.UseShellExecute = true;
203+
startInfo.FileName = command;
204+
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
205+
startInfo.Arguments = args;
206+
207+
try
208+
{
209+
using (Process exeProcess = Process.Start(startInfo))
210+
{
211+
exeProcess.WaitForExit();
212+
}
213+
}
214+
catch (Exception e)
215+
{
216+
s_logger.Error("Error occurred in deleting or adding a scheduled task " + e.Message);
217+
}
218+
}
219+
177220
// from http://stackoverflow.com/a/2541569/939250
178221
#region imports
179222
[DllImport("advapi32.dll", SetLastError = true)]
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
@REM Licensed to the Apache Software Foundation (ASF) under one
2+
@REM or more contributor license agreements. See the NOTICE file
3+
@REM distributed with this work for additional information
4+
@REM regarding copyright ownership. The ASF licenses this file
5+
@REM to you under the Apache License, Version 2.0 (the
6+
@REM "License"); you may not use this file except in compliance
7+
@REM with the License. You may obtain a copy of the License at
8+
@REM
9+
@REM http://www.apache.org/licenses/LICENSE-2.0
10+
@REM
11+
@REM Unless required by applicable law or agreed to in writing,
12+
@REM software distributed under the License is distributed on an
13+
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
@REM KIND, either express or implied. See the License for the
15+
@REM specific language governing permissions and limitations
16+
@REM under the License.
17+
@REM
18+
@echo off
19+
@REM This script is based on:
20+
@REM http://stackoverflow.com/questions/9871499/how-to-get-utc-time-with-windows-batch-file
21+
22+
for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x
23+
echo %Year%-%Month%-%Day%@%Hour%:%Minute%:%Second%>%1

0 commit comments

Comments
 (0)