You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by al...@apache.org on 2013/04/11 02:15:48 UTC

[37/50] [abbrv] git commit: updated refs/heads/internallb to 20beb7a

InternalLB:

1) Added new set of Interfaces - including the new VO - for the internal load balancer
2) DB change - added source_ip_address/source_ip_address_network_id/scheme (Internal/Public) fields to the load_balancer table


Project: http://git-wip-us.apache.org/repos/asf/cloudstack/repo
Commit: http://git-wip-us.apache.org/repos/asf/cloudstack/commit/08f855d4
Tree: http://git-wip-us.apache.org/repos/asf/cloudstack/tree/08f855d4
Diff: http://git-wip-us.apache.org/repos/asf/cloudstack/diff/08f855d4

Branch: refs/heads/internallb
Commit: 08f855d4e4b3888b3b4a163ce73c0e444b91e6b7
Parents: f66b9b5
Author: Alena Prokharchyk <al...@citrix.com>
Authored: Thu Apr 4 09:26:21 2013 -0700
Committer: Alena Prokharchyk <al...@citrix.com>
Committed: Wed Apr 10 16:27:33 2013 -0700

----------------------------------------------------------------------
 api/src/com/cloud/async/AsyncJob.java              |    3 +-
 api/src/com/cloud/network/IpAddress.java           |    2 +
 api/src/com/cloud/network/NetworkModel.java        |    3 +
 .../com/cloud/network/lb/LoadBalancingRule.java    |   66 +--
 .../network/lb/LoadBalancingRulesService.java      |   15 +-
 .../rules/ApplicationLoadBalancerContainer.java    |   27 +
 .../network/rules/ApplicationLoadBalancerRule.java |   22 +
 api/src/com/cloud/network/rules/LoadBalancer.java  |   10 +-
 .../cloud/network/rules/LoadBalancerContainer.java |   33 +
 .../org/apache/cloudstack/api/ApiConstants.java    |    5 +
 api/src/org/apache/cloudstack/api/BaseCmd.java     |    5 +
 .../apache/cloudstack/api/ResponseGenerator.java   |    5 +
 .../CreateApplicationLoadBalancerCmd.java          |  240 ++++++
 .../loadbalancer/CreateLoadBalancerRuleCmd.java    |    6 +-
 .../DeleteApplicationLoadBalancerCmd.java          |  116 +++
 .../ListApplicationLoadBalancersCmd.java           |   89 +++
 .../ApplicationLoadBalancerInstanceResponse.java   |   63 ++
 .../response/ApplicationLoadBalancerResponse.java  |  142 ++++
 .../ApplicationLoadBalancerRuleResponse.java       |   51 ++
 .../network/lb/ApplicationLoadBalancerService.java |   38 +
 client/tomcatconf/applicationContext.xml.in        |    2 +
 client/tomcatconf/commands.properties.in           |    6 +
 .../network/lb/ElasticLoadBalancerManager.java     |    2 +-
 .../network/lb/ElasticLoadBalancerManagerImpl.java |   13 +-
 server/src/com/cloud/api/ApiResponseHelper.java    |   73 ++-
 server/src/com/cloud/network/NetworkModelImpl.java |    5 +
 .../network/dao/ApplicationLoadBalancerRuleVO.java |   78 ++
 server/src/com/cloud/network/dao/IPAddressVO.java  |    9 +-
 .../src/com/cloud/network/dao/LoadBalancerVO.java  |   30 +
 .../network/element/VirtualRouterElement.java      |    4 +-
 .../network/firewall/FirewallManagerImpl.java      |   77 +-
 .../network/lb/LoadBalancingRulesManager.java      |   13 +-
 .../network/lb/LoadBalancingRulesManagerImpl.java  |  256 +++++--
 .../router/VirtualNetworkApplianceManager.java     |    3 +
 .../router/VirtualNetworkApplianceManagerImpl.java |   25 +
 .../src/com/cloud/server/ManagementServerImpl.java |  607 ++++++++++-----
 .../lb/ApplicationLoadBalancerManagerImpl.java     |   61 ++
 .../com/cloud/network/MockNetworkModelImpl.java    |    6 +
 .../test/com/cloud/vpc/MockNetworkModelImpl.java   |    6 +
 .../vpc/MockVpcVirtualNetworkApplianceManager.java |    7 +
 setup/db/db/schema-410to420.sql                    |    7 +
 41 files changed, 1833 insertions(+), 398 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/async/AsyncJob.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/async/AsyncJob.java b/api/src/com/cloud/async/AsyncJob.java
index 8e4aec0..1528809 100644
--- a/api/src/com/cloud/async/AsyncJob.java
+++ b/api/src/com/cloud/async/AsyncJob.java
@@ -49,7 +49,8 @@ public interface AsyncJob extends Identity, InternalIdentity {
         AutoScalePolicy,
         AutoScaleVmProfile,
         AutoScaleVmGroup,
-        GlobalLoadBalancerRule
+        GlobalLoadBalancerRule,
+        LoadBalancerRule
     }
 
     long getUserId();

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/IpAddress.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/IpAddress.java b/api/src/com/cloud/network/IpAddress.java
index fce8f38..a1fcb79 100644
--- a/api/src/com/cloud/network/IpAddress.java
+++ b/api/src/com/cloud/network/IpAddress.java
@@ -89,5 +89,7 @@ public interface IpAddress extends ControlledEntity, Identity, InternalIdentity
     void setVpcId(Long vpcId);
     String getVmIp();
     void setVmIp(String vmIp);
+    
+    Long getNetworkId();
 
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/NetworkModel.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/NetworkModel.java b/api/src/com/cloud/network/NetworkModel.java
index 4d7d714..bd83b17 100644
--- a/api/src/com/cloud/network/NetworkModel.java
+++ b/api/src/com/cloud/network/NetworkModel.java
@@ -263,4 +263,7 @@ public interface NetworkModel {
     boolean isProviderEnabledInZone(long zoneId, String provider);
 
     Nic getPlaceholderNicForRouter(Network network, Long podId);
+    
+    IpAddress getPublicIpAddress(String ipAddress, long networkId);
+
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/lb/LoadBalancingRule.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/lb/LoadBalancingRule.java b/api/src/com/cloud/network/lb/LoadBalancingRule.java
index 3e11e8c..33cc5fd 100644
--- a/api/src/com/cloud/network/lb/LoadBalancingRule.java
+++ b/api/src/com/cloud/network/lb/LoadBalancingRule.java
@@ -27,7 +27,7 @@ import com.cloud.network.rules.FirewallRule;
 import com.cloud.network.rules.LoadBalancer;
 import com.cloud.utils.Pair;
 
-public class LoadBalancingRule implements FirewallRule, LoadBalancer {
+public class LoadBalancingRule {
     private LoadBalancer lb;
     private List<LbDestination> destinations;
     private List<LbStickinessPolicy> stickinessPolicies;
@@ -42,94 +42,66 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer {
         this.healthCheckPolicies = healthCheckPolicies;
     }
 
-    @Override
     public long getId() {
         return lb.getId();
     }
 
-    @Override
-    public long getAccountId() {
-        return lb.getAccountId();
-    }
-
-    @Override
-    public long getDomainId() {
-        return lb.getDomainId();
-    }
-
-    @Override
     public String getName() {
         return lb.getName();
     }
 
-    @Override
     public String getDescription() {
         return lb.getDescription();
     }
 
-    @Override
     public int getDefaultPortStart() {
         return lb.getDefaultPortStart();
     }
 
-    @Override
     public int getDefaultPortEnd() {
         return lb.getDefaultPortEnd();
     }
 
-    @Override
     public String getAlgorithm() {
         return lb.getAlgorithm();
     }
 
-    @Override
     public String getUuid() {
         return lb.getUuid();
     }
 
-    @Override
     public String getXid() {
         return lb.getXid();
     }
 
-    @Override
     public Long getSourceIpAddressId() {
         return lb.getSourceIpAddressId();
     }
 
-    @Override
     public Integer getSourcePortStart() {
         return lb.getSourcePortStart();
     }
 
-    @Override
     public Integer getSourcePortEnd() {
         return lb.getSourcePortEnd();
     }
 
-    @Override
     public String getProtocol() {
         return lb.getProtocol();
     }
 
-    @Override
-    public Purpose getPurpose() {
-        return Purpose.LoadBalancing;
+    public FirewallRule.Purpose getPurpose() {
+        return FirewallRule.Purpose.LoadBalancing;
     }
 
-    @Override
-    public State getState() {
+    public FirewallRule.State getState() {
         return lb.getState();
     }
 
-    @Override
     public long getNetworkId() {
         return lb.getNetworkId();
     }
 
-    public LoadBalancer getLb() {
-        return lb;
-    }
 
     public void setDestinations(List<LbDestination> destinations) {
         this.destinations = destinations;
@@ -287,36 +259,6 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer {
         }
     }
 
-    @Override
-    public Integer getIcmpCode() {
-        return null;
-    }
-
-    @Override
-    public Integer getIcmpType() {
-        return null;
-    }
-
-    @Override
-    public List<String> getSourceCidrList() {
-        return null;
-    }
-
-    @Override
-    public Long getRelated() {
-        return null;
-    }
-
-    @Override
-    public TrafficType getTrafficType() {
-        return null;
-    }
-
-    @Override
-    public FirewallRuleType getType() {
-        return FirewallRuleType.User;
-    }
-
     public LbAutoScaleVmGroup getAutoScaleVmGroup() {
         return autoScaleVmGroup;
     }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/lb/LoadBalancingRulesService.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java
index ed39bed..7dc513c 100644
--- a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java
+++ b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java
@@ -17,10 +17,10 @@
 package com.cloud.network.lb;
 
 import java.util.List;
+import java.util.Map;
 
 import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBHealthCheckPolicyCmd;
 import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd;
-import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd;
 import org.apache.cloudstack.api.command.user.loadbalancer.ListLBHealthCheckPoliciesCmd;
 import org.apache.cloudstack.api.command.user.loadbalancer.ListLBStickinessPoliciesCmd;
 import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRuleInstancesCmd;
@@ -30,12 +30,12 @@ import org.apache.cloudstack.api.command.user.loadbalancer.UpdateLoadBalancerRul
 import com.cloud.exception.InsufficientAddressCapacityException;
 import com.cloud.exception.NetworkRuleConflictException;
 import com.cloud.exception.ResourceUnavailableException;
-import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy;
 import com.cloud.network.rules.HealthCheckPolicy;
 import com.cloud.network.rules.LoadBalancer;
 import com.cloud.network.rules.StickinessPolicy;
 import com.cloud.uservm.UserVm;
 import com.cloud.utils.Pair;
+import com.cloud.utils.net.Ip;
 
 
 public interface LoadBalancingRulesService {
@@ -49,7 +49,9 @@ public interface LoadBalancingRulesService {
      * @return the newly created LoadBalancerVO if successful, null otherwise
      * @throws InsufficientAddressCapacityException
      */
-    LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException;
+    LoadBalancer createPublicLoadBalancerRule(String xId, String name, String description, 
+            int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd, Long ipAddrId, String protocol, String algorithm,
+            long networkId, long lbOwnerId, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException;
 
     LoadBalancer updateLoadBalancerRule(UpdateLoadBalancerRuleCmd cmd);
 
@@ -134,8 +136,9 @@ public interface LoadBalancingRulesService {
 
     List<? extends HealthCheckPolicy> searchForLBHealthCheckPolicies(ListLBHealthCheckPoliciesCmd cmd);
 
-    List<LoadBalancingRule> listByNetworkId(long networkId);
-
     LoadBalancer findById(long LoadBalancer);
-   public void updateLBHealthChecks() throws ResourceUnavailableException;
+    
+    public void updateLBHealthChecks() throws ResourceUnavailableException;
+
+    Map<Ip, UserVm> getLbInstances(long lbId);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/rules/ApplicationLoadBalancerContainer.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/rules/ApplicationLoadBalancerContainer.java b/api/src/com/cloud/network/rules/ApplicationLoadBalancerContainer.java
new file mode 100644
index 0000000..90f1e61
--- /dev/null
+++ b/api/src/com/cloud/network/rules/ApplicationLoadBalancerContainer.java
@@ -0,0 +1,27 @@
+// 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.rules;
+
+import com.cloud.utils.net.Ip;
+
+public interface ApplicationLoadBalancerContainer extends LoadBalancerContainer{
+    
+    public String getSourceIpNetworkUuid();
+    
+    public Ip getSourceIpAddress();
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/rules/ApplicationLoadBalancerRule.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/rules/ApplicationLoadBalancerRule.java b/api/src/com/cloud/network/rules/ApplicationLoadBalancerRule.java
new file mode 100644
index 0000000..76c07d5
--- /dev/null
+++ b/api/src/com/cloud/network/rules/ApplicationLoadBalancerRule.java
@@ -0,0 +1,22 @@
+// 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.rules;
+
+public interface ApplicationLoadBalancerRule extends ApplicationLoadBalancerContainer, LoadBalancer{
+    int getInstancePort();
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/rules/LoadBalancer.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/rules/LoadBalancer.java b/api/src/com/cloud/network/rules/LoadBalancer.java
index ab6085a..e6dadca 100644
--- a/api/src/com/cloud/network/rules/LoadBalancer.java
+++ b/api/src/com/cloud/network/rules/LoadBalancer.java
@@ -19,16 +19,10 @@ package com.cloud.network.rules;
 /**
  * Definition for a LoadBalancer
  */
-public interface LoadBalancer extends FirewallRule {
-
-    String getName();
-
-    String getDescription();
-
+public interface LoadBalancer extends FirewallRule, LoadBalancerContainer {
+    
     int getDefaultPortStart();
 
     int getDefaultPortEnd();
 
-    String getAlgorithm();
-
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/com/cloud/network/rules/LoadBalancerContainer.java
----------------------------------------------------------------------
diff --git a/api/src/com/cloud/network/rules/LoadBalancerContainer.java b/api/src/com/cloud/network/rules/LoadBalancerContainer.java
new file mode 100644
index 0000000..9d5ea59
--- /dev/null
+++ b/api/src/com/cloud/network/rules/LoadBalancerContainer.java
@@ -0,0 +1,33 @@
+// 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.rules;
+
+public interface LoadBalancerContainer {
+    
+    public enum Scheme {
+        Public, Internal;
+    }
+
+    String getName();
+
+    String getDescription();
+    
+    String getAlgorithm();
+    
+    Scheme getScheme();
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/ApiConstants.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java
index c518830..e3297d5 100755
--- a/api/src/org/apache/cloudstack/api/ApiConstants.java
+++ b/api/src/org/apache/cloudstack/api/ApiConstants.java
@@ -473,6 +473,11 @@ public class ApiConstants {
     public static final String HEALTHCHECK_HEALTHY_THRESHOLD = "healthythreshold";
     public static final String HEALTHCHECK_UNHEALTHY_THRESHOLD = "unhealthythreshold";
     public static final String HEALTHCHECK_PINGPATH = "pingpath";
+    public static final String SOURCE_PORT = "sourceport";
+    public static final String INSTANCE_PORT = "instanceport";
+    public static final String SOURCE_IP = "sourceipaddress";
+    public static final String SOURCE_IP_NETWORK_ID = "sourceipaddressnetworkid";
+    public static final String SCHEME = "scheme";
 
     public enum HostDetails {
         all, capacity, events, stats, min;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/BaseCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java
index 8fef422..41f085e 100644
--- a/api/src/org/apache/cloudstack/api/BaseCmd.java
+++ b/api/src/org/apache/cloudstack/api/BaseCmd.java
@@ -27,6 +27,7 @@ import java.util.regex.Pattern;
 
 import javax.inject.Inject;
 
+import org.apache.cloudstack.network.lb.ApplicationLoadBalancerService;
 import org.apache.cloudstack.query.QueryService;
 import org.apache.cloudstack.usage.UsageService;
 import org.apache.log4j.Logger;
@@ -41,6 +42,7 @@ import com.cloud.exception.NetworkRuleConflictException;
 import com.cloud.exception.PermissionDeniedException;
 import com.cloud.exception.ResourceAllocationException;
 import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.NetworkModel;
 import com.cloud.network.NetworkService;
 import com.cloud.network.NetworkUsageService;
 import com.cloud.network.StorageNetworkService;
@@ -132,6 +134,9 @@ public abstract class BaseCmd {
     @Inject public VMSnapshotService _vmSnapshotService;
     @Inject public DataStoreProviderApiService dataStoreProviderApiService;
     @Inject public VpcProvisioningService _vpcProvSvc;
+    @Inject public ApplicationLoadBalancerService _newLbSvc;
+    @Inject public NetworkModel _ntwkModel;
+    @Inject public ApplicationLoadBalancerService _appLbService;
 
     public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException;
 

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/ResponseGenerator.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java
index d1e1302..e280a15 100644
--- a/api/src/org/apache/cloudstack/api/ResponseGenerator.java
+++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java
@@ -19,6 +19,7 @@ package org.apache.cloudstack.api;
 import java.text.DecimalFormat;
 import java.util.EnumSet;
 import java.util.List;
+import java.util.Map;
 
 import org.apache.cloudstack.api.ApiConstants.HostDetails;
 import org.apache.cloudstack.api.ApiConstants.VMDetails;
@@ -50,6 +51,7 @@ import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
 import org.apache.cloudstack.api.response.LBHealthCheckResponse;
 import org.apache.cloudstack.api.response.LBStickinessResponse;
 import org.apache.cloudstack.api.response.LDAPConfigResponse;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse;
 import org.apache.cloudstack.api.response.LoadBalancerResponse;
 import org.apache.cloudstack.api.response.NetworkACLResponse;
 import org.apache.cloudstack.api.response.NetworkOfferingResponse;
@@ -148,6 +150,7 @@ import com.cloud.user.Account;
 import com.cloud.user.User;
 import com.cloud.user.UserAccount;
 import com.cloud.uservm.UserVm;
+import com.cloud.utils.net.Ip;
 import com.cloud.vm.InstanceGroup;
 import com.cloud.vm.Nic;
 import com.cloud.vm.NicSecondaryIp;
@@ -392,4 +395,6 @@ public interface ResponseGenerator {
     NicSecondaryIpResponse createSecondaryIPToNicResponse(String ip,
             Long nicId, Long networkId);
     public NicResponse createNicResponse(Nic result);
+
+    ApplicationLoadBalancerResponse createLoadBalancerContainerReponse(LoadBalancer lb, Map<Ip, UserVm> lbInstances);
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java
new file mode 100644
index 0000000..f9e8d64
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateApplicationLoadBalancerCmd.java
@@ -0,0 +1,240 @@
+// 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 org.apache.cloudstack.api.command.user.loadbalancer;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseAsyncCreateCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse;
+import org.apache.cloudstack.api.response.DomainResponse;
+import org.apache.cloudstack.api.response.NetworkResponse;
+import org.apache.log4j.Logger;
+
+import com.cloud.async.AsyncJob;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InsufficientAddressCapacityException;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.exception.NetworkRuleConflictException;
+import com.cloud.exception.ResourceAllocationException;
+import com.cloud.exception.ResourceUnavailableException;
+import com.cloud.network.Network;
+import com.cloud.network.Networks.TrafficType;
+import com.cloud.network.rules.LoadBalancer;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.user.Account;
+import com.cloud.user.UserContext;
+import com.cloud.utils.net.NetUtils;
+
+@APICommand(name = "createLoadBalancer", description="Creates a Load Balancer", responseObject=ApplicationLoadBalancerResponse.class)
+public class CreateApplicationLoadBalancerCmd extends BaseAsyncCreateCmd {
+    public static final Logger s_logger = Logger.getLogger(CreateApplicationLoadBalancerCmd.class.getName());
+
+    private static final String s_name = "createloadbalancerresponse";
+
+    /////////////////////////////////////////////////////
+    //////////////// API parameters /////////////////////
+    /////////////////////////////////////////////////////
+    @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="name of the Load Balancer")
+    private String loadBalancerName;
+    
+    @Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="the description of the Load Balancer", length=4096)
+    private String description;
+    
+    @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, required=true, entityType = NetworkResponse.class,
+            description="The guest network the Load Balancer will be created for")
+    private Long networkId;
+    
+    @Parameter(name=ApiConstants.SOURCE_PORT, type=CommandType.INTEGER, required=true, description="the source port the network traffic will be load balanced from")
+    private Integer sourcePort;
+
+    @Parameter(name=ApiConstants.ALGORITHM, type=CommandType.STRING, required=true, description="load balancer algorithm (source, roundrobin, leastconn)")
+    private String algorithm;
+
+    @Parameter(name=ApiConstants.INSTANCE_PORT, type=CommandType.INTEGER, required=true, description="the TCP port of the virtual machine where the network traffic will be load balanced to")
+    private Integer instancePort;
+
+    @Parameter(name=ApiConstants.SOURCE_IP, type=CommandType.STRING, description="the source ip address the network traffic will be load balanced from")
+    private String sourceIp;
+    
+    @Parameter(name=ApiConstants.SOURCE_IP_NETWORK_ID, type=CommandType.LONG, required=true, description="the network id of the source ip address")
+    private Long sourceIpNetworkId;
+
+    @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the load balancer." +
+    		" Must be used with the domainId parameter.")
+    private String accountName;
+
+    @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class,
+            description="the domain ID associated with the load balancer")
+    private Long domainId;
+    
+    @Parameter(name=ApiConstants.SCHEME, type=CommandType.STRING, required=true, description="the load balancer scheme. Supported value in this release is Internal")
+    private String scheme;
+
+
+
+    /////////////////////////////////////////////////////
+    /////////////////// Accessors ///////////////////////
+    /////////////////////////////////////////////////////
+
+    public String getAlgorithm() {
+        return algorithm;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public String getLoadBalancerName() {
+        return loadBalancerName;
+    }
+
+    public Integer getPrivatePort() {
+        return instancePort;
+    }
+
+
+    public long getNetworkId() {
+        return networkId;
+    }
+
+    public String getName() {
+        return loadBalancerName;
+    }
+    
+    public Integer getSourcePort() {
+        return sourcePort.intValue();
+    }
+
+    public String getProtocol() {
+        return NetUtils.TCP_PROTO;
+    }
+
+    public long getAccountId() {
+        Account account = null;
+        //get account info from the network object if it's a guest network
+        Network ntwk = _networkService.getNetwork(networkId);
+        if (ntwk.getTrafficType() == TrafficType.Guest){
+            return ntwk.getAccountId();
+        } else if (sourceIp != null) {
+            //get account info from the ip address object if the traffic type is public
+
+        } if ((domainId != null) && (accountName != null)) {
+            account = _responseGenerator.findAccountByNameDomain(accountName, domainId);
+            if (account != null) {
+                return account.getId();
+            } else {
+                throw new InvalidParameterValueException("Unable to find account " + account + " in domain id=" + domainId);
+            }
+        } else {
+            throw new InvalidParameterValueException("Can't define the Load Balancer owner. Either specify guest" +
+                    " network in networkId, or Public Ip address in sourceIpAddress, or account/domainId parameters");
+        }   
+    }
+
+    public int getInstancePort() {
+        return instancePort.intValue();
+    }
+
+    public String getAccountName() {
+        return accountName;
+    }
+
+    @Override
+    public String getEventType() {
+        return EventTypes.EVENT_LOAD_BALANCER_CREATE;
+    }
+
+    @Override
+    public String getEventDescription() {
+        return "creating load balancer: " + getName() + " account: " + getAccountName();
+
+    }
+
+    @Override
+    public AsyncJob.Type getInstanceType() {
+        return AsyncJob.Type.LoadBalancerRule;
+    }
+    
+    public String getSourceIp() {
+        return sourceIp;
+    }
+
+    public long getSourceIpNetworkId() {
+        return sourceIpNetworkId;
+    }
+
+    public Scheme getScheme() {
+        if (scheme.equalsIgnoreCase(Scheme.Internal.toString())) {
+            return Scheme.Internal;
+        } else {
+            throw new InvalidParameterValueException("Invalid value for sheme. Supported value is Internal");
+        }
+    }
+    
+    @Override
+    public long getEntityOwnerId() {
+       return getAccountId();
+    }
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public void execute() throws ResourceAllocationException, ResourceUnavailableException {
+        LoadBalancer rule = null;
+        try {
+            UserContext.current().setEventDetails("Load Balancer Id: " + getEntityId());
+            // State might be different after the rule is applied, so get new object here
+            rule = _entityMgr.findById(LoadBalancer.class, getEntityId());
+            ApplicationLoadBalancerResponse lbResponse = _responseGenerator.createLoadBalancerContainerReponse(rule, _lbService.getLbInstances(getEntityId()));
+            setResponseObject(lbResponse);
+            lbResponse.setResponseName(getCommandName());
+        } catch (Exception ex) {
+            s_logger.warn("Failed to create Load Balancer due to exception ", ex);
+        } finally {
+            if (rule == null) {
+                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Load Balancer");
+            }
+        }
+    }
+
+    @Override
+    public void create() {
+        try {
+            
+            LoadBalancer result = _appLbService.createApplicationLoadBalancer(getName(), getDescription(), getScheme(), getSourceIpNetworkId(), getSourceIp(), getSourcePort(),
+                    getInstancePort(), getAlgorithm(), getNetworkId(), getEntityOwnerId());
+            this.setEntityId(result.getId());
+            this.setEntityUuid(result.getUuid());
+        }catch (NetworkRuleConflictException e) {
+            s_logger.warn("Exception: ", e);
+            throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());
+        } catch (InsufficientAddressCapacityException e) {
+            s_logger.warn("Exception: ", e);
+            throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, e.getMessage());
+        }
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java
index 5f1d97b..f6cc1f1 100644
--- a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java
+++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java
@@ -148,7 +148,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd  /*implements
     }
 
 
-    public Long getNetworkId() {
+    public long getNetworkId() {
         if (networkId != null) {
             return networkId;
         }
@@ -278,7 +278,9 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd  /*implements
             throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command");
         }
         try {
-            LoadBalancer result = _lbService.createLoadBalancerRule(this, getOpenFirewall());
+            LoadBalancer result = _lbService.createPublicLoadBalancerRule(getXid(), getName(), getDescription(), 
+                    getSourcePortStart(), getSourcePortEnd(), getDefaultPortStart(), getDefaultPortEnd(), getSourceIpAddressId(), getProtocol(), getAlgorithm(),
+                    getNetworkId(), getEntityOwnerId(), getOpenFirewall());
             this.setEntityId(result.getId());
             this.setEntityUuid(result.getUuid());
         } catch (NetworkRuleConflictException e) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java
new file mode 100644
index 0000000..78b06ad
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteApplicationLoadBalancerCmd.java
@@ -0,0 +1,116 @@
+// 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 org.apache.cloudstack.api.command.user.loadbalancer;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.ApiErrorCode;
+import org.apache.cloudstack.api.BaseAsyncCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.ServerApiException;
+import org.apache.cloudstack.api.response.FirewallRuleResponse;
+import org.apache.cloudstack.api.response.SuccessResponse;
+import org.apache.log4j.Logger;
+
+import com.cloud.async.AsyncJob;
+import com.cloud.event.EventTypes;
+import com.cloud.exception.InvalidParameterValueException;
+import com.cloud.network.rules.LoadBalancer;
+import com.cloud.user.UserContext;
+
+@APICommand(name = "deleteLoadBalancer", description="Deletes a load balancer", responseObject=SuccessResponse.class)
+public class DeleteApplicationLoadBalancerCmd extends BaseAsyncCmd {
+    public static final Logger s_logger = Logger.getLogger(DeleteApplicationLoadBalancerCmd.class.getName());
+    private static final String s_name = "deleteloadbalancerresponse";
+    /////////////////////////////////////////////////////
+    //////////////// API parameters /////////////////////
+    /////////////////////////////////////////////////////
+
+    @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class,
+            required=true, description="the ID of the Load Balancer")
+    private Long id;
+
+
+    /////////////////////////////////////////////////////
+    /////////////////// Accessors ///////////////////////
+    /////////////////////////////////////////////////////
+
+    public Long getId() {
+        return id;
+    }
+
+    /////////////////////////////////////////////////////
+    /////////////// API Implementation///////////////////
+    /////////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public long getEntityOwnerId() {
+        LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getId());
+        if (lb != null) {
+            return lb.getAccountId();
+        } else {
+            throw new InvalidParameterValueException("Can't find load balancer by id specified");
+        }
+    }
+
+    @Override
+    public String getEventType() {
+        return EventTypes.EVENT_LOAD_BALANCER_DELETE;
+    }
+
+    @Override
+    public String getEventDescription() {
+        return  "deleting load balancer: " + getId();
+    }
+
+    @Override
+    public void execute(){
+        UserContext.current().setEventDetails("Load balancer Id: " + getId());
+        boolean result = _appLbService.deleteApplicationLoadBalancer(getId());
+
+        if (result) {
+            SuccessResponse response = new SuccessResponse(getCommandName());
+            this.setResponseObject(response);
+        } else {
+            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete load balancer");
+        }
+    }
+
+    @Override
+    public String getSyncObjType() {
+        return BaseAsyncCmd.networkSyncObject;
+    }
+
+    @Override
+    public Long getSyncObjId() {
+        LoadBalancer lb = _lbService.findById(id);
+        if(lb == null){
+            throw new InvalidParameterValueException("Unable to find load balancer by id ");
+        }
+        return lb.getNetworkId();
+    }
+
+    @Override
+    public AsyncJob.Type getInstanceType() {
+        return AsyncJob.Type.FirewallRule;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java
new file mode 100644
index 0000000..844e294
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListApplicationLoadBalancersCmd.java
@@ -0,0 +1,89 @@
+// 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 org.apache.cloudstack.api.command.user.loadbalancer;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.cloudstack.api.APICommand;
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseListTaggedResourcesCmd;
+import org.apache.cloudstack.api.Parameter;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse;
+import org.apache.cloudstack.api.response.FirewallRuleResponse;
+import org.apache.cloudstack.api.response.ListResponse;
+import org.apache.log4j.Logger;
+
+import com.cloud.network.rules.ApplicationLoadBalancerRule;
+import com.cloud.utils.Pair;
+
+@APICommand(name = "listLoadBalancers", description = "Lists Load Balancers", responseObject = ApplicationLoadBalancerResponse.class)
+public class ListApplicationLoadBalancersCmd extends BaseListTaggedResourcesCmd {
+    public static final Logger s_logger = Logger.getLogger(ListLoadBalancerRulesCmd.class.getName());
+
+    private static final String s_name = "listloadbalancerssresponse";
+
+    // ///////////////////////////////////////////////////
+    // ////////////// API parameters /////////////////////
+    // ///////////////////////////////////////////////////
+
+    @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class,
+            description = "the ID of the Load Balancer")
+    private Long id;
+
+    @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the name of the Load Balancer")
+    private String loadBalancerName;
+
+
+    // ///////////////////////////////////////////////////
+    // ///////////////// Accessors ///////////////////////
+    // ///////////////////////////////////////////////////
+
+    public Long getId() {
+        return id;
+    }
+
+    public String getLoadBalancerRuleName() {
+        return loadBalancerName;
+    }
+
+
+    // ///////////////////////////////////////////////////
+    // ///////////// API Implementation///////////////////
+    // ///////////////////////////////////////////////////
+
+    @Override
+    public String getCommandName() {
+        return s_name;
+    }
+
+    @Override
+    public void execute() {
+        Pair<List<? extends ApplicationLoadBalancerRule>, Integer> loadBalancers = _appLbService.listApplicationLoadBalancers();
+        ListResponse<ApplicationLoadBalancerResponse> response = new ListResponse<ApplicationLoadBalancerResponse>();
+        List<ApplicationLoadBalancerResponse> lbResponses = new ArrayList<ApplicationLoadBalancerResponse>();
+        for (ApplicationLoadBalancerRule loadBalancer : loadBalancers.first()) {
+            ApplicationLoadBalancerResponse lbResponse = _responseGenerator.createLoadBalancerContainerReponse(loadBalancer, _lbService.getLbInstances(loadBalancer.getId()));
+            lbResponse.setObjectName("loadbalancer");
+            lbResponses.add(lbResponse);
+        }
+        response.setResponses(lbResponses, loadBalancers.second());
+        response.setResponseName(getCommandName());
+        this.setResponseObject(response);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerInstanceResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerInstanceResponse.java b/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerInstanceResponse.java
new file mode 100644
index 0000000..2d6614d
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerInstanceResponse.java
@@ -0,0 +1,63 @@
+// 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 org.apache.cloudstack.api.response;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseResponse;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * 
+ * Load Balancer instance is the User Vm instance participating in the Load Balancer
+ *
+ */
+
+@SuppressWarnings("unused")
+public class ApplicationLoadBalancerInstanceResponse extends BaseResponse{
+    
+    @SerializedName(ApiConstants.ID) @Param(description = "the instance ID")
+    private String id;
+    
+    @SerializedName(ApiConstants.NAME) @Param(description = "the name of the instance")
+    private String name;
+    
+    @SerializedName(ApiConstants.STATE) @Param(description="the state of the instance")
+    private String state;
+    
+    @SerializedName(ApiConstants.IP_ADDRESS)
+    @Param(description="the ip address of the instance")
+    private String ipAddress;
+    
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public void setState(String state) {
+        this.state = state;
+    }
+
+    public void setIpAddress(String ipAddress) {
+        this.ipAddress = ipAddress;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerResponse.java b/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerResponse.java
new file mode 100644
index 0000000..de9bce6
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerResponse.java
@@ -0,0 +1,142 @@
+// 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 org.apache.cloudstack.api.response;
+
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseResponse;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+
+@SuppressWarnings("unused")
+public class ApplicationLoadBalancerResponse extends BaseResponse implements ControlledEntityResponse{
+    @SerializedName(ApiConstants.ID) @Param(description = "the Load Balancer ID")
+    private String id;
+
+    @SerializedName(ApiConstants.NAME) @Param(description = "the name of the Load Balancer")
+    private String name;
+
+    @SerializedName(ApiConstants.DESCRIPTION) @Param(description = "the description of the Load Balancer")
+    private String description;
+    
+    @SerializedName(ApiConstants.ALGORITHM) @Param(description = "the load balancer algorithm (source, roundrobin, leastconn)")
+    private String algorithm;
+    
+    @SerializedName(ApiConstants.NETWORK_ID) @Param(description="Load Balancer network id")
+    private String networkId;
+    
+    @SerializedName(ApiConstants.SOURCE_IP) @Param(description="Load Balancer source ip")
+    private String sourceIp;
+    
+    @SerializedName(ApiConstants.SOURCE_IP_NETWORK_ID) @Param(description="Load Balancer source ip network id")
+    private String sourceIpNetworkId;
+    
+    @SerializedName(ApiConstants.ACCOUNT)
+    @Param(description = "the account of the Load Balancer")
+    private String accountName;
+
+    @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the Load Balancer")
+    private String projectId;
+
+    @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the Load Balancer")
+    private String projectName;
+
+    @SerializedName(ApiConstants.DOMAIN_ID)
+    @Param(description = "the domain ID of the Load Balancer")
+    private String domainId;
+    
+    @SerializedName(ApiConstants.DOMAIN)
+    @Param(description = "the domain of the Load Balancer")
+    private String domainName;
+    
+    @SerializedName("loadbalancerrule")  @Param(description="the list of rules associated with the Load Balancer", responseObject = ApplicationLoadBalancerRuleResponse.class)
+    private List<ApplicationLoadBalancerRuleResponse> lbRules;
+    
+    @SerializedName("loadbalancerinstance")  @Param(description="the list of instances associated with the Load Balancer", responseObject = ApplicationLoadBalancerInstanceResponse.class)
+    private List<ApplicationLoadBalancerInstanceResponse> lbInstances;
+    
+    @SerializedName(ApiConstants.TAGS)  @Param(description="the list of resource tags associated with the Load Balancer", responseObject = ResourceTagResponse.class)
+    private List<ResourceTagResponse> tags;
+
+    public void setAccountName(String accountName) {
+        this.accountName = accountName;
+    }
+
+    @Override
+    public void setDomainId(String domainId) {
+        this.domainId = domainId;
+    }
+
+    public void setDomainName(String domainName) {
+        this.domainName = domainName;
+    }
+    
+    @Override
+    public void setProjectId(String projectId) {
+        this.projectId = projectId;
+    }
+
+    @Override
+    public void setProjectName(String projectName) {
+        this.projectName = projectName;
+    }
+
+    public void setTags(List<ResourceTagResponse> tags) {
+        this.tags = tags;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public void setAlgorithm(String algorithm) {
+        this.algorithm = algorithm;
+    }
+
+    public void setNetworkId(String networkId) {
+        this.networkId = networkId;
+    }
+
+    public void setSourceIp(String sourceIp) {
+        this.sourceIp = sourceIp;
+    }
+
+    public void setSourceIpNetworkId(String sourceIpNetworkId) {
+        this.sourceIpNetworkId = sourceIpNetworkId;
+    }
+
+    public void setLbRules(List<ApplicationLoadBalancerRuleResponse> lbRules) {
+        this.lbRules = lbRules;
+    }
+
+    public void setLbInstances(List<ApplicationLoadBalancerInstanceResponse> lbInstances) {
+        this.lbInstances = lbInstances;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerRuleResponse.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerRuleResponse.java b/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerRuleResponse.java
new file mode 100644
index 0000000..ffc64d5
--- /dev/null
+++ b/api/src/org/apache/cloudstack/api/response/ApplicationLoadBalancerRuleResponse.java
@@ -0,0 +1,51 @@
+// 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 org.apache.cloudstack.api.response;
+
+import org.apache.cloudstack.api.ApiConstants;
+import org.apache.cloudstack.api.BaseResponse;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * Subobject of the load balancer container response
+ */
+@SuppressWarnings("unused")
+public class ApplicationLoadBalancerRuleResponse extends BaseResponse{
+    @SerializedName(ApiConstants.SOURCE_PORT) @Param(description = "source port of the load balancer rule")
+    private Integer sourcePort;
+    
+    @SerializedName(ApiConstants.INSTANCE_PORT) @Param(description = "instance port of the load balancer rule")
+    private Integer instancePort;
+    
+    @SerializedName(ApiConstants.STATE) @Param(description = "the state of the load balancer rule")
+    private String state;
+
+    public void setSourcePort(Integer sourcePort) {
+        this.sourcePort = sourcePort;
+    }
+
+    public void setInstancePort(Integer instancePort) {
+        this.instancePort = instancePort;
+    }
+
+    public void setState(String state) {
+        this.state = state;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/api/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerService.java
----------------------------------------------------------------------
diff --git a/api/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerService.java b/api/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerService.java
new file mode 100644
index 0000000..d9971f9
--- /dev/null
+++ b/api/src/org/apache/cloudstack/network/lb/ApplicationLoadBalancerService.java
@@ -0,0 +1,38 @@
+// 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 org.apache.cloudstack.network.lb;
+
+import java.util.List;
+
+import com.cloud.exception.InsufficientAddressCapacityException;
+import com.cloud.exception.NetworkRuleConflictException;
+import com.cloud.network.rules.ApplicationLoadBalancerRule;
+import com.cloud.network.rules.LoadBalancerContainer.Scheme;
+import com.cloud.utils.Pair;
+
+public interface ApplicationLoadBalancerService {
+    
+    ApplicationLoadBalancerRule createApplicationLoadBalancer(String name, String description, Scheme scheme, long sourceIpNetworkId, String sourceIp,
+            int sourcePort, int instancePort, String algorithm, long networkId, long lbOwnerId) throws InsufficientAddressCapacityException,
+            NetworkRuleConflictException;
+    
+    boolean deleteApplicationLoadBalancer(long id);
+    
+    Pair<List<? extends ApplicationLoadBalancerRule>, Integer> listApplicationLoadBalancers();
+
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/client/tomcatconf/applicationContext.xml.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/applicationContext.xml.in b/client/tomcatconf/applicationContext.xml.in
index 67b1286..6d49145 100644
--- a/client/tomcatconf/applicationContext.xml.in
+++ b/client/tomcatconf/applicationContext.xml.in
@@ -785,6 +785,8 @@
   <bean id="vMSnapshotManagerImpl" class="com.cloud.vm.snapshot.VMSnapshotManagerImpl" />
   <bean id="volumeManagerImpl" class="com.cloud.storage.VolumeManagerImpl" />
   <bean id="ClassicalPrimaryDataStoreProvider" class="org.apache.cloudstack.storage.datastore.provider.CloudStackPrimaryDataStoreProviderImpl" />
+  <bean id="ApplicationLoadBalancerService" class="org.apache.cloudstack.network.lb.ApplicationLoadBalancerManagerImpl" />
+
 
 
 <!--=======================================================================================================-->

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/client/tomcatconf/commands.properties.in
----------------------------------------------------------------------
diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in
index 163c2ce..af302c6 100644
--- a/client/tomcatconf/commands.properties.in
+++ b/client/tomcatconf/commands.properties.in
@@ -568,3 +568,9 @@ revertToSnapshot=15
 
 #### Baremetal commands
 addBaremetalHost=1
+
+#### New Load Balancer commands
+createLoadBalancer=15
+listLoadBalancers=15
+deleteLoadBalancer=15
+

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java
index aea795d..fc9548e 100644
--- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java
+++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java
@@ -32,7 +32,7 @@ public interface ElasticLoadBalancerManager {
     public static final int DEFAULT_ELB_VM_CPU_MHZ = 256;               // 500 MHz
 
     public boolean applyLoadBalancerRules(Network network, 
-            List<? extends FirewallRule> rules) 
+            List<LoadBalancingRule> rules) 
             throws ResourceUnavailableException;
 
     public LoadBalancer handleCreateLoadBalancerRule(CreateLoadBalancerRuleCmd lb, Account caller, long networkId) throws InsufficientAddressCapacityException, NetworkRuleConflictException;

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
----------------------------------------------------------------------
diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
index 283b517..49b9022 100644
--- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
+++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java
@@ -331,7 +331,7 @@ ElasticLoadBalancerManager, VirtualMachineGuru<DomainRouterVO> {
         return sendCommandsToRouter(elbVm, cmds);
     }
     
-    protected DomainRouterVO findElbVmForLb(FirewallRule lb) {//TODO: use a table to lookup
+    protected DomainRouterVO findElbVmForLb(LoadBalancingRule lb) {//TODO: use a table to lookup
         ElasticLbVmMapVO map = _elbVmMapDao.findOneByIp(lb.getSourceIpAddressId());
         if (map == null) {
             return null;
@@ -342,15 +342,11 @@ ElasticLoadBalancerManager, VirtualMachineGuru<DomainRouterVO> {
 
     @Override
     public boolean applyLoadBalancerRules(Network network,
-            List<? extends FirewallRule> rules)
+            List<LoadBalancingRule> rules)
             throws ResourceUnavailableException {
         if (rules == null || rules.isEmpty()) {
             return true;
         }
-        if (rules.get(0).getPurpose() != Purpose.LoadBalancing) {
-            s_logger.warn("ELB: Not handling non-LB firewall rules");
-            return false;
-        }
         
         DomainRouterVO elbVm = findElbVmForLb(rules.get(0));
                                                                           
@@ -656,7 +652,10 @@ ElasticLoadBalancerManager, VirtualMachineGuru<DomainRouterVO> {
             LoadBalancer result = null;
             try {
                 lb.setSourceIpAddressId(ipId);
-                result = _lbMgr.createLoadBalancer(lb, false);
+                
+                result = _lbMgr.createPublicLoadBalancer(lb.getXid(), lb.getName(), lb.getDescription(), 
+                        lb.getSourcePortStart(), lb.getSourcePortEnd(), lb.getDefaultPortStart(), ipId.longValue(),
+                        lb.getProtocol(), lb.getAlgorithm(), false, UserContext.current());
             } catch (NetworkRuleConflictException e) {
                 s_logger.warn("Failed to create LB rule, not continuing with ELB deployment");
                 if (newIp) {

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/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 93b755a..e77a130 100755
--- a/server/src/com/cloud/api/ApiResponseHelper.java
+++ b/server/src/com/cloud/api/ApiResponseHelper.java
@@ -42,6 +42,9 @@ import org.apache.cloudstack.api.BaseCmd;
 import org.apache.cloudstack.api.ResponseGenerator;
 import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd;
 import org.apache.cloudstack.api.response.AccountResponse;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerInstanceResponse;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerResponse;
+import org.apache.cloudstack.api.response.ApplicationLoadBalancerRuleResponse;
 import org.apache.cloudstack.api.response.AsyncJobResponse;
 import org.apache.cloudstack.api.response.AutoScalePolicyResponse;
 import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse;
@@ -204,10 +207,12 @@ import com.cloud.network.dao.IPAddressVO;
 import com.cloud.network.dao.NetworkVO;
 import com.cloud.network.dao.PhysicalNetworkVO;
 import com.cloud.network.router.VirtualRouter;
+import com.cloud.network.rules.ApplicationLoadBalancerRule;
 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.LoadBalancerContainer.Scheme;
 import com.cloud.network.rules.PortForwardingRule;
 import com.cloud.network.rules.StaticNatRule;
 import com.cloud.network.rules.StickinessPolicy;
@@ -261,6 +266,7 @@ import com.cloud.user.UserContext;
 import com.cloud.uservm.UserVm;
 import com.cloud.utils.Pair;
 import com.cloud.utils.StringUtils;
+import com.cloud.utils.net.Ip;
 import com.cloud.utils.net.NetUtils;
 import com.cloud.vm.ConsoleProxyVO;
 import com.cloud.vm.InstanceGroup;
@@ -721,7 +727,7 @@ public class ApiResponseHelper implements ResponseGenerator {
         }
 
         //set tag information
-        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, loadBalancer.getId());
+        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.LoadBalancer, loadBalancer.getId());
         List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
         for (ResourceTag tag : tags) {
             ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
@@ -3620,4 +3626,69 @@ public class ApiResponseHelper implements ResponseGenerator {
         response.setIsDefault(result.isDefaultNic());
         return response;
     }
+    
+    @Override
+    public ApplicationLoadBalancerResponse createLoadBalancerContainerReponse(LoadBalancer lb, Map<Ip, UserVm> lbInstances) {
+
+        ApplicationLoadBalancerResponse lbResponse = new ApplicationLoadBalancerResponse();
+        lbResponse.setId(lb.getUuid());
+        lbResponse.setName(lb.getName());
+        lbResponse.setDescription(lb.getDescription());
+        lbResponse.setAlgorithm(lb.getAlgorithm());
+        Network nw = ApiDBUtils.findNetworkById(lb.getNetworkId());
+        lbResponse.setNetworkId(nw.getUuid());
+        populateOwner(lbResponse, lb);
+        
+        if (lb.getScheme() == Scheme.Internal) {
+            ApplicationLoadBalancerRule ruleInternal = (ApplicationLoadBalancerRule)lb;
+            lbResponse.setSourceIp(ruleInternal.getSourceIpAddress().addr());
+            lbResponse.setSourceIpNetworkId(ruleInternal.getSourceIpNetworkUuid());
+        } else {
+            //for public, populate the ip information from the ip address
+            IpAddress publicIp = ApiDBUtils.findIpAddressById(lb.getSourceIpAddressId());
+            lbResponse.setSourceIp(publicIp.getAddress().addr());
+            Network ntwk = ApiDBUtils.findNetworkById(publicIp.getNetworkId());
+            lbResponse.setSourceIpNetworkId(ntwk.getUuid());
+        }
+        
+        //set load balancer rules information (only one rule per load balancer in this release)
+        List<ApplicationLoadBalancerRuleResponse> ruleResponses = new ArrayList<ApplicationLoadBalancerRuleResponse>();
+        ApplicationLoadBalancerRuleResponse ruleResponse = new ApplicationLoadBalancerRuleResponse();
+        ruleResponse.setInstancePort(lb.getDefaultPortStart());
+        ruleResponse.setSourcePort(lb.getSourcePortStart());
+        String stateToSet = lb.getState().toString();
+        if (stateToSet.equals(FirewallRule.State.Revoke)) {
+            stateToSet = "Deleting";
+        }
+        ruleResponse.setState(stateToSet);
+        ruleResponse.setObjectName("loadbalancerrule");
+        ruleResponses.add(ruleResponse);
+        lbResponse.setLbRules(ruleResponses);
+        
+        //set Lb instances information
+        List<ApplicationLoadBalancerInstanceResponse> instanceResponses = new ArrayList<ApplicationLoadBalancerInstanceResponse>();
+        for (Ip ip : lbInstances.keySet()) {
+            ApplicationLoadBalancerInstanceResponse instanceResponse = new ApplicationLoadBalancerInstanceResponse();
+            instanceResponse.setIpAddress(ip.addr());
+            UserVm vm = lbInstances.get(ip);
+            instanceResponse.setId(vm.getUuid());
+            instanceResponse.setName(vm.getInstanceName());
+            instanceResponse.setObjectName("loadbalancerinstance");
+            instanceResponses.add(instanceResponse);
+        }
+        
+        lbResponse.setLbInstances(instanceResponses);
+
+        //set tag information
+        List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.LoadBalancer, lb.getId());
+        List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
+        for (ResourceTag tag : tags) {
+            ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
+            tagResponses.add(tagResponse);
+        }
+        lbResponse.setTags(tagResponses);
+
+        lbResponse.setObjectName("loadbalancer");
+        return lbResponse;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/server/src/com/cloud/network/NetworkModelImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/NetworkModelImpl.java b/server/src/com/cloud/network/NetworkModelImpl.java
index 4c13c91..d7108db 100644
--- a/server/src/com/cloud/network/NetworkModelImpl.java
+++ b/server/src/com/cloud/network/NetworkModelImpl.java
@@ -2033,4 +2033,9 @@ public class NetworkModelImpl extends ManagerBase implements NetworkModel {
         }
         return null;
     }
+    
+    @Override
+    public IpAddress getPublicIpAddress(String ipAddress, long networkId) {
+        return _ipAddressDao.findByIpAndSourceNetworkId(networkId, ipAddress);
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/server/src/com/cloud/network/dao/ApplicationLoadBalancerRuleVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/dao/ApplicationLoadBalancerRuleVO.java b/server/src/com/cloud/network/dao/ApplicationLoadBalancerRuleVO.java
new file mode 100644
index 0000000..91f28e2
--- /dev/null
+++ b/server/src/com/cloud/network/dao/ApplicationLoadBalancerRuleVO.java
@@ -0,0 +1,78 @@
+// 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 javax.persistence.Column;
+import javax.persistence.DiscriminatorValue;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.Id;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+import com.cloud.network.rules.ApplicationLoadBalancerRule;
+import com.cloud.utils.net.Ip;
+
+/**
+ * This VO represent Internal Load Balancer rule.
+ * Instead of pointing to the public ip address id directly as External Load Balancer rule does, it refers to the ip address by its value/sourceNetworkid
+ *
+ */
+@Entity
+@Table(name=("load_balancing_rules"))
+@DiscriminatorValue(value="LoadBalancing")
+@PrimaryKeyJoinColumn(name="id")
+public class ApplicationLoadBalancerRuleVO extends LoadBalancerVO implements ApplicationLoadBalancerRule{
+    
+    
+    @Column(name="source_ip_address_network_id")
+    String sourceIpNetworkUuid;
+    
+    @Id
+    @Column(name="source_ip_address")
+    @Enumerated(value=EnumType.STRING)
+    private Ip sourceIpAddress = null;
+    
+
+    public ApplicationLoadBalancerRuleVO() {  
+    }
+    
+    public ApplicationLoadBalancerRuleVO(String xId, String name, String description, int srcPort, int dstPort, String algorithm, long networkId,
+            long accountId, long domainId, Ip sourceIp, String sourceIpNtwkUuid) {
+        
+        super(xId, name, description, srcPort, dstPort, algorithm, networkId, accountId, domainId);
+        this.sourceIpAddress = sourceIp;
+        this.sourceIpNetworkUuid = sourceIpNtwkUuid;
+    }
+    
+    @Override
+    public String getSourceIpNetworkUuid() {
+        return sourceIpNetworkUuid;
+    }
+
+    @Override
+    public Ip getSourceIpAddress() {
+        return sourceIpAddress;
+    }
+
+    @Override
+    public int getInstancePort() {
+        return super.getDefaultPortStart();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/server/src/com/cloud/network/dao/IPAddressVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/dao/IPAddressVO.java b/server/src/com/cloud/network/dao/IPAddressVO.java
index 8ce8d33..281f211 100644
--- a/server/src/com/cloud/network/dao/IPAddressVO.java
+++ b/server/src/com/cloud/network/dao/IPAddressVO.java
@@ -31,12 +31,8 @@ import javax.persistence.Temporal;
 import javax.persistence.TemporalType;
 import javax.persistence.Transient;
 
-import org.apache.cloudstack.api.Identity;
-
 import com.cloud.network.IpAddress;
-import com.cloud.network.IpAddress.State;
 import com.cloud.utils.net.Ip;
-import org.apache.cloudstack.api.InternalIdentity;
 
 /**
  * A bean representing a public IP Address
@@ -306,4 +302,9 @@ public class IPAddressVO implements IpAddress {
     public void setVmIp(String vmIp) {
         this.vmIp = vmIp;
     }
+
+    @Override
+    public Long getNetworkId() {
+        return sourceNetworkId;
+    }
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/server/src/com/cloud/network/dao/LoadBalancerVO.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/dao/LoadBalancerVO.java b/server/src/com/cloud/network/dao/LoadBalancerVO.java
index 5422f41..d0cffcd 100644
--- a/server/src/com/cloud/network/dao/LoadBalancerVO.java
+++ b/server/src/com/cloud/network/dao/LoadBalancerVO.java
@@ -19,6 +19,8 @@ package com.cloud.network.dao;
 import javax.persistence.Column;
 import javax.persistence.DiscriminatorValue;
 import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
 import javax.persistence.PrimaryKeyJoinColumn;
 import javax.persistence.Table;
 
@@ -26,6 +28,12 @@ import com.cloud.network.rules.FirewallRuleVO;
 import com.cloud.network.rules.LoadBalancer;
 import com.cloud.utils.net.NetUtils;
 
+/**
+ * This VO represent Public Load Balancer
+ * It references source ip address by its Id. 
+ * To get the VO for Internal Load Balancer rule, please refer to LoadBalancerRuleVO
+ *
+ */
 @Entity
 @Table(name=("load_balancing_rules"))
 @DiscriminatorValue(value="LoadBalancing")
@@ -46,6 +54,10 @@ public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer {
     
     @Column(name="default_port_end")
     private int defaultPortEnd;
+    
+    @Enumerated(value=EnumType.STRING)
+    @Column(name="scheme")
+    Scheme scheme;
 
     public LoadBalancerVO() { 
     }
@@ -57,6 +69,19 @@ public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer {
         this.algorithm = algorithm;
         this.defaultPortStart = dstPort;
         this.defaultPortEnd = dstPort;
+        this.scheme = Scheme.Public;
+    }
+    
+    
+    protected LoadBalancerVO(String xId, String name, String description, int srcPort, int dstPort, String algorithm, long networkId, long accountId, long domainId) {
+        super(xId, null, srcPort, dstPort, NetUtils.TCP_PROTO, networkId, accountId, domainId, Purpose.LoadBalancing, null, null,
+                null, null, null); 
+        this.name = name;
+        this.description = description;
+        this.algorithm = algorithm;
+        this.defaultPortStart = dstPort;
+        this.defaultPortEnd = dstPort;
+        this.scheme = Scheme.Internal;
     }
     
     @Override
@@ -94,5 +119,10 @@ public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer {
 
     public void setDescription(String description) {
         this.description = description;
+    }
+
+    @Override
+    public Scheme getScheme() {
+        return scheme;
     }  
 }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/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 169db32..6fb6ad6 100755
--- a/server/src/com/cloud/network/element/VirtualRouterElement.java
+++ b/server/src/com/cloud/network/element/VirtualRouterElement.java
@@ -358,8 +358,8 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl
                 return true;
             }
 
-            if (!_routerMgr.applyFirewallRules(network, rules, routers)) {
-                throw new CloudRuntimeException("Failed to apply firewall rules in network " + network.getId());
+            if (!_routerMgr.applyLoadBalancingRules(network, rules, routers)) {
+                throw new CloudRuntimeException("Failed to apply load balancing rules in network " + network.getId());
             } else {
                 return true;
             }

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
----------------------------------------------------------------------
diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
index 080f7b0..9a425e1 100644
--- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
+++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java
@@ -27,16 +27,11 @@ import javax.ejb.Local;
 import javax.inject.Inject;
 import javax.naming.ConfigurationException;
 
+import org.apache.cloudstack.api.command.user.firewall.ListEgressFirewallRulesCmd;
 import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd;
 import org.apache.log4j.Logger;
 import org.springframework.stereotype.Component;
 
-import com.mysql.jdbc.ConnectionPropertiesImpl;
-import org.apache.log4j.Logger;
-
-import org.apache.cloudstack.api.BaseListCmd;
-import org.apache.cloudstack.api.command.user.firewall.ListEgressFirewallRulesCmd;
-import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd;
 import com.cloud.configuration.Config;
 import com.cloud.configuration.dao.ConfigurationDao;
 import com.cloud.domain.dao.DomainDao;
@@ -52,7 +47,6 @@ import com.cloud.network.IpAddress;
 import com.cloud.network.Network;
 import com.cloud.network.Network.Capability;
 import com.cloud.network.Network.Service;
-import com.cloud.network.Networks.TrafficType;
 import com.cloud.network.NetworkManager;
 import com.cloud.network.NetworkModel;
 import com.cloud.network.NetworkRuleApplier;
@@ -64,10 +58,15 @@ import com.cloud.network.element.FirewallServiceProvider;
 import com.cloud.network.element.NetworkACLServiceProvider;
 import com.cloud.network.element.PortForwardingServiceProvider;
 import com.cloud.network.element.StaticNatServiceProvider;
-import com.cloud.network.rules.*;
+import com.cloud.network.rules.FirewallManager;
+import com.cloud.network.rules.FirewallRule;
 import com.cloud.network.rules.FirewallRule.FirewallRuleType;
 import com.cloud.network.rules.FirewallRule.Purpose;
 import com.cloud.network.rules.FirewallRule.State;
+import com.cloud.network.rules.FirewallRuleVO;
+import com.cloud.network.rules.PortForwardingRule;
+import com.cloud.network.rules.PortForwardingRuleVO;
+import com.cloud.network.rules.StaticNat;
 import com.cloud.network.rules.dao.PortForwardingRulesDao;
 import com.cloud.network.vpc.VpcManager;
 import com.cloud.projects.Project.ListProjectResourcesCriteria;
@@ -86,8 +85,8 @@ import com.cloud.utils.db.Filter;
 import com.cloud.utils.db.JoinBuilder;
 import com.cloud.utils.db.SearchBuilder;
 import com.cloud.utils.db.SearchCriteria;
-import com.cloud.utils.db.*;
 import com.cloud.utils.db.SearchCriteria.Op;
+import com.cloud.utils.db.Transaction;
 import com.cloud.utils.exception.CloudRuntimeException;
 import com.cloud.utils.net.NetUtils;
 import com.cloud.vm.UserVmVO;
@@ -434,22 +433,28 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService,
             return;
         }
 
-        if (ipAddress!=null){
-        if (ipAddress.getAssociatedWithNetworkId() == null) {
-                throw new InvalidParameterValueException("Unable to create firewall rule ; ip with specified id is not associated with any network");
-        } else {
-            networkId = ipAddress.getAssociatedWithNetworkId();
-        }
-
+        if (ipAddress != null){
+            if (ipAddress.getAssociatedWithNetworkId() == null) {
+                    throw new InvalidParameterValueException("Unable to create firewall rule ; ip with specified id is not associated with any network");
+            } else {
+                networkId = ipAddress.getAssociatedWithNetworkId();
+            }
+    
             // Validate ip address
             _accountMgr.checkAccess(caller, null, true, ipAddress);
-
+        }
+        
+        //network id either has to be passed explicitly, or implicitly as a part of ipAddress object 
+        if (networkId == null) {
+            throw new InvalidParameterValueException("Unable to retrieve network id to validate the rule");
+        }
+    
         Network network = _networkModel.getNetwork(networkId);
-        assert network != null : "Can't create port forwarding rule as network associated with public ip address is null?";
+        assert network != null : "Can't create rule as network associated with public ip address is null?";
 
-            if (trafficType == FirewallRule.TrafficType.Egress) {
-                _accountMgr.checkAccess(caller, null, true, network);
-            }
+        if (trafficType == FirewallRule.TrafficType.Egress) {
+            _accountMgr.checkAccess(caller, null, true, network);
+        }
 
         // Verify that the network guru supports the protocol specified
         Map<Network.Capability, String> caps = null;
@@ -460,32 +465,32 @@ public class FirewallManagerImpl extends ManagerBase implements FirewallService,
             }
         } else if (purpose == Purpose.PortForwarding) {
             caps = _networkModel.getNetworkServiceCapabilities(network.getId(), Service.PortForwarding);
-            }else if (purpose == Purpose.Firewall){
-                caps = _networkModel.getNetworkServiceCapabilities(network.getId(),Service.Firewall);
+        } else if (purpose == Purpose.Firewall){
+            caps = _networkModel.getNetworkServiceCapabilities(network.getId(),Service.Firewall);
         }
 
         if (caps != null) {
-                String supportedProtocols;
-                String supportedTrafficTypes = null;
-                if (purpose == FirewallRule.Purpose.Firewall) {
-                    supportedTrafficTypes = caps.get(Capability.SupportedTrafficDirection).toLowerCase();
-                }
+            String supportedProtocols;
+            String supportedTrafficTypes = null;
+            if (purpose == FirewallRule.Purpose.Firewall) {
+                supportedTrafficTypes = caps.get(Capability.SupportedTrafficDirection).toLowerCase();
+            }
 
-                if (purpose == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress) {
-                    supportedProtocols = caps.get(Capability.SupportedEgressProtocols).toLowerCase();
-                } else {
-                    supportedProtocols = caps.get(Capability.SupportedProtocols).toLowerCase();
-                }
+            if (purpose == FirewallRule.Purpose.Firewall && trafficType == FirewallRule.TrafficType.Egress) {
+                supportedProtocols = caps.get(Capability.SupportedEgressProtocols).toLowerCase();
+            } else {
+                supportedProtocols = caps.get(Capability.SupportedProtocols).toLowerCase();
+            }
 
             if (!supportedProtocols.contains(proto.toLowerCase())) {
                 throw new InvalidParameterValueException("Protocol " + proto + " is not supported in zone " + network.getDataCenterId());
             } else if (proto.equalsIgnoreCase(NetUtils.ICMP_PROTO) && purpose != Purpose.Firewall) {
                 throw new InvalidParameterValueException("Protocol " + proto + " is currently supported only for rules with purpose " + Purpose.Firewall);
-                } else if (purpose == Purpose.Firewall && !supportedTrafficTypes.contains(trafficType.toString().toLowerCase())) {
-                    throw new InvalidParameterValueException("Traffic Type " + trafficType + " is currently supported by Firewall in network " + networkId);
-                }
+            } else if (purpose == Purpose.Firewall && !supportedTrafficTypes.contains(trafficType.toString().toLowerCase())) {
+                throw new InvalidParameterValueException("Traffic Type " + trafficType + " is currently supported by Firewall in network " + networkId);
             }
         }
+        
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/cloudstack/blob/08f855d4/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 d98872a..22df280 100644
--- a/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java
+++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java
@@ -16,23 +16,23 @@
 // under the License.
 package com.cloud.network.lb;
 
+import java.util.List;
+
 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;
 import com.cloud.network.rules.LoadBalancer;
 import com.cloud.user.Account;
-import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd;
-
-import java.util.List;
+import com.cloud.user.UserContext;
 
 public interface LoadBalancingRulesManager extends LoadBalancingRulesService {
 
-    LoadBalancer createLoadBalancer(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException;
+    LoadBalancer createPublicLoadBalancer(String xId, String name, String description, 
+            int srcPortStart, int srcPortEnd, int defPortStart, long sourceIpId, String protocol, String algorithm, boolean openFirewall, UserContext caller)
+            throws NetworkRuleConflictException;
 
     boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId);
     boolean removeAllLoadBalanacersForNetwork(long networkId, Account caller, long callerUserId);
@@ -47,7 +47,6 @@ public interface LoadBalancingRulesManager extends LoadBalancingRulesService {
      * @return true if removal is successful
      */
     boolean removeVmFromLoadBalancers(long vmId);
-    boolean applyRules(Network network, FirewallRule.Purpose purpose, List<? extends FirewallRule> rules) throws ResourceUnavailableException ;
     boolean applyLoadBalancersForNetwork(long networkId) throws ResourceUnavailableException;
     String getLBCapability(long networkid, String capabilityName);
     boolean configureLbAutoScaleVmGroup(long vmGroupid, String currentState) throws ResourceUnavailableException;