DaanHoogland commented on a change in pull request #3575: [WIP DO NOT MERGE]
Health check feature for virtual router
URL: https://github.com/apache/cloudstack/pull/3575#discussion_r358198478
##########
File path:
server/src/main/java/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java
##########
@@ -1186,6 +1227,431 @@ protected void pushToUpdateQueue(final List<NetworkVO>
networks) throws Interrup
}
}
+ protected class FetchRouterHealthChecksResultTask extends
ManagedContextRunnable {
+ public FetchRouterHealthChecksResultTask() {
+ }
+
+ @Override
+ protected void runInContext() {
+ try {
+ final List<DomainRouterVO> routers =
_routerDao.listByStateAndManagementServer(VirtualMachine.State.Running,
mgmtSrvrId);
+ s_logger.debug("Found " + routers.size() + " running routers.
");
+
+ for (final DomainRouterVO router : routers) {
+ GetRouterMonitorResultsAnswer answer =
fetchAndUpdateRouterHealthChecks(router, false);
+ String checkFailsToRestartVr =
RouterHealthChecksFailuresToRestartVr.valueIn(router.getDataCenterId());
+ if (answer == null) {
+ s_logger.warn("Unable to fetch monitor results for
router " + router);
+ updateRouterConnectivityHealthCheck(router.getId(),
false, "Communication failed");
+ } else if (!answer.getResult()) {
+ s_logger.warn("Failed to fetch monitor results from
router " + router + " with details: " + answer.getDetails());
+ updateRouterConnectivityHealthCheck(router.getId(),
false, "Failed to fetch results with details: " + answer.getDetails());
+ } else {
+ updateRouterConnectivityHealthCheck(router.getId(),
true, "Successfully fetched data");
+ parseAndMergeDbHealthChecks(router.getId(),
answer.getMonitoringResults());
+
+ // Check failing tests and restart if needed
+ if (answer.getFailingChecks().size() > 0 &&
StringUtils.isNotBlank(checkFailsToRestartVr)) {
+ s_logger.info("Checking failed health checks to
see if router needs reboot");
+ for (String failedCheck :
answer.getFailingChecks()) {
+ if
(checkFailsToRestartVr.contains(failedCheck)) {
+ s_logger.info("Found failing health check
" + failedCheck + " so restarting router.");
+ rebootRouter(router.getId(), true);
+ }
+ }
+ }
+ }
+ }
+ } catch (final Exception ex) {
+ s_logger.error("Fail to complete the
FetchRouterHealthChecksResultTask! ", ex);
+ ex.printStackTrace();
+ }
+ }
+ }
+
+ private Map<String, Map<String, RouterHealthCheckResultVO>>
getHealthChecksFromDb(long routerId) {
+ List<RouterHealthCheckResultVO> healthChecksList =
routerHealthCheckResultDao.getHealthCheckResults(routerId);
+ Map<String, Map<String, RouterHealthCheckResultVO>> healthCheckResults
= new HashMap<>();
+ if (healthChecksList.isEmpty()) {
+ return healthCheckResults;
+ }
+
+ for (RouterHealthCheckResultVO healthCheck : healthChecksList) {
+ if (!healthCheckResults.containsKey(healthCheck.getCheckType())) {
+ healthCheckResults.put(healthCheck.getCheckType(), new
HashMap<>());
+ }
+
healthCheckResults.get(healthCheck.getCheckType()).put(healthCheck.getCheckName(),
healthCheck);
+ }
+
+ return healthCheckResults;
+ }
+
+ private RouterHealthCheckResultVO
updateRouterConnectivityHealthCheck(final long routerId, boolean connected,
String message) {
+ boolean newEntry = false;
+ RouterHealthCheckResultVO connectivityVO =
routerHealthCheckResultDao.getRouterHealthCheckResult(routerId, "connectivity",
"basic");
+ if (connectivityVO == null) {
+ connectivityVO = new RouterHealthCheckResultVO(routerId,
"connectivity", "basic");
+ newEntry = true;
+ }
+
+ connectivityVO.setCheckResult(connected);
+ connectivityVO.setLastUpdateTime(new Date());
+ connectivityVO.setCheckDetails(StringUtils.isNotEmpty(message) ?
message.getBytes(Charset.forName("US-ASCII")) : null);
+
+ if (newEntry) {
+ routerHealthCheckResultDao.persist(connectivityVO);
+ } else {
+ routerHealthCheckResultDao.update(connectivityVO.getId(),
connectivityVO);
+ }
+
+ return routerHealthCheckResultDao.getRouterHealthCheckResult(routerId,
"connectivity", "basic");
+ }
+
+ private List<RouterHealthCheckResult> parseAndMergeDbHealthChecks(final
long routerId, final String monitoringResult) {
+ if (StringUtils.isBlank(monitoringResult)) {
+ s_logger.warn("Attempted parsing empty monitoring results string
for router " + routerId);
+ return Collections.emptyList();
+ }
+
+ try {
+ s_logger.info("Parsing and updating DB health check data for
router: " + routerId);
+ s_logger.info("Retrieved data" + monitoringResult);
+ final Map<String, Map<String, RouterHealthCheckResultVO>>
checksInDb = getHealthChecksFromDb(routerId);
+ final Type t = new TypeToken<Map<String, Map<String, Map<String,
String>>>>() {}.getType();
+ final Map<String, Map<String, Map<String, String>>> checks =
GsonHelper.getGson().fromJson(monitoringResult, t);
+ final String lastRunKey = "lastRun";
+ List<RouterHealthCheckResult> healthChecks = new ArrayList<>();
+ for (String checkType : checks.keySet()) {
+ if (checks.get(checkType).containsKey(lastRunKey)) {
+ Map<String, String> lastRun =
checks.get(checkType).get(lastRunKey);
+ s_logger.info("Found check types executed on VR " +
checkType + ", start: " + lastRun.get("start") +
+ ", end: " + lastRun.get("end") + ", duration: " +
lastRun.get("duration"));
+ }
+
+ for (String checkName : checks.get(checkType).keySet()) {
+ if (lastRunKey.equals(checkName)) {
+ continue;
+ }
+ Map<String, String> checkData =
checks.get(checkType).get(checkName);
+ try {
+ boolean success =
Boolean.parseBoolean(checkData.get("success"));
+ Date lastUpdate = new
Date(Long.parseLong(checkData.get("lastUpdate")));
+ double lastRunDuration =
Double.parseDouble(checkData.get("lastRunDuration"));
+ String message = checkData.get("message");
+ final RouterHealthCheckResultVO hcVo;
+ boolean newEntry = false;
+ if (checksInDb.containsKey(checkType) &&
checksInDb.get(checkType).containsKey(checkName)) {
+ hcVo = checksInDb.get(checkType).get(checkName);
+ } else {
+ hcVo = new RouterHealthCheckResultVO(routerId,
checkName, checkType);
+ newEntry = true;
+ }
+
+ hcVo.setCheckResult(success);
+ hcVo.setLastUpdateTime(lastUpdate);
+ hcVo.setCheckDetails(StringUtils.isNotEmpty(message) ?
message.getBytes(Charset.forName("US-ASCII")) : null);
+ if (newEntry) {
+ routerHealthCheckResultDao.persist(hcVo);
+ } else {
+ routerHealthCheckResultDao.update(hcVo.getId(),
hcVo);
+ }
+ healthChecks.add(hcVo);
+ s_logger.info("Found health check " + hcVo + " which
took running duration (secs) " + lastRunDuration);
+ } catch (Exception ex) {
+ s_logger.error("Skipping health check: Exception while
parsing check result data for router id " + routerId +
+ ", check type: " + checkType + ", check name:
" + checkName + ":" + ex.getLocalizedMessage());
+ ex.printStackTrace();
+ }
+ }
+ }
+ return healthChecks;
+ } catch (JsonSyntaxException ex) {
+ s_logger.error("Unable to parse the result of health checks due to
" + ex.getLocalizedMessage());
+ ex.printStackTrace();
+ }
+
+ return Collections.emptyList();
+ }
+
+ // Returns null if health checks are not enabled
+ private GetRouterMonitorResultsAnswer
fetchAndUpdateRouterHealthChecks(DomainRouterVO router, boolean
performFreshChecks) {
+ if (!RouterHealthChecksEnabled.valueIn(router.getDataCenterId())) {
+ return null;
+ }
+
+ String controlIP = getRouterControlIP(router);
+ if (StringUtils.isNotBlank(controlIP) && !controlIP.equals("0.0.0.0"))
{
+ final GetRouterMonitorResultsCommand command = new
GetRouterMonitorResultsCommand(performFreshChecks);
+ command.setAccessDetail(NetworkElementCommand.ROUTER_IP,
controlIP);
+ command.setAccessDetail(NetworkElementCommand.ROUTER_NAME,
router.getInstanceName());
+ try {
+ final Answer answer = _agentMgr.easySend(router.getHostId(),
command);
+
+ if (answer == null) {
+ s_logger.warn("Unable to fetch monitoring results data
from router " + router.getHostName());
+ return null;
+ }
+ if (answer instanceof GetRouterMonitorResultsAnswer) {
+ return (GetRouterMonitorResultsAnswer) answer;
+ } else {
+ s_logger.warn("Unable to fetch health checks results to
router " + router.getHostName() + " Received answer " + answer.getDetails());
+ return new GetRouterMonitorResultsAnswer(command, false,
null, answer.getDetails());
+ }
+ } catch (final Exception e) {
+ s_logger.warn("Error while collecting alerts from router: " +
router.getInstanceName(), e);
+ return null;
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ public boolean performRouterHealthChecks(long routerId) {
+ DomainRouterVO router = _routerDao.findById(routerId);
+
+ if (router == null) {
+ throw new CloudRuntimeException("Unable to find router with id " +
routerId);
+ }
+
+ if (!RouterHealthChecksEnabled.valueIn(router.getDataCenterId())) {
+ throw new CloudRuntimeException("Router health checks are not
enabled in cluster router: " + router);
+ }
+
+ s_logger.info("Running health check results for router " +
router.getUuid());
+
+ // Step 1: Update health check data on router.
+ if (!updateRouterHealthCheckData(router)) {
+ s_logger.warn("Unable to update health check data for fresh run
successfully for router: " + router);
+ return false;
+ }
+ s_logger.info("Updated health check data for fresh run successfully
for router: " + router);
+
+ // Step 2: Perform and retrieve health checks on router
+ s_logger.info("Retrieving results for fresh health check execution for
router " + router.getUuid());
+ GetRouterMonitorResultsAnswer answer =
fetchAndUpdateRouterHealthChecks(router, true);
+
+ // Step 3: Update health checks values in database
+ if (answer == null || !answer.getResult()) {
+ updateRouterConnectivityHealthCheck(routerId, false,
+ answer == null ? "Communication failed " : "Failed to
fetch results with details: " + answer.getDetails());
+ } else {
+ updateRouterConnectivityHealthCheck(routerId, true, "Successfully
fetched data");
+ parseAndMergeDbHealthChecks(routerId,
answer.getMonitoringResults());
+ }
Review comment:
the methods called are also logging the warnings and the info seems
excessive in some cases. I like good logging, so don't be discouraged by this
comment. maybe simplify?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services