@Override
  @DB
  @ActionEvent(
      eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE,
      eventDescription = "creating load balancer")
  public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall)
      throws NetworkRuleConflictException, InsufficientAddressCapacityException {
    UserContext caller = UserContext.current();

    int defPortStart = lb.getDefaultPortStart();
    int defPortEnd = lb.getDefaultPortEnd();

    if (!NetUtils.isValidPort(defPortEnd)) {
      throw new InvalidParameterValueException("privatePort is an invalid value: " + defPortEnd);
    }
    if (defPortStart > defPortEnd) {
      throw new InvalidParameterValueException(
          "private port range is invalid: " + defPortStart + "-" + defPortEnd);
    }
    if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) {
      throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm());
    }

    LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb, caller.getCaller());
    if (result == null) {
      result = createLoadBalancer(lb, openFirewall);
    }
    return result;
  }
  @Override
  @ActionEvent(
      eventType = EventTypes.EVENT_LOAD_BALANCER_DELETE,
      eventDescription = "deleting load balancer",
      async = true)
  public boolean deleteLoadBalancerRule(long loadBalancerId, boolean apply) {
    UserContext ctx = UserContext.current();
    Account caller = ctx.getCaller();

    LoadBalancerVO rule = _lbDao.findById(loadBalancerId);
    if (rule == null) {
      throw new InvalidParameterValueException(
          "Unable to find load balancer rule " + loadBalancerId);
    }

    _accountMgr.checkAccess(caller, null, rule);

    return deleteLoadBalancerRule(loadBalancerId, apply, caller, ctx.getCallerUserId());
  }
  private boolean removeFromLoadBalancerInternal(long loadBalancerId, List<Long> instanceIds) {
    UserContext caller = UserContext.current();

    LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(loadBalancerId));
    if (loadBalancer == null) {
      throw new InvalidParameterException("Invalid load balancer value: " + loadBalancerId);
    }

    _accountMgr.checkAccess(caller.getCaller(), null, loadBalancer);

    try {
      loadBalancer.setState(FirewallRule.State.Add);
      _lbDao.persist(loadBalancer);

      for (long instanceId : instanceIds) {
        LoadBalancerVMMapVO map =
            _lb2VmMapDao.findByLoadBalancerIdAndVmId(loadBalancerId, instanceId);
        map.setRevoke(true);
        _lb2VmMapDao.persist(map);
        s_logger.debug(
            "Set load balancer rule for revoke: rule id "
                + loadBalancerId
                + ", vmId "
                + instanceId);
      }

      if (!applyLoadBalancerConfig(loadBalancerId)) {
        s_logger.warn(
            "Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
        throw new CloudRuntimeException(
            "Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds);
      }

    } catch (ResourceUnavailableException e) {
      s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
      return false;
    }

    return true;
  }
  @DB
  public LoadBalancer createLoadBalancer(CreateLoadBalancerRuleCmd lb, boolean openFirewall)
      throws NetworkRuleConflictException {
    long ipId = lb.getSourceIpAddressId();
    UserContext caller = UserContext.current();
    int srcPortStart = lb.getSourcePortStart();
    int defPortStart = lb.getDefaultPortStart();
    int srcPortEnd = lb.getSourcePortEnd();

    IPAddressVO ipAddr = _ipAddressDao.findById(lb.getSourceIpAddressId());
    Long networkId = ipAddr.getSourceNetworkId();
    // make sure ip address exists
    if (ipAddr == null || !ipAddr.readyToUse()) {
      throw new InvalidParameterValueException(
          "Unable to create load balancer rule, invalid IP address id" + ipId);
    }

    _firewallMgr.validateFirewallRule(
        caller.getCaller(),
        ipAddr,
        srcPortStart,
        srcPortEnd,
        lb.getProtocol(),
        Purpose.LoadBalancing);

    networkId = ipAddr.getAssociatedWithNetworkId();
    if (networkId == null) {
      throw new InvalidParameterValueException(
          "Unable to create load balancer rule ; ip id="
              + ipId
              + " is not associated with any network");
    }
    NetworkVO network = _networkDao.findById(networkId);

    _accountMgr.checkAccess(caller.getCaller(), null, ipAddr);

    // verify that lb service is supported by the network
    if (!_networkMgr.isServiceSupported(network.getNetworkOfferingId(), Service.Lb)) {
      throw new InvalidParameterValueException(
          "LB service is not supported in network id= " + networkId);
    }

    Transaction txn = Transaction.currentTxn();
    txn.start();

    LoadBalancerVO newRule =
        new LoadBalancerVO(
            lb.getXid(),
            lb.getName(),
            lb.getDescription(),
            lb.getSourceIpAddressId(),
            lb.getSourcePortEnd(),
            lb.getDefaultPortStart(),
            lb.getAlgorithm(),
            network.getId(),
            ipAddr.getAccountId(),
            ipAddr.getDomainId());

    newRule = _lbDao.persist(newRule);

    if (openFirewall) {
      _firewallMgr.createRuleForAllCidrs(
          ipId,
          caller.getCaller(),
          lb.getSourcePortStart(),
          lb.getSourcePortEnd(),
          lb.getProtocol(),
          null,
          null,
          newRule.getId());
    }

    boolean success = true;

    try {
      _firewallMgr.detectRulesConflict(newRule, ipAddr);
      if (!_firewallDao.setStateToAdd(newRule)) {
        throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
      }
      s_logger.debug(
          "Load balancer "
              + newRule.getId()
              + " for Ip address id="
              + ipId
              + ", public port "
              + srcPortStart
              + ", private port "
              + defPortStart
              + " is added successfully.");
      UserContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
      UsageEventVO usageEvent =
          new UsageEventVO(
              EventTypes.EVENT_LOAD_BALANCER_CREATE,
              ipAddr.getAllocatedToAccountId(),
              ipAddr.getDataCenterId(),
              newRule.getId(),
              null);
      _usageEventDao.persist(usageEvent);
      txn.commit();

      return newRule;
    } catch (Exception e) {
      success = false;
      if (e instanceof NetworkRuleConflictException) {
        throw (NetworkRuleConflictException) e;
      }
      throw new CloudRuntimeException(
          "Unable to add rule for ip address id=" + newRule.getSourceIpAddressId(), e);
    } finally {
      if (!success && newRule != null) {

        txn.start();
        _firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
        _lbDao.remove(newRule.getId());

        txn.commit();
      }
    }
  }
  @Override
  @DB
  @ActionEvent(
      eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE,
      eventDescription = "assigning to load balancer",
      async = true)
  public boolean assignToLoadBalancer(long loadBalancerId, List<Long> instanceIds) {
    UserContext ctx = UserContext.current();
    Account caller = ctx.getCaller();

    LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
      throw new InvalidParameterValueException(
          "Failed to assign to load balancer "
              + loadBalancerId
              + ", the load balancer was not found.");
    }

    List<LoadBalancerVMMapVO> mappedInstances =
        _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false);
    Set<Long> mappedInstanceIds = new HashSet<Long>();
    for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
      mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
    }

    List<UserVm> vmsToAdd = new ArrayList<UserVm>();

    for (Long instanceId : instanceIds) {
      if (mappedInstanceIds.contains(instanceId)) {
        throw new InvalidParameterValueException(
            "VM " + instanceId + " is already mapped to load balancer.");
      }

      UserVm vm = _vmDao.findById(instanceId);
      if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
        throw new InvalidParameterValueException("Invalid instance id: " + instanceId);
      }

      _rulesMgr.checkRuleAndUserVm(loadBalancer, vm, caller);

      if (vm.getAccountId() != loadBalancer.getAccountId()) {
        throw new PermissionDeniedException(
            "Cannot add virtual machines that do not belong to the same owner.");
      }

      // Let's check to make sure the vm has a nic in the same network as the load balancing rule.
      List<? extends Nic> nics = _networkMgr.getNics(vm.getId());
      Nic nicInSameNetwork = null;
      for (Nic nic : nics) {
        if (nic.getNetworkId() == loadBalancer.getNetworkId()) {
          nicInSameNetwork = nic;
          break;
        }
      }

      if (nicInSameNetwork == null) {
        throw new InvalidParameterValueException(
            "VM " + instanceId + " cannot be added because it doesn't belong in the same network.");
      }

      if (s_logger.isDebugEnabled()) {
        s_logger.debug("Adding " + vm + " to the load balancer pool");
      }
      vmsToAdd.add(vm);
    }

    Transaction txn = Transaction.currentTxn();
    txn.start();

    for (UserVm vm : vmsToAdd) {
      LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vm.getId(), false);
      map = _lb2VmMapDao.persist(map);
    }
    txn.commit();

    try {
      loadBalancer.setState(FirewallRule.State.Add);
      _lbDao.persist(loadBalancer);
      applyLoadBalancerConfig(loadBalancerId);
    } catch (ResourceUnavailableException e) {
      s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
      return false;
    }

    return true;
  }
  @Override
  public RemoteAccessVpn createRemoteAccessVpn(
      long publicIpId, String ipRange, boolean openFirewall, long networkId)
      throws NetworkRuleConflictException {
    UserContext ctx = UserContext.current();
    Account caller = ctx.getCaller();

    // make sure ip address exists
    PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
    if (ipAddr == null) {
      throw new InvalidParameterValueException(
          "Unable to create remote access vpn, invalid public IP address id" + publicIpId);
    }

    _accountMgr.checkAccess(caller, null, true, ipAddr);

    if (!ipAddr.readyToUse()) {
      throw new InvalidParameterValueException(
          "The Ip address is not ready to be used yet: " + ipAddr.getAddress());
    }

    IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId);
    _networkMgr.checkIpForService(ipAddress, Service.Vpn, null);

    RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId);

    if (vpnVO != null) {
      // if vpn is in Added state, return it to the api
      if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
        return vpnVO;
      }
      throw new InvalidParameterValueException(
          "A Remote Access VPN already exists for this public Ip address");
    }

    // TODO: assumes one virtual network / domr per account per zone
    vpnVO = _remoteAccessVpnDao.findByAccountAndNetwork(ipAddr.getAccountId(), networkId);
    if (vpnVO != null) {
      // if vpn is in Added state, return it to the api
      if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
        return vpnVO;
      }
      throw new InvalidParameterValueException(
          "A Remote Access VPN already exists for this account");
    }

    // Verify that vpn service is enabled for the network
    Network network = _networkMgr.getNetwork(networkId);
    if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) {
      throw new InvalidParameterValueException(
          "Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId());
    }

    if (ipRange == null) {
      ipRange = _clientIpRange;
    }
    String[] range = ipRange.split("-");
    if (range.length != 2) {
      throw new InvalidParameterValueException("Invalid ip range");
    }
    if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])) {
      throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
    }
    if (!NetUtils.validIpRange(range[0], range[1])) {
      throw new InvalidParameterValueException("Invalid ip range " + ipRange);
    }

    Pair<String, Integer> cidr = NetUtils.getCidr(network.getCidr());

    // FIXME: This check won't work for the case where the guest ip range
    // changes depending on the vlan allocated.
    String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second());
    if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
      throw new InvalidParameterValueException(
          "Invalid ip range: "
              + ipRange
              + " overlaps with guest ip range "
              + guestIpRange[0]
              + "-"
              + guestIpRange[1]);
    }
    // TODO: check sufficient range
    // TODO: check overlap with private and public ip ranges in datacenter

    long startIp = NetUtils.ip2Long(range[0]);
    String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
    String sharedSecret = PasswordGenerator.generatePresharedKey(_pskLength);
    _rulesMgr.reservePorts(
        ipAddr,
        NetUtils.UDP_PROTO,
        Purpose.Vpn,
        openFirewall,
        caller,
        NetUtils.VPN_PORT,
        NetUtils.VPN_L2TP_PORT,
        NetUtils.VPN_NATT_PORT);
    vpnVO =
        new RemoteAccessVpnVO(
            ipAddr.getAccountId(),
            ipAddr.getDomainId(),
            ipAddr.getAssociatedWithNetworkId(),
            publicIpId,
            range[0],
            newIpRange,
            sharedSecret);
    return _remoteAccessVpnDao.persist(vpnVO);
  }
  private String queueCommand(BaseCmd cmdObj, Map<String, String> params) throws Exception {
    UserContext ctx = UserContext.current();
    Long callerUserId = ctx.getCallerUserId();
    Account caller = ctx.getCaller();

    // Queue command based on Cmd super class:
    // BaseCmd: cmd is dispatched to ApiDispatcher, executed, serialized and returned.
    // BaseAsyncCreateCmd: cmd params are processed and create() is called, then same workflow as
    // BaseAsyncCmd.
    // BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized
    // and returned.
    if (cmdObj instanceof BaseAsyncCmd) {
      Long objectId = null;
      String objectUuid = null;
      if (cmdObj instanceof BaseAsyncCreateCmd) {
        BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
        _dispatcher.dispatchCreateCmd(createCmd, params);
        objectId = createCmd.getEntityId();
        objectUuid = createCmd.getEntityUuid();
        params.put("id", objectId.toString());
      } else {
        ApiDispatcher.processParameters(cmdObj, params);
      }

      BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj;

      if (callerUserId != null) {
        params.put("ctxUserId", callerUserId.toString());
      }
      if (caller != null) {
        params.put("ctxAccountId", String.valueOf(caller.getId()));
      }

      long startEventId = ctx.getStartEventId();
      asyncCmd.setStartEventId(startEventId);

      // save the scheduled event
      Long eventId =
          EventUtils.saveScheduledEvent(
              (callerUserId == null) ? User.UID_SYSTEM : callerUserId,
              asyncCmd.getEntityOwnerId(),
              asyncCmd.getEventType(),
              asyncCmd.getEventDescription(),
              startEventId);
      if (startEventId == 0) {
        // There was no create event before, set current event id as start eventId
        startEventId = eventId;
      }

      params.put("ctxStartEventId", String.valueOf(startEventId));

      ctx.setAccountId(asyncCmd.getEntityOwnerId());

      Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId;
      AsyncJobVO job =
          new AsyncJobVO(
              callerUserId,
              caller.getId(),
              cmdObj.getClass().getName(),
              ApiGsonHelper.getBuilder().create().toJson(params),
              instanceId,
              asyncCmd.getInstanceType());

      long jobId = _asyncMgr.submitAsyncJob(job);

      if (jobId == 0L) {
        String errorMsg = "Unable to schedule async job for command " + job.getCmd();
        s_logger.warn(errorMsg);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg);
      }

      if (objectId != null) {
        String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid;
        return ((BaseAsyncCreateCmd) asyncCmd).getResponse(jobId, objUuid);
      }

      SerializationContext.current().setUuidTranslation(true);
      return ApiResponseSerializer.toSerializedString(
          asyncCmd.getResponse(jobId), asyncCmd.getResponseType());
    } else {
      _dispatcher.dispatch(cmdObj, params);

      // if the command is of the listXXXCommand, we will need to also return the
      // the job id and status if possible
      // For those listXXXCommand which we have already created DB views, this step is not needed
      // since async job is joined in their db views.
      if (cmdObj instanceof BaseListCmd
          && !(cmdObj instanceof ListVMsCmd)
          && !(cmdObj instanceof ListRoutersCmd)
          && !(cmdObj instanceof ListSecurityGroupsCmd)
          && !(cmdObj instanceof ListTagsCmd)
          && !(cmdObj instanceof ListEventsCmd)
          && !(cmdObj instanceof ListVMGroupsCmd)
          && !(cmdObj instanceof ListProjectsCmd)
          && !(cmdObj instanceof ListProjectAccountsCmd)
          && !(cmdObj instanceof ListProjectInvitationsCmd)
          && !(cmdObj instanceof ListHostsCmd)
          && !(cmdObj instanceof ListVolumesCmd)
          && !(cmdObj instanceof ListUsersCmd)
          && !(cmdObj instanceof ListAccountsCmd)
          && !(cmdObj instanceof ListStoragePoolsCmd)) {
        buildAsyncListResponse((BaseListCmd) cmdObj, caller);
      }

      SerializationContext.current().setUuidTranslation(true);
      return ApiResponseSerializer.toSerializedString(
          (ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType());
    }
  }