cloudstack-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From t..@apache.org
Subject [44/50] [abbrv] CLOUDSTACK-664:AWS-Health Check feature: Patch applied cleanly , RAT build is successful
Date Mon, 18 Mar 2013 12:27:10 GMT
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
index abea464..4eb0ce2 100644
--- a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
+++ b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java
@@ -11,11 +11,12 @@
 // 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 
+// KIND, either express or implied.  See the License for the
 // specific language governing permissions and limitations
 // under the License.
 package com.cloud.network.resource;
 
+import java.util.ArrayList;
 import java.util.Formatter;
 import java.util.HashMap;
 import java.util.List;
@@ -31,6 +32,7 @@ import com.citrix.netscaler.nitro.resource.base.base_response;
 import com.citrix.netscaler.nitro.resource.config.autoscale.autoscalepolicy;
 import com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleprofile;
 import com.citrix.netscaler.nitro.resource.config.basic.server_service_binding;
+import com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding;
 import com.citrix.netscaler.nitro.resource.config.basic.servicegroup;
 import com.citrix.netscaler.nitro.resource.config.basic.servicegroup_lbmonitor_binding;
 import com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable;
@@ -71,6 +73,8 @@ import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupExternalLoadBalancerCommand;
 import com.cloud.agent.api.routing.CreateLoadBalancerApplianceCommand;
 import com.cloud.agent.api.routing.DestroyLoadBalancerApplianceCommand;
+import com.cloud.agent.api.routing.HealthCheckLBConfigAnswer;
+import com.cloud.agent.api.routing.HealthCheckLBConfigCommand;
 import com.cloud.agent.api.routing.IpAssocAnswer;
 import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
@@ -84,6 +88,7 @@ import com.cloud.agent.api.to.LoadBalancerTO.AutoScaleVmProfileTO;
 import com.cloud.agent.api.to.LoadBalancerTO.ConditionTO;
 import com.cloud.agent.api.to.LoadBalancerTO.CounterTO;
 import com.cloud.agent.api.to.LoadBalancerTO.DestinationTO;
+import com.cloud.agent.api.to.LoadBalancerTO.HealthCheckPolicyTO;
 import com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO;
 import com.cloud.agent.api.to.StaticNatRuleTO;
 import org.apache.cloudstack.api.ApiConstants;
@@ -396,12 +401,14 @@ public class NetscalerResource implements ServerResource {
             return execute((DestroyLoadBalancerApplianceCommand) cmd, numRetries);
         } else if (cmd instanceof SetStaticNatRulesCommand) {
             return execute((SetStaticNatRulesCommand) cmd, numRetries);
-        } else {
+        } else if (cmd instanceof HealthCheckLBConfigCommand) {
+           return execute((HealthCheckLBConfigCommand) cmd, numRetries);
+        }else {
             return Answer.createUnsupportedCommandAnswer(cmd);
         }
     }
 
-    private Answer execute(ReadyCommand cmd) {
+	private Answer execute(ReadyCommand cmd) {
         return new ReadyAnswer(cmd);
     }
 
@@ -450,6 +457,65 @@ public class NetscalerResource implements ServerResource {
         return new IpAssocAnswer(cmd, results);
     }
 
+    private Answer execute(HealthCheckLBConfigCommand cmd, int numRetries) {
+
+        List<LoadBalancerTO> hcLB = new ArrayList<LoadBalancerTO>();
+        try {
+
+            if (_isSdx) {
+                return Answer.createUnsupportedCommandAnswer(cmd);
+            }
+
+            LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers();
+
+            if (loadBalancers == null) {
+                return new HealthCheckLBConfigAnswer(hcLB);
+            }
+
+            for (LoadBalancerTO loadBalancer : loadBalancers) {
+                HealthCheckPolicyTO[] healthCheckPolicies = loadBalancer.getHealthCheckPolicies();
+                if ((healthCheckPolicies != null) && (healthCheckPolicies.length > 0)
+                        && (healthCheckPolicies[0] != null)) {
+                    String nsVirtualServerName = generateNSVirtualServerName(loadBalancer.getSrcIp(),
+                            loadBalancer.getSrcPort());
+
+                    com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding
+                            .get(_netscalerService, nsVirtualServerName);
+
+                    if (serviceBindings != null) {
+                        for (DestinationTO destination : loadBalancer.getDestinations()) {
+                            String nsServiceName = generateNSServiceName(destination.getDestIp(),
+                                    destination.getDestPort());
+                            for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) {
+                                if (nsServiceName.equalsIgnoreCase(binding.get_servicename())) {
+                                    destination.setMonitorState(binding.get_curstate());
+                                    break;
+                                }
+                            }
+                        }
+                        hcLB.add(loadBalancer);
+                    }
+                }
+            }
+
+        } catch (ExecutionException e) {
+            s_logger.error("Failed to execute HealthCheckLBConfigCommand due to ", e);
+            if (shouldRetry(numRetries)) {
+                return retry(cmd, numRetries);
+            } else {
+                return new HealthCheckLBConfigAnswer(hcLB);
+            }
+        } catch (Exception e) {
+            s_logger.error("Failed to execute HealthCheckLBConfigCommand due to ", e);
+            if (shouldRetry(numRetries)) {
+                return retry(cmd, numRetries);
+            } else {
+                return new HealthCheckLBConfigAnswer(hcLB);
+            }
+        }
+        return new HealthCheckLBConfigAnswer(hcLB);
+    }
+
     private synchronized Answer execute(LoadBalancerConfigCommand cmd, int numRetries) {
         try {
             if (_isSdx) {
@@ -467,12 +533,13 @@ public class NetscalerResource implements ServerResource {
                 String lbProtocol = getNetScalerProtocol(loadBalancer);
                 String lbAlgorithm = loadBalancer.getAlgorithm();
                 String nsVirtualServerName  = generateNSVirtualServerName(srcIp, srcPort);
-
+                String nsMonitorName = generateNSMonitorName(srcIp, srcPort);
                 if(loadBalancer.isAutoScaleVmGroupTO()) {
                     applyAutoScaleConfig(loadBalancer);
                     return new Answer(cmd);
                 }
-
+                boolean hasMonitor = false;
+                boolean deleteMonitor = false;
                 boolean destinationsToAdd = false;
                 for (DestinationTO destination : loadBalancer.getDestinations()) {
                     if (!destination.isRevoked()) {
@@ -489,11 +556,28 @@ public class NetscalerResource implements ServerResource {
                         s_logger.debug("Created load balancing virtual server " + nsVirtualServerName + " on the Netscaler device");
                     }
 
+                    // create a new monitor
+                    HealthCheckPolicyTO[] healthCheckPolicies = loadBalancer.getHealthCheckPolicies();
+                    if ((healthCheckPolicies != null) && (healthCheckPolicies.length > 0)
+                            && (healthCheckPolicies[0] != null)) {
+
+                        for (HealthCheckPolicyTO healthCheckPolicyTO : healthCheckPolicies) {
+                            if ( !healthCheckPolicyTO.isRevoked() ) {
+                                addLBMonitor(nsMonitorName, lbProtocol, healthCheckPolicyTO);
+                                hasMonitor = true;
+                            }
+                            else {
+                                deleteMonitor = true;
+                                hasMonitor = false;
+                            }
+                        }
+
+                    }
+
                     for (DestinationTO destination : loadBalancer.getDestinations()) {
 
                         String nsServerName = generateNSServerName(destination.getDestIp());
                         String nsServiceName = generateNSServiceName(destination.getDestIp(), destination.getDestPort());
-
                         if (!destination.isRevoked()) {
                             // add a new destination to deployed load balancing rule
 
@@ -534,6 +618,26 @@ public class NetscalerResource implements ServerResource {
                                     throw new ExecutionException("Failed to bind service: " + nsServiceName + " to the lb virtual server: " + nsVirtualServerName + " on Netscaler device");
                                 }
                             }
+
+                            // After binding the service to the LB Vserver
+                            // successfully, bind the created monitor to the
+                            // service.
+                            if (hasMonitor) {
+                                if (!isServiceBoundToMonitor(nsServiceName, nsMonitorName)) {
+                                    bindServiceToMonitor(nsServiceName, nsMonitorName);
+                                }
+                            } else {
+                                // check if any monitor created by CS is already
+                                // existing, if yes, unbind it from services and
+                                // delete it.
+                                if (nsMonitorExist(nsMonitorName)) {
+                                    // unbind the service from the monitor and
+                                    // delete the monitor
+                                    unBindServiceToMonitor(nsServiceName, nsMonitorName);
+                                    deleteMonitor = true;
+                                }
+
+                            }
                             if (s_logger.isDebugEnabled()) {
                                 s_logger.debug("Successfully added LB destination: " + destination.getDestIp() + ":" + destination.getDestPort() + " to load balancer " + srcIp + ":" + srcPort);
                             }
@@ -609,8 +713,13 @@ public class NetscalerResource implements ServerResource {
                             }
                         }
                         removeLBVirtualServer(nsVirtualServerName);
+                        deleteMonitor = true;
                     }
                 }
+                if(deleteMonitor) {
+                    removeLBMonitor(nsMonitorName);
+                }
+
             }
 
             if (s_logger.isInfoEnabled()) {
@@ -1223,23 +1332,64 @@ public class NetscalerResource implements ServerResource {
         }
     }
 
+    private lbmonitor getMonitorIfExisits(String lbMonitorName) throws ExecutionException {
+        try {
+            return lbmonitor.get(_netscalerService, lbMonitorName);
+        } catch (nitro_exception e) {
+            if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) {
+                return null;
+            } else {
+                throw new ExecutionException(e.getMessage());
+            }
+        } catch (Exception e) {
+            throw new ExecutionException(e.getMessage());
+        }
+   }
+
     private boolean isServiceBoundToVirtualServer(String serviceName) throws ExecutionException {
         try {
             lbvserver[] lbservers = lbvserver.get(_netscalerService);
             for (lbvserver vserver : lbservers) {
                 filtervalue[] filter = new filtervalue[1];
                 filter[0] = new filtervalue("servicename", serviceName);
-                lbvserver_service_binding[] result = lbvserver_service_binding.get_filtered(_netscalerService, vserver.get_name(), filter);
+                lbvserver_service_binding[] result = lbvserver_service_binding.get_filtered(_netscalerService,
+                        vserver.get_name(), filter);
                 if (result != null && result.length > 0) {
                     return true;
                 }
             }
             return false;
         } catch (Exception e) {
-            throw new ExecutionException("Failed to verify service " + serviceName + " is bound to any virtual server due to " + e.getMessage());
+            throw new ExecutionException("Failed to verify service " + serviceName
+                    + " is bound to any virtual server due to " + e.getMessage());
         }
     }
 
+    private boolean isServiceBoundToMonitor(String nsServiceName, String nsMonitorName) throws ExecutionException {
+
+        filtervalue[] filter = new filtervalue[1];
+        filter[0] = new filtervalue("monitor_name", nsMonitorName);
+        service_lbmonitor_binding[] result;
+        try {
+            result = service_lbmonitor_binding.get_filtered(_netscalerService, nsServiceName, filter);
+            if (result != null && result.length > 0) {
+                return true;
+            }
+
+        } catch (Exception e) {
+            throw new ExecutionException("Failed to verify service " + nsServiceName
+                    + " is bound to any monitor due to " + e.getMessage());
+        }
+        return false;
+    }
+
+    private boolean nsMonitorExist(String nsMonitorname) throws ExecutionException {
+        if (getMonitorIfExisits(nsMonitorname) != null)
+            return true;
+        else
+            return false;
+    }
+
     private boolean nsServiceExists(String serviceName) throws ExecutionException {
         try {
             if (com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName) != null) {
@@ -1480,6 +1630,126 @@ public class NetscalerResource implements ServerResource {
         }
     }
 
+    // Monitor related methods
+    private void addLBMonitor(String nsMonitorName, String lbProtocol, HealthCheckPolicyTO hcp)
+            throws ExecutionException {
+        try {
+            // check if the monitor exists
+            boolean csMonitorExisis = false;
+            lbmonitor csMonitor = getMonitorIfExisits(nsMonitorName);
+            if (csMonitor != null) {
+                if (!csMonitor.get_type().equalsIgnoreCase(lbProtocol)) {
+                    throw new ExecutionException("Can not update monitor :" + nsMonitorName + " as current protocol:"
+                            + csMonitor.get_type() + " of monitor is different from the " + " intended protocol:"
+                            + lbProtocol);
+                }
+                csMonitorExisis = true;
+            }
+            if (!csMonitorExisis) {
+                lbmonitor csMon = new lbmonitor();
+                csMon.set_monitorname(nsMonitorName);
+                csMon.set_type(lbProtocol);
+                if (lbProtocol.equalsIgnoreCase("HTTP")) {
+                    csMon.set_httprequest(hcp.getpingPath());
+                    s_logger.trace("LB Protocol is HTTP,  Applying  ping path on HealthCheck Policy");
+                } else {
+                    s_logger.debug("LB Protocol is not HTTP, Skipping to apply  ping path on HealthCheck Policy");
+                }
+
+                csMon.set_interval(hcp.getHealthcheckInterval());
+                csMon.set_resptimeout(hcp.getResponseTime());
+                csMon.set_failureretries(hcp.getUnhealthThresshold());
+                csMon.set_successretries(hcp.getHealthcheckThresshold());
+                s_logger.debug("Monitor properites going to get created :interval :: " + csMon.get_interval() + "respTimeOUt:: " + csMon.get_resptimeout()
+                        +"failure retires(unhealththresshold) :: " + csMon.get_failureretries() + "successtries(healththresshold) ::" + csMon.get_successretries());
+                lbmonitor.add(_netscalerService, csMon);
+            } else {
+                s_logger.debug("Monitor :" + nsMonitorName + " is already existing. Skipping to delete and create it");
+            }
+        } catch (nitro_exception e) {
+            throw new ExecutionException("Failed to create new monitor :" + nsMonitorName + " due to " + e.getMessage());
+        } catch (Exception e) {
+            throw new ExecutionException("Failed to create new monitor :" + nsMonitorName + " due to " + e.getMessage());
+        }
+    }
+
+    private void bindServiceToMonitor(String nsServiceName, String nsMonitorName) throws ExecutionException {
+
+        try {
+            com.citrix.netscaler.nitro.resource.config.basic.service serviceObject = new com.citrix.netscaler.nitro.resource.config.basic.service();
+            serviceObject = com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService,
+                    nsServiceName);
+            if (serviceObject != null) {
+                com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding serviceMonitor = new com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding();
+                serviceMonitor.set_monitor_name(nsMonitorName);
+                serviceMonitor.set_name(nsServiceName);
+                serviceMonitor.set_monstate("ENABLED");
+                s_logger.debug("Trying to bind  the monitor :" + nsMonitorName + " to the service :" + nsServiceName);
+                com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding.add(_netscalerService,
+                        serviceMonitor);
+                s_logger.debug("Successfully binded the monitor :" + nsMonitorName + " to the service :"
+                        + nsServiceName);
+            }
+        } catch (nitro_exception e) {
+            throw new ExecutionException("Failed to create new monitor :" + nsMonitorName + " due to " + e.getMessage());
+        } catch (Exception e) {
+            throw new ExecutionException("Failed to create new monitor :" + nsMonitorName + " due to " + e.getMessage());
+        }
+    }
+
+    private void unBindServiceToMonitor(String nsServiceName, String nsMonitorName) throws ExecutionException {
+
+        try {
+            com.citrix.netscaler.nitro.resource.config.basic.service serviceObject = new com.citrix.netscaler.nitro.resource.config.basic.service();
+            serviceObject = com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService,
+                    nsServiceName);
+
+            if (serviceObject != null) {
+                com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding serviceMonitor = new com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding();
+                serviceMonitor.set_monitor_name(nsMonitorName);
+                serviceMonitor.set_name(nsServiceName);
+                s_logger.debug("Trying to unbind  the monitor :" + nsMonitorName + " from the service :"
+                        + nsServiceName);
+                service_lbmonitor_binding.delete(_netscalerService, serviceMonitor);
+                s_logger.debug("Successfully unbinded the monitor :" + nsMonitorName + " from the service :"
+                        + nsServiceName);
+            }
+
+        } catch (nitro_exception e) {
+            if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) {
+                return;
+            } else {
+                throw new ExecutionException("Failed to unbind monitor :" + nsMonitorName + "from the service :"
+                        + nsServiceName + "due to " + e.getMessage());
+            }
+        } catch (Exception e) {
+            throw new ExecutionException("Failed to unbind monitor :" + nsMonitorName + "from the service :"
+                    + nsServiceName + "due to " + e.getMessage());
+        }
+
+    }
+
+    private void removeLBMonitor(String nsMonitorName) throws ExecutionException {
+
+        try {
+            if (nsMonitorExist(nsMonitorName)) {
+                lbmonitor monitorObj = lbmonitor.get(_netscalerService, nsMonitorName);
+                monitorObj.set_respcode(null);
+                lbmonitor.delete(_netscalerService, monitorObj);
+                s_logger.info("Successfully deleted monitor : " + nsMonitorName);
+            }
+        } catch (nitro_exception e) {
+            if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) {
+                return;
+            } else {
+                throw new ExecutionException("Failed to delete monitor :" + nsMonitorName + " due to " + e.getMessage());
+            }
+        } catch (Exception e) {
+            throw new ExecutionException("Failed to delete monitor :" + nsMonitorName + " due to " + e.getMessage());
+        }
+
+    }
+
     public synchronized void applyAutoScaleConfig(LoadBalancerTO loadBalancer) throws Exception, ExecutionException {
 
         AutoScaleVmGroupTO vmGroupTO = loadBalancer.getAutoScaleVmGroupTO();
@@ -2229,6 +2499,11 @@ public class NetscalerResource implements ServerResource {
         return genObjectName("Cloud-VirtualServer", srcIp, srcPort);
     }
 
+    private String generateNSMonitorName(String srcIp, long srcPort) {
+        // maximum length supported by NS is 31
+        return genObjectName("Cloud-Hc", srcIp, srcPort);
+    }
+
     private String generateNSServerName(String serverIP) {
         return genObjectName("Cloud-Server-",  serverIP);
     }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/api/ApiResponseHelper.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java
index 2546f29..ebf0fcf 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -46,6 +46,8 @@ import org.apache.cloudstack.api.response.ControlledViewEntityResponse;
 import org.apache.cloudstack.api.response.IPAddressResponse;
 import org.apache.cloudstack.api.response.InstanceGroupResponse;
 import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
+import org.apache.cloudstack.api.response.LBHealthCheckPolicyResponse;
+import org.apache.cloudstack.api.response.LBHealthCheckResponse;
 import org.apache.cloudstack.api.response.LBStickinessPolicyResponse;
 import org.apache.cloudstack.api.response.LBStickinessResponse;
 import org.apache.cloudstack.api.response.LDAPConfigResponse;
@@ -143,6 +145,13 @@ import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.network.router.VirtualRouter;
 import com.cloud.network.rules.*;
+import com.cloud.network.rules.FirewallRule;
+import com.cloud.network.rules.FirewallRuleVO;
+import com.cloud.network.rules.HealthCheckPolicy;
+import com.cloud.network.rules.LoadBalancer;
+import com.cloud.network.rules.PortForwardingRule;
+import com.cloud.network.rules.StaticNatRule;
+import com.cloud.network.rules.StickinessPolicy;
 import com.cloud.network.security.SecurityGroup;
 import com.cloud.network.security.SecurityGroupVO;
 import com.cloud.network.security.SecurityRule;
@@ -2751,6 +2760,58 @@ public class ApiResponseHelper implements ResponseGenerator {
     }
 
     @Override
+    public LBHealthCheckResponse createLBHealthCheckPolicyResponse(
+            List<? extends HealthCheckPolicy> healthcheckPolicies, LoadBalancer lb) {
+        LBHealthCheckResponse hcResponse = new LBHealthCheckResponse();
+
+        if (lb == null)
+            return hcResponse;
+        hcResponse.setlbRuleId(lb.getUuid());
+        Account account = ApiDBUtils.findAccountById(lb.getAccountId());
+        if (account != null) {
+            hcResponse.setAccountName(account.getAccountName());
+            Domain domain = ApiDBUtils.findDomainById(account.getDomainId());
+            if (domain != null) {
+                hcResponse.setDomainId(domain.getUuid());
+                hcResponse.setDomainName(domain.getName());
+            }
+        }
+
+        List<LBHealthCheckPolicyResponse> responses = new ArrayList<LBHealthCheckPolicyResponse>();
+        for (HealthCheckPolicy healthcheckPolicy : healthcheckPolicies) {
+            LBHealthCheckPolicyResponse ruleResponse = new LBHealthCheckPolicyResponse(healthcheckPolicy);
+            responses.add(ruleResponse);
+        }
+        hcResponse.setRules(responses);
+
+        hcResponse.setObjectName("healthcheckpolicies");
+        return hcResponse;
+    }
+
+    @Override
+    public LBHealthCheckResponse createLBHealthCheckPolicyResponse(HealthCheckPolicy healthcheckPolicy, LoadBalancer lb) {
+        LBHealthCheckResponse hcResponse = new LBHealthCheckResponse();
+
+        hcResponse.setlbRuleId(lb.getUuid());
+        Account accountTemp = ApiDBUtils.findAccountById(lb.getAccountId());
+        if (accountTemp != null) {
+            hcResponse.setAccountName(accountTemp.getAccountName());
+            Domain domain = ApiDBUtils.findDomainById(accountTemp.getDomainId());
+            if (domain != null) {
+                hcResponse.setDomainId(domain.getUuid());
+                hcResponse.setDomainName(domain.getName());
+            }
+        }
+
+        List<LBHealthCheckPolicyResponse> responses = new ArrayList<LBHealthCheckPolicyResponse>();
+        LBHealthCheckPolicyResponse ruleResponse = new LBHealthCheckPolicyResponse(healthcheckPolicy);
+        responses.add(ruleResponse);
+        hcResponse.setRules(responses);
+        hcResponse.setObjectName("healthcheckpolicies");
+        return hcResponse;
+    }
+
+    @Override
     public LDAPConfigResponse createLDAPConfigResponse(String hostname,
             Integer port, Boolean useSSL, String queryFilter,
             String searchBase, String bindDN) {

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/configuration/Config.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java
index d01ea5b..9db7dbd 100755
--- a/server/src/com/cloud/configuration/Config.java
+++ b/server/src/com/cloud/configuration/Config.java
@@ -207,7 +207,11 @@ public enum Config {
     AlertPurgeInterval("Advanced", ManagementServer.class, Integer.class, "alert.purge.interval", "86400", "The interval (in seconds) to wait before running the alert purge thread", null),
     AlertPurgeDelay("Advanced", ManagementServer.class, Integer.class, "alert.purge.delay", "0", "Alerts older than specified number days will be purged. Set this value to 0 to never delete alerts", null),
 
-    DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"),
+    // LB HealthCheck Interval.
+    LBHealthCheck("Advanced", ManagementServer.class, String.class, "healthcheck.update.interval", "600",
+            "Time Interval to fetch the LB health check states (in sec)", null),
+
+	DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"),
 	DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null),
 	CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"),
 	NetworkGcWait("Advanced", ManagementServer.class, Integer.class, "network.gc.wait", "600", "Time (in seconds) to wait before shutting down a network that's not in used", null),

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/ExternalLoadBalancerDeviceManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManager.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManager.java
index d979f07..dee3ca9 100644
--- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManager.java
+++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManager.java
@@ -18,6 +18,7 @@ package com.cloud.network;
 
 import java.util.List;
 
+import com.cloud.agent.api.to.LoadBalancerTO;
 import com.cloud.exception.InsufficientCapacityException;
 import com.cloud.exception.ResourceUnavailableException;
 import com.cloud.host.Host;
@@ -96,7 +97,9 @@ public interface ExternalLoadBalancerDeviceManager extends Manager{
      * @throws ResourceUnavailableException
      * @throws InsufficientCapacityException
      */
-    public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException, 
+    public boolean manageGuestNetworkWithExternalLoadBalancer(boolean add, Network guestConfig) throws ResourceUnavailableException,
             InsufficientCapacityException;
-    
+
+    public List<LoadBalancerTO> getLBHealthChecks(Network network, List<? extends FirewallRule> rules)
+            throws ResourceUnavailableException;
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
index d7b6d78..049099d 100644
--- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
+++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java
@@ -34,6 +34,8 @@ import com.cloud.agent.api.StartupCommand;
 import com.cloud.agent.api.StartupExternalLoadBalancerCommand;
 import com.cloud.agent.api.routing.CreateLoadBalancerApplianceCommand;
 import com.cloud.agent.api.routing.DestroyLoadBalancerApplianceCommand;
+import com.cloud.agent.api.routing.HealthCheckLBConfigAnswer;
+import com.cloud.agent.api.routing.HealthCheckLBConfigCommand;
 import com.cloud.agent.api.routing.IpAssocCommand;
 import com.cloud.agent.api.routing.LoadBalancerConfigCommand;
 import com.cloud.agent.api.routing.NetworkElementCommand;
@@ -888,7 +890,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
 
             if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) {
                 boolean inline = _networkMgr.isNetworkInlineMode(network);
-                LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies());
+                LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies());
                 if (rule.isAutoScaleConfig()) {
                     loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup());
                 }
@@ -1111,4 +1113,95 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase
         s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId());
         return (IpDeployer)element;
     }
+
+    @Override
+    public List<LoadBalancerTO> getLBHealthChecks(Network network, List<? extends FirewallRule> rules)
+            throws ResourceUnavailableException {
+
+        // Find the external load balancer in this zone
+        long zoneId = network.getDataCenterId();
+        DataCenterVO zone = _dcDao.findById(zoneId);
+        HealthCheckLBConfigAnswer answer = null;
+
+        List<LoadBalancingRule> loadBalancingRules = new ArrayList<LoadBalancingRule>();
+
+        for (FirewallRule rule : rules) {
+            if (rule.getPurpose().equals(Purpose.LoadBalancing)) {
+                loadBalancingRules.add((LoadBalancingRule) rule);
+            }
+        }
+
+        if (loadBalancingRules == null || loadBalancingRules.isEmpty()) {
+            return null;
+        }
+
+        ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
+        if (lbDeviceVO == null) {
+            s_logger.warn("There is no external load balancer device assigned to this network either network is not implement are already shutdown so just returning");
+            return null;
+        }
+
+        HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
+
+        boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network);
+
+        if (network.getState() == Network.State.Allocated) {
+            s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId()
+                    + "; this network is not implemented. Skipping backend commands.");
+            return null;
+        }
+
+        List<LoadBalancerTO> loadBalancersToApply = new ArrayList<LoadBalancerTO>();
+        List<MappingState> mappingStates = new ArrayList<MappingState>();
+        for (int i = 0; i < loadBalancingRules.size(); i++) {
+            LoadBalancingRule rule = loadBalancingRules.get(i);
+
+            boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke));
+            String protocol = rule.getProtocol();
+            String algorithm = rule.getAlgorithm();
+            String uuid = rule.getUuid();
+            String srcIp = _networkModel.getIp(rule.getSourceIpAddressId()).getAddress().addr();
+            int srcPort = rule.getSourcePortStart();
+            List<LbDestination> destinations = rule.getDestinations();
+
+            if (externalLoadBalancerIsInline) {
+                MappingNic nic = getLoadBalancingIpNic(zone, network, rule.getSourceIpAddressId(), revoked, null);
+                mappingStates.add(nic.getState());
+                NicVO loadBalancingIpNic = nic.getNic();
+                if (loadBalancingIpNic == null) {
+                    continue;
+                }
+
+                // Change the source IP address for the load balancing rule to
+                // be the load balancing IP address
+                srcIp = loadBalancingIpNic.getIp4Address();
+            }
+
+            if ((destinations != null && !destinations.isEmpty()) || !rule.isAutoScaleConfig()) {
+                boolean inline = _networkMgr.isNetworkInlineMode(network);
+                LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked,
+                        false, inline, destinations, rule.getStickinessPolicies(), rule.getHealthCheckPolicies());
+                loadBalancersToApply.add(loadBalancer);
+            }
+        }
+
+        try {
+            if (loadBalancersToApply.size() > 0) {
+                int numLoadBalancersForCommand = loadBalancersToApply.size();
+                LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply
+                        .toArray(new LoadBalancerTO[numLoadBalancersForCommand]);
+                // LoadBalancerConfigCommand cmd = new
+                // LoadBalancerConfigCommand(loadBalancersForCommand, null);
+                HealthCheckLBConfigCommand cmd = new HealthCheckLBConfigCommand(loadBalancersForCommand);
+                long guestVlanTag = Integer.parseInt(network.getBroadcastUri().getHost());
+                cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag));
+
+                answer = (HealthCheckLBConfigAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd);
+            }
+        } catch (Exception ex) {
+            s_logger.error("Exception Occured ", ex);
+        }
+        return answer.getLoadBalancers();
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/LBHealthCheckPolicyVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/LBHealthCheckPolicyVO.java b/server/src/com/cloud/network/LBHealthCheckPolicyVO.java
new file mode 100644
index 0000000..ed03a2b
--- /dev/null
+++ b/server/src/com/cloud/network/LBHealthCheckPolicyVO.java
@@ -0,0 +1,157 @@
+// 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.
+package com.cloud.network;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+import com.cloud.network.rules.HealthCheckPolicy;
+import org.apache.cloudstack.api.InternalIdentity;
+
+@Entity
+@Table(name = ("load_balancer_healthcheck_policies"))
+@PrimaryKeyJoinColumn(name = "load_balancer_id", referencedColumnName = "id")
+public class LBHealthCheckPolicyVO implements HealthCheckPolicy {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    @Column(name = "id")
+    private long id;
+
+    @Column(name = "load_balancer_id")
+    private long loadBalancerId;
+
+    @Column(name = "pingpath")
+    private String pingPath;
+
+    @Column(name = "description")
+    private String description;
+
+    @Column(name = "uuid")
+    private String uuid;
+
+    @Column(name = "response_time")
+    private int responseTime;
+
+    @Column(name = "healthcheck_interval")
+    private int healthcheckInterval;
+
+    @Column(name = "healthcheck_thresshold")
+    private int healthcheckThresshold;
+
+    @Column(name = "unhealth_thresshold")
+    private int unhealthThresshold;
+
+    @Column(name = "revoke")
+    private boolean revoke = false;
+
+    protected LBHealthCheckPolicyVO() {
+        this.uuid = UUID.randomUUID().toString();
+    }
+
+    public LBHealthCheckPolicyVO(long loadBalancerId, String pingPath, String description, int responseTime,
+            int healthcheckInterval, int healthcheckThresshold, int unhealthThresshold) {
+        this.loadBalancerId = loadBalancerId;
+
+        if (pingPath == null || pingPath.isEmpty())
+            this.pingPath = "/";
+        else
+            this.pingPath = pingPath;
+
+        if (responseTime == 0)
+            this.responseTime = 2;
+        else
+            this.responseTime = responseTime;
+
+        if (healthcheckInterval == 0)
+            this.healthcheckInterval = 5;
+        else
+            this.healthcheckInterval = healthcheckInterval;
+
+        if (healthcheckThresshold == 0)
+            this.healthcheckThresshold = 2;
+        else
+            this.healthcheckThresshold = healthcheckThresshold;
+
+        if (unhealthThresshold == 0)
+            this.unhealthThresshold = 1;
+        else
+            this.unhealthThresshold = unhealthThresshold;
+        this.uuid = UUID.randomUUID().toString();
+
+    }
+
+    public int getResponseTime() {
+        return responseTime;
+    }
+
+    public int getHealthcheckInterval() {
+        return healthcheckInterval;
+    }
+
+    public int getHealthcheckThresshold() {
+        return healthcheckThresshold;
+    }
+
+    public int getUnhealthThresshold() {
+        return unhealthThresshold;
+    }
+
+    public long getId() {
+        return id;
+    }
+
+    public long getLoadBalancerId() {
+        return loadBalancerId;
+    }
+
+    public String getpingpath() {
+        return pingPath;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public boolean isRevoke() {
+        return revoke;
+    }
+
+    public void setRevoke(boolean revoke) {
+        this.revoke = revoke;
+    }
+
+    @Override
+    public String getUuid() {
+        return this.uuid;
+    }
+
+    public void setUuid(String uuid) {
+        this.uuid = uuid;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/NetworkManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java
index 3220c91..591910b 100755
--- a/server/src/com/cloud/network/NetworkManagerImpl.java
+++ b/server/src/com/cloud/network/NetworkManagerImpl.java
@@ -106,6 +106,7 @@ import com.cloud.network.element.UserDataServiceProvider;
 import com.cloud.network.guru.NetworkGuru;
 import com.cloud.network.lb.LoadBalancingRule;
 import com.cloud.network.lb.LoadBalancingRule.LbDestination;
+import com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy;
 import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
 import com.cloud.network.lb.LoadBalancingRulesManager;
 import com.cloud.network.rules.*;
@@ -2310,52 +2311,51 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
     @Override
     public boolean applyRules(List<? extends FirewallRule> rules, FirewallRule.Purpose purpose,
             NetworkRuleApplier applier, boolean continueOnError) throws ResourceUnavailableException {
-    	if (rules == null || rules.size() == 0) {
-    		s_logger.debug("There are no rules to forward to the network elements");
-    		return true;
-    	}
+        if (rules == null || rules.size() == 0) {
+            s_logger.debug("There are no rules to forward to the network elements");
+            return true;
+        }
 
-    	boolean success = true;
-    	Network network = _networksDao.findById(rules.get(0).getNetworkId());
+        boolean success = true;
+        Network network = _networksDao.findById(rules.get(0).getNetworkId());
         FirewallRuleVO.TrafficType trafficType = rules.get(0).getTrafficType();
-         List<PublicIp> publicIps = new ArrayList<PublicIp>();
+        List<PublicIp> publicIps = new ArrayList<PublicIp>();
 
-        if (! (rules.get(0).getPurpose() == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress)) {
+        if (!(rules.get(0).getPurpose() == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress)) {
             // get the list of public ip's owned by the network
             List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null);
             if (userIps != null && !userIps.isEmpty()) {
                 for (IPAddressVO userIp : userIps) {
-    			PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
-    			publicIps.add(publicIp);
-	                }
-             }
-
-    	// rules can not programmed unless IP is associated with network service provider, so run IP assoication for
-    	// the network so as to ensure IP is associated before applying rules (in add state)
-    	applyIpAssociations(network, false, continueOnError, publicIps);
-	}
-    	
-    	try {
-    		applier.applyRules(network, purpose, rules);
-    	} catch (ResourceUnavailableException e) {
-    		if (!continueOnError) {
-    			throw e;
-    		}
-    		s_logger.warn("Problems with applying " + purpose + " rules but pushing on", e);
-    		success = false;
-    	}
-    	
-        if (! (rules.get(0).getPurpose() == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress) ) {
-            // if all the rules configured on public IP are revoked then dis-associate IP with network service provider
+                    PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
+                    publicIps.add(publicIp);
+                }
+            }
+
+            // rules can not programmed unless IP is associated with network
+            // service provider, so run IP assoication for
+            // the network so as to ensure IP is associated before applying
+            // rules (in add state)
+            applyIpAssociations(network, false, continueOnError, publicIps);
+        }
+
+        try {
+            applier.applyRules(network, purpose, rules);
+        } catch (ResourceUnavailableException e) {
+            if (!continueOnError) {
+                throw e;
+            }
+            s_logger.warn("Problems with applying " + purpose + " rules but pushing on", e);
+            success = false;
+        }
+
+        if (!(rules.get(0).getPurpose() == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress)) {
+            // if all the rules configured on public IP are revoked then
+            // dis-associate IP with network service provider
             applyIpAssociations(network, true, continueOnError, publicIps);
         }
 
-    	return success;
+        return success;
     }
-        
-    
-
-   
 
     public class NetworkGarbageCollector implements Runnable {
 
@@ -3099,13 +3099,14 @@ public class NetworkManagerImpl extends ManagerBase implements NetworkManager, L
             lb.setState(FirewallRule.State.Revoke);
             List<LbDestination> dstList = _lbMgr.getExistingDestinations(lb.getId());
             List<LbStickinessPolicy> policyList = _lbMgr.getStickinessPolicies(lb.getId());
+            List<LbHealthCheckPolicy> hcPolicyList =  _lbMgr.getHealthCheckPolicies (lb.getId());
             // mark all destination with revoke state
             for (LbDestination dst : dstList) {
                 s_logger.trace("Marking lb destination " + dst + " with Revoke state");
                 dst.setRevoked(true);
             }
 
-            LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList);
+            LoadBalancingRule loadBalancing = new LoadBalancingRule(lb, dstList, policyList, hcPolicyList);
             lbRules.add(loadBalancing);
         }
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/dao/LBHealthCheckPolicyDao.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/dao/LBHealthCheckPolicyDao.java b/server/src/com/cloud/network/dao/LBHealthCheckPolicyDao.java
new file mode 100644
index 0000000..42a9e42
--- /dev/null
+++ b/server/src/com/cloud/network/dao/LBHealthCheckPolicyDao.java
@@ -0,0 +1,35 @@
+// 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.
+package com.cloud.network.dao;
+
+import java.util.List;
+
+import com.cloud.network.LBHealthCheckPolicyVO;
+import com.cloud.utils.db.GenericDao;
+
+
+public interface LBHealthCheckPolicyDao extends
+        GenericDao<LBHealthCheckPolicyVO, Long> {
+    void remove(long loadBalancerId);
+
+    void remove(long loadBalancerId, Boolean pending);
+
+    List<LBHealthCheckPolicyVO> listByLoadBalancerId(long loadBalancerId);
+
+    List<LBHealthCheckPolicyVO> listByLoadBalancerId(long loadBalancerId,
+            boolean revoke);
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/dao/LBHealthCheckPolicyDaoImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/dao/LBHealthCheckPolicyDaoImpl.java b/server/src/com/cloud/network/dao/LBHealthCheckPolicyDaoImpl.java
new file mode 100644
index 0000000..65e0689
--- /dev/null
+++ b/server/src/com/cloud/network/dao/LBHealthCheckPolicyDaoImpl.java
@@ -0,0 +1,71 @@
+// 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.
+package com.cloud.network.dao;
+
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.springframework.stereotype.Component;
+
+import com.cloud.network.LBHealthCheckPolicyVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchCriteria;
+
+
+@Component
+@Local(value = { LBHealthCheckPolicyDao.class })
+public class LBHealthCheckPolicyDaoImpl extends
+        GenericDaoBase<LBHealthCheckPolicyVO, Long> implements
+        LBHealthCheckPolicyDao {
+
+    @Override
+    public void remove(long loadBalancerId) {
+        SearchCriteria<LBHealthCheckPolicyVO> sc = createSearchCriteria();
+        sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId);
+
+        expunge(sc);
+    }
+
+    @Override
+    public void remove(long loadBalancerId, Boolean revoke) {
+        SearchCriteria<LBHealthCheckPolicyVO> sc = createSearchCriteria();
+        sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId);
+        sc.addAnd("revoke", SearchCriteria.Op.EQ, revoke);
+
+        expunge(sc);
+    }
+
+    @Override
+    public List<LBHealthCheckPolicyVO> listByLoadBalancerId(long loadBalancerId) {
+        SearchCriteria<LBHealthCheckPolicyVO> sc = createSearchCriteria();
+        sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId);
+
+        return listBy(sc);
+    }
+
+    @Override
+    public List<LBHealthCheckPolicyVO> listByLoadBalancerId(long loadBalancerId,
+            boolean pending) {
+        SearchCriteria<LBHealthCheckPolicyVO> sc = createSearchCriteria();
+        sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId);
+        sc.addAnd("revoke", SearchCriteria.Op.EQ, pending);
+
+        return listBy(sc);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/dao/LoadBalancerVMMapVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/dao/LoadBalancerVMMapVO.java b/server/src/com/cloud/network/dao/LoadBalancerVMMapVO.java
index 8856993..852302e 100644
--- a/server/src/com/cloud/network/dao/LoadBalancerVMMapVO.java
+++ b/server/src/com/cloud/network/dao/LoadBalancerVMMapVO.java
@@ -39,10 +39,14 @@ public class LoadBalancerVMMapVO implements InternalIdentity {
     @Column(name="instance_id")
     private long instanceId;
 
-    @Column(name="revoke")
+    @Column(name = "revoke")
     private boolean revoke = false;
 
-    public LoadBalancerVMMapVO() { }
+    @Column(name = "state")
+    private String state;
+
+    public LoadBalancerVMMapVO() {
+    }
 
     public LoadBalancerVMMapVO(long loadBalancerId, long instanceId) {
         this.loadBalancerId = loadBalancerId;
@@ -74,4 +78,12 @@ public class LoadBalancerVMMapVO implements InternalIdentity {
     public void setRevoke(boolean revoke) {
         this.revoke = revoke;
     }
+
+    public String getState() {
+        return state;
+    }
+
+    public void setState(String state) {
+        this.state = state;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/element/VirtualRouterElement.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java
index 500d0b6..169db32 100755
--- a/server/src/com/cloud/network/element/VirtualRouterElement.java
+++ b/server/src/com/cloud/network/element/VirtualRouterElement.java
@@ -31,6 +31,7 @@ import org.apache.cloudstack.api.command.admin.router.CreateVirtualRouterElement
 import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd;
 import org.apache.log4j.Logger;
 
+import com.cloud.agent.api.to.LoadBalancerTO;
 import com.cloud.configuration.ConfigurationManager;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.dc.DataCenter;
@@ -363,7 +364,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
                 return true;
             }
         } else {
-            return true;
+            return false;
         }
     }
 
@@ -938,4 +939,11 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
     protected VirtualRouterProviderType getVirtualRouterProvider() {
         return VirtualRouterProviderType.VirtualRouter;
     }
+
+	@Override
+	public List<LoadBalancerTO> updateHealthChecks(Network network,
+			List<LoadBalancingRule> lbrules) {
+		// TODO Auto-generated method stub
+		return null;
+	}
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/lb/LBHealthCheckManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/lb/LBHealthCheckManager.java b/server/src/com/cloud/network/lb/LBHealthCheckManager.java
new file mode 100644
index 0000000..2e24965
--- /dev/null
+++ b/server/src/com/cloud/network/lb/LBHealthCheckManager.java
@@ -0,0 +1,24 @@
+// 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.
+package com.cloud.network.lb;
+
+
+public interface LBHealthCheckManager {
+
+    void updateLBHealthCheck();
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/lb/LBHealthCheckManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/lb/LBHealthCheckManagerImpl.java b/server/src/com/cloud/network/lb/LBHealthCheckManagerImpl.java
new file mode 100644
index 0000000..9054732
--- /dev/null
+++ b/server/src/com/cloud/network/lb/LBHealthCheckManagerImpl.java
@@ -0,0 +1,110 @@
+// 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.
+package com.cloud.network.lb;
+
+import static java.lang.String.format;
+
+import java.util.Map;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import javax.ejb.Local;
+import javax.inject.Inject;
+import javax.naming.ConfigurationException;
+
+import org.apache.log4j.Logger;
+import org.springframework.stereotype.Component;
+
+import com.cloud.configuration.Config;
+import com.cloud.configuration.dao.ConfigurationDao;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.utils.NumbersUtil;
+import com.cloud.utils.component.Manager;
+import com.cloud.utils.component.ManagerBase;
+import com.cloud.utils.concurrency.NamedThreadFactory;
+
+@Component
+@Local(value = {LBHealthCheckManager.class})
+public class LBHealthCheckManagerImpl extends ManagerBase implements LBHealthCheckManager, Manager {
+    private static final Logger s_logger = Logger.getLogger(LBHealthCheckManagerImpl.class);
+
+    @Inject
+    ConfigurationDao _configDao;
+    @Inject
+    LoadBalancingRulesService _lbService;
+
+    private String name;
+    private Map<String, String> _configs;
+    ScheduledExecutorService _executor;
+
+    private long _interval;
+
+    @Override
+    public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
+        _configs = _configDao.getConfiguration("management-server", params);
+        if (s_logger.isInfoEnabled()) {
+            s_logger.info(format("Configuring LBHealthCheck Manager %1$s", name));
+        }
+        this.name = name;
+        _interval = NumbersUtil.parseLong(_configs.get(Config.LBHealthCheck.key()), 600);
+        _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("LBHealthCheck"));
+        return true;
+    }
+
+    @Override
+    public boolean start() {
+        s_logger.debug("LB HealthCheckmanager is getting Started");
+        _executor.scheduleAtFixedRate(new UpdateLBHealthCheck(), 10, _interval, TimeUnit.SECONDS);
+        return true;
+    }
+
+    @Override
+    public boolean stop() {
+        s_logger.debug("HealthCheckmanager is getting Stopped");
+        _executor.shutdown();
+        return true;
+    }
+
+    @Override
+    public String getName() {
+        return this.name;
+    }
+
+    protected class UpdateLBHealthCheck implements Runnable {
+        @Override
+        public void run() {
+            try {
+                updateLBHealthCheck();
+            } catch (Exception e) {
+                s_logger.error("Exception in LB HealthCheck Update Checker", e);
+            }
+        }
+    }
+
+    @Override
+    public void updateLBHealthCheck() {
+        try {
+            _lbService.updateLBHealthChecks();
+        } catch (ResourceUnavailableException e) {
+            s_logger.debug("Error while updating the LB HealtCheck ", e);
+        }
+        s_logger.debug("LB HealthCheck Manager is running and getting the updates from LB providers and updating service status");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/183b989d/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java
index 9d7d22f..da19f86 100644
--- a/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java
+++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java
@@ -20,6 +20,7 @@ import com.cloud.exception.NetworkRuleConflictException;
 import com.cloud.exception.ResourceUnavailableException;
 import com.cloud.network.Network;
 import com.cloud.network.lb.LoadBalancingRule.LbDestination;
+import com.cloud.network.lb.LoadBalancingRule.LbHealthCheckPolicy;
 import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
 import com.cloud.network.rules.FirewallRule;
 import com.cloud.network.rules.LbStickinessMethod;
@@ -38,6 +39,7 @@ public interface LoadBalancingRulesManager extends LoadBalancingRulesService {
     List<LbDestination> getExistingDestinations(long lbId);
     List<LbStickinessPolicy> getStickinessPolicies(long lbId);
     List<LbStickinessMethod> getStickinessMethods(long networkid);
+    List<LbHealthCheckPolicy> getHealthCheckPolicies(long lbId);
 
     /**
      * Remove vm from all load balancers


Mime
View raw message