protected void driveAuthTest(final short type) {

    // Prepare
    final BaseCmd cmd = new FakeCmdWithRoleAdmin();
    final Account account = mock(Account.class);
    ((FakeCmdWithRoleAdmin) cmd).account = account;
    when(account.getType()).thenReturn(type);
    User user =
        new UserVO(
            1,
            "testuser",
            "password",
            "firstname",
            "lastName",
            "email",
            "timezone",
            UUID.randomUUID().toString());
    CallContext.register(user, account);

    final Map<String, String> params = new HashMap<String, String>();
    params.put(ApiConstants.COMMAND, "");
    params.put("addedParam", "");
    params.put("paramWithRole", "");

    // Execute
    try {
      driveTest(cmd, params);
    } finally {
      CallContext.unregister();
    }
  }
  @Override
  public long getEntityOwnerId() {

    Volume volume = _entityMgr.findById(Volume.class, getVolumeId());
    if (volume == null) {
      throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId);
    }

    Account account = _accountService.getAccount(volume.getAccountId());
    // Can create templates for enabled projects/accounts only
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
      Project project = _projectService.findByProjectAccountId(volume.getAccountId());
      if (project.getState() != Project.State.Active) {
        throw new PermissionDeniedException(
            "Can't add resources to the project id="
                + project.getId()
                + " in state="
                + project.getState()
                + " as it's no longer active");
      }
    } else if (account.getState() == Account.State.disabled) {
      throw new PermissionDeniedException("The owner of template is disabled: " + account);
    }

    return volume.getAccountId();
  }
  @Override
  public long getEntityOwnerId() {
    Account account = UserContext.current().getCaller();
    if ((account == null) || isAdmin(account.getType())) {
      if ((domainId != null) && (accountName != null)) {
        Account userAccount = _responseGenerator.findAccountByNameDomain(accountName, domainId);
        if (userAccount != null) {
          return userAccount.getId();
        } else {
          throw new InvalidParameterValueException(
              "Unable to find account by name " + accountName + " in domain " + domainId);
        }
      }
    }

    return account.getId();
  }
  private Long accountAndUserValidation(
      Account account, Long userId, UserVmVO vmInstanceCheck, VMTemplateVO template, String msg)
      throws PermissionDeniedException {

    if (account != null) {
      if (!isAdmin(account.getType())) {
        if ((vmInstanceCheck != null) && (account.getId() != vmInstanceCheck.getAccountId())) {
          throw new PermissionDeniedException(msg + ". Permission denied.");
        }

        if ((template != null)
            && (!template.isPublicTemplate()
                && (account.getId() != template.getAccountId())
                && (template.getTemplateType() != TemplateType.PERHOST))) {
          throw new PermissionDeniedException(msg + ". Permission denied.");
        }

      } else {
        if ((vmInstanceCheck != null)
            && !_domainDao.isChildDomain(account.getDomainId(), vmInstanceCheck.getDomainId())) {
          throw new PermissionDeniedException(msg + ". Permission denied.");
        }
        // FIXME: if template/ISO owner is null we probably need to
        // throw some kind of exception

        if (template != null) {
          Account templateOwner = _accountDao.findById(template.getAccountId());
          if ((templateOwner != null)
              && !_domainDao.isChildDomain(account.getDomainId(), templateOwner.getDomainId())) {
            throw new PermissionDeniedException(msg + ". Permission denied.");
          }
        }
      }
    }
    // If command is executed via 8096 port, set userId to the id of System
    // account (1)
    if (userId == null) {
      userId = new Long(1);
    }

    return userId;
  }
  protected boolean revokeFirewallRule(long ruleId, boolean apply, Account caller, long userId) {

    FirewallRuleVO rule = _firewallDao.findById(ruleId);
    if (rule == null || rule.getPurpose() != Purpose.Firewall) {
      throw new InvalidParameterValueException(
          "Unable to find " + ruleId + " having purpose " + Purpose.Firewall);
    }

    if (rule.getType() == FirewallRuleType.System
        && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
      throw new InvalidParameterValueException(
          "Only root admin can delete the system wide firewall rule");
    }

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

    revokeRule(rule, caller, userId, false);

    boolean success = false;
    Long networkId = rule.getNetworkId();

    if (apply) {
      // ingress firewall rule
      if (rule.getSourceIpAddressId() != null) {
        // feteches ingress firewall, ingress firewall rules associated with the ip
        List<FirewallRuleVO> rules =
            _firewallDao.listByIpAndPurpose(rule.getSourceIpAddressId(), Purpose.Firewall);
        return applyFirewallRules(rules, false, caller);
        // egress firewall rule
      } else if (networkId != null) {
        List<FirewallRuleVO> rules =
            _firewallDao.listByNetworkPurposeTrafficType(
                rule.getNetworkId(), Purpose.Firewall, FirewallRule.TrafficType.Egress);
        return applyFirewallRules(rules, false, caller);
      }
    } else {
      success = true;
    }

    return success;
  }
Example #6
0
  @SuppressWarnings("unchecked")
  private void buildAsyncListResponse(BaseListCmd command, Account account) {
    List<ResponseObject> responses = ((ListResponse) command.getResponseObject()).getResponses();
    if (responses != null && responses.size() > 0) {
      List<? extends AsyncJob> jobs = null;

      // list all jobs for ROOT admin
      if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
        jobs = _asyncMgr.findInstancePendingAsyncJobs(command.getInstanceType().toString(), null);
      } else {
        jobs =
            _asyncMgr.findInstancePendingAsyncJobs(
                command.getInstanceType().toString(), account.getId());
      }

      if (jobs.size() == 0) {
        return;
      }

      Map<String, AsyncJob> objectJobMap = new HashMap<String, AsyncJob>();
      for (AsyncJob job : jobs) {
        if (job.getInstanceId() == null) {
          continue;
        }
        String instanceUuid = ApiDBUtils.findJobInstanceUuid(job);
        objectJobMap.put(instanceUuid, job);
      }

      for (ResponseObject response : responses) {
        if (response.getObjectId() != null && objectJobMap.containsKey(response.getObjectId())) {
          AsyncJob job = objectJobMap.get(response.getObjectId());
          response.setJobId(job.getUuid());
          response.setJobStatus(job.getStatus().ordinal());
        }
      }
    }
  }
Example #7
0
  @Override
  public void loginUser(
      HttpSession session,
      String username,
      String password,
      Long domainId,
      String domainPath,
      String loginIpAddress,
      Map<String, Object[]> requestParameters)
      throws CloudAuthenticationException {
    // We will always use domainId first. If that does not exist, we will use domain name. If THAT
    // doesn't exist
    // we will default to ROOT
    if (domainId == null) {
      if (domainPath == null || domainPath.trim().length() == 0) {
        domainId = Domain.ROOT_DOMAIN;
      } else {
        Domain domainObj = _domainMgr.findDomainByPath(domainPath);
        if (domainObj != null) {
          domainId = domainObj.getId();
        } else { // if an unknown path is passed in, fail the login call
          throw new CloudAuthenticationException(
              "Unable to find the domain from the path " + domainPath);
        }
      }
    }

    UserAccount userAcct =
        _accountMgr.authenticateUser(
            username, password, domainId, loginIpAddress, requestParameters);
    if (userAcct != null) {
      String timezone = userAcct.getTimezone();
      float offsetInHrs = 0f;
      if (timezone != null) {
        TimeZone t = TimeZone.getTimeZone(timezone);
        s_logger.info("Current user logged in under " + timezone + " timezone");

        java.util.Date date = new java.util.Date();
        long longDate = date.getTime();
        float offsetInMs = (t.getOffset(longDate));
        offsetInHrs = offsetInMs / (1000 * 60 * 60);
        s_logger.info("Timezone offset from UTC is: " + offsetInHrs);
      }

      Account account = _accountMgr.getAccount(userAcct.getAccountId());

      // set the userId and account object for everyone
      session.setAttribute("userid", userAcct.getId());
      UserVO user = (UserVO) _accountMgr.getActiveUser(userAcct.getId());
      if (user.getUuid() != null) {
        session.setAttribute("user_UUID", user.getUuid());
      }

      session.setAttribute("username", userAcct.getUsername());
      session.setAttribute("firstname", userAcct.getFirstname());
      session.setAttribute("lastname", userAcct.getLastname());
      session.setAttribute("accountobj", account);
      session.setAttribute("account", account.getAccountName());

      session.setAttribute("domainid", account.getDomainId());
      DomainVO domain = (DomainVO) _domainMgr.getDomain(account.getDomainId());
      if (domain.getUuid() != null) {
        session.setAttribute("domain_UUID", domain.getUuid());
      }

      session.setAttribute("type", Short.valueOf(account.getType()).toString());
      session.setAttribute("registrationtoken", userAcct.getRegistrationToken());
      session.setAttribute("registered", new Boolean(userAcct.isRegistered()).toString());

      if (timezone != null) {
        session.setAttribute("timezone", timezone);
        session.setAttribute("timezoneoffset", Float.valueOf(offsetInHrs).toString());
      }

      // (bug 5483) generate a session key that the user must submit on every request to prevent
      // CSRF, add that
      // to the login response so that session-based authenticators know to send the key back
      SecureRandom sesssionKeyRandom = new SecureRandom();
      byte sessionKeyBytes[] = new byte[20];
      sesssionKeyRandom.nextBytes(sessionKeyBytes);
      String sessionKey = Base64.encodeBase64String(sessionKeyBytes);
      session.setAttribute("sessionkey", sessionKey);

      return;
    }
    throw new CloudAuthenticationException(
        "Failed to authenticate user "
            + username
            + " in domain "
            + domainId
            + "; please provide valid credentials");
  }
  @Override
  public VolumeResponse newVolumeResponse(VolumeJoinVO volume) {
    Account caller = UserContext.current().getCaller();

    VolumeResponse volResponse = new VolumeResponse();
    volResponse.setId(volume.getUuid());

    if (volume.getName() != null) {
      volResponse.setName(volume.getName());
    } else {
      volResponse.setName("");
    }

    volResponse.setZoneId(volume.getDataCenterUuid());
    volResponse.setZoneName(volume.getDataCenterName());

    volResponse.setVolumeType(volume.getVolumeType().toString());
    volResponse.setDeviceId(volume.getDeviceId());

    long instanceId = volume.getVmId();
    if (instanceId > 0 && volume.getState() != Volume.State.Destroy) {
      volResponse.setVirtualMachineId(volume.getVmUuid());
      volResponse.setVirtualMachineName(volume.getVmName());
      volResponse.setVirtualMachineState(volume.getVmState().toString());
      volResponse.setVirtualMachineDisplayName(volume.getVmDisplayName());
    }

    // Show the virtual size of the volume
    volResponse.setSize(volume.getSize());

    volResponse.setCreated(volume.getCreated());
    volResponse.setState(volume.getState().toString());
    if (volume.getState() == Volume.State.UploadOp) {
      // com.cloud.storage.VolumeHostVO volumeHostRef =
      // ApiDBUtils.findVolumeHostRef(volume.getId(),
      // volume.getDataCenterId());
      volResponse.setSize(volume.getVolumeHostSize());
      volResponse.setCreated(volume.getVolumeHostCreated());

      if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN
          || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)
        volResponse.setHypervisor(
            ApiDBUtils.getHypervisorTypeFromFormat(volume.getFormat()).toString());
      if (volume.getDownloadState() != Status.DOWNLOADED) {
        String volumeStatus = "Processing";
        if (volume.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) {
          if (volume.getDownloadPercent() == 100) {
            volumeStatus = "Checking Volume";
          } else {
            volumeStatus = volume.getDownloadPercent() + "% Uploaded";
          }
          volResponse.setState("Uploading");
        } else {
          volumeStatus = volume.getErrorString();
          if (volume.getDownloadState() == VMTemplateHostVO.Status.NOT_DOWNLOADED) {
            volResponse.setState("UploadNotStarted");
          } else {
            volResponse.setState("UploadError");
          }
        }
        volResponse.setStatus(volumeStatus);
      } else if (volume.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) {
        volResponse.setStatus("Upload Complete");
        volResponse.setState("Uploaded");
      } else {
        volResponse.setStatus("Successfully Installed");
      }
    }

    // populate owner.
    ApiResponseHelper.populateOwner(volResponse, volume);

    // DiskOfferingVO diskOffering =
    // ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId());
    if (volume.getDiskOfferingId() > 0) {
      if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
        volResponse.setServiceOfferingId(volume.getDiskOfferingUuid());
      } else {
        volResponse.setDiskOfferingId(volume.getDiskOfferingUuid());
      }

      if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
        volResponse.setServiceOfferingName(volume.getDiskOfferingName());
        volResponse.setServiceOfferingDisplayText(volume.getDiskOfferingDisplayText());
      } else {
        volResponse.setDiskOfferingName(volume.getDiskOfferingName());
        volResponse.setDiskOfferingDisplayText(volume.getDiskOfferingDisplayText());
      }
      volResponse.setStorageType(
          volume.isUseLocalStorage()
              ? ServiceOffering.StorageType.local.toString()
              : ServiceOffering.StorageType.shared.toString());
    }
    Long poolId = volume.getPoolId();
    String poolName = (poolId == null) ? "none" : volume.getPoolName();
    volResponse.setStoragePoolName(poolName);

    // return hypervisor for ROOT and Resource domain only
    if ((caller.getType() == Account.ACCOUNT_TYPE_ADMIN
            || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)
        && volume.getState() != Volume.State.UploadOp
        && volume.getHypervisorType() != null) {
      volResponse.setHypervisor(volume.getHypervisorType().toString());
    }

    volResponse.setAttached(volume.getAttached());
    volResponse.setDestroyed(volume.getState() == Volume.State.Destroy);
    boolean isExtractable = true;
    if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont
      // have any
      // template
      // dependence.
      if (volume.getTemplateId() > 0) { // For ISO based volumes template
        // = null and we allow extraction
        // of all ISO based volumes
        isExtractable =
            volume.isExtractable() && volume.getTemplateType() != Storage.TemplateType.SYSTEM;
      }
    }

    // update tag information
    long tag_id = volume.getTagId();
    if (tag_id > 0) {
      ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id);
      if (vtag != null) {
        volResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false));
      }
    }

    volResponse.setExtractable(isExtractable);

    // set async job
    volResponse.setJobId(volume.getJobUuid());
    volResponse.setJobStatus(volume.getJobStatus());

    volResponse.setObjectName("volume");
    return volResponse;
  }
  @Override
  public List<SecurityGroupRulesVO> searchForSecurityGroupRules(ListSecurityGroupsCmd cmd)
      throws PermissionDeniedException, InvalidParameterValueException {
    Account caller = UserContext.current().getCaller();
    Long domainId = cmd.getDomainId();
    String accountName = cmd.getAccountName();
    Long instanceId = cmd.getVirtualMachineId();
    String securityGroup = cmd.getSecurityGroupName();
    Long id = cmd.getId();
    Long accountId = null;

    if (instanceId != null) {
      UserVmVO userVM = _userVMDao.findById(instanceId);
      if (userVM == null) {
        throw new InvalidParameterValueException(
            "Unable to list network groups for virtual machine instance "
                + instanceId
                + "; instance not found.");
      }
      _accountMgr.checkAccess(caller, null, userVM);
      return listSecurityGroupRulesByVM(instanceId.longValue());
    }

    if (_accountMgr.isAdmin(caller.getType())) {
      if (domainId != null) {
        Domain domain = _domainMgr.getDomain(domainId);
        if (domain == null) {
          throw new InvalidParameterValueException("Unable to find domain by id " + domainId);
        }
        _accountMgr.checkAccess(caller, domain);
        if (accountName != null) {
          Account account = _accountMgr.getActiveAccountByName(accountName, domainId);
          if (account == null) {
            throw new InvalidParameterValueException(
                "Unable to find account " + accountName + " in domain " + domainId);
          }
          _accountMgr.checkAccess(caller, null, account);
          accountId = account.getId();
        }
      }
    } else {
      // regular user can see only his own security groups
      accountId = caller.getId();
    }

    List<SecurityGroupRulesVO> securityRulesList = new ArrayList<SecurityGroupRulesVO>();
    Filter searchFilter =
        new Filter(SecurityGroupVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    Object keyword = cmd.getKeyword();

    SearchBuilder<SecurityGroupVO> sb = _securityGroupDao.createSearchBuilder();
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
    sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);

    // only do a recursive domain search if the search is not limited by account or instance
    if ((accountId == null)
        && (instanceId == null)
        && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
      SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
      domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
      sb.join(
          "domainSearch",
          domainSearch,
          sb.entity().getDomainId(),
          domainSearch.entity().getId(),
          JoinBuilder.JoinType.INNER);
    }

    SearchCriteria<SecurityGroupVO> sc = sb.create();

    if (id != null) {
      sc.setParameters("id", id);
    }

    if (securityGroup != null) {
      sc.setParameters("name", securityGroup);
    }

    if (accountId != null) {
      sc.setParameters("accountId", accountId);
    }

    // only do a recursive domain search if the search is not limited by account or instance
    if ((accountId == null)
        && (instanceId == null)
        && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN)) {
      DomainVO domain = _domainDao.findById(caller.getDomainId());
      sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%");
    }

    if (keyword != null) {
      SearchCriteria<SecurityGroupRulesVO> ssc = _securityGroupRulesDao.createSearchCriteria();
      ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
      ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
      sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }

    List<SecurityGroupVO> securityGroups = _securityGroupDao.search(sc, searchFilter);
    for (SecurityGroupVO group : securityGroups) {
      securityRulesList.addAll(_securityGroupRulesDao.listSecurityRulesByGroupId(group.getId()));
    }

    return securityRulesList;
  }
  @Override
  public Set<Pair<Long, Long>> searchTemplates(
      String name,
      String keyword,
      TemplateFilter templateFilter,
      boolean isIso,
      List<HypervisorType> hypers,
      Boolean bootable,
      DomainVO domain,
      Long pageSize,
      Long startIndex,
      Long zoneId,
      HypervisorType hyperType,
      boolean onlyReady,
      boolean showDomr,
      List<Account> permittedAccounts,
      Account caller,
      ListProjectResourcesCriteria listProjectResourcesCriteria) {
    StringBuilder builder = new StringBuilder();
    if (!permittedAccounts.isEmpty()) {
      for (Account permittedAccount : permittedAccounts) {
        builder.append(permittedAccount.getAccountId() + ",");
      }
    }

    String permittedAccountsStr = builder.toString();

    if (permittedAccountsStr.length() > 0) {
      // chop the "," off
      permittedAccountsStr = permittedAccountsStr.substring(0, permittedAccountsStr.length() - 1);
    }

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

    /* Use LinkedHashSet here to guarantee iteration order */
    Set<Pair<Long, Long>> templateZonePairList = new LinkedHashSet<Pair<Long, Long>>();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    StringBuilder relatedDomainIds = new StringBuilder();
    String sql = SELECT_TEMPLATE_ZONE_REF;
    String groupByClause = "";
    try {
      // short accountType;
      // String accountId = null;
      String guestOSJoin = "";
      StringBuilder templateHostRefJoin = new StringBuilder();
      String dataCenterJoin = "";

      if (isIso && !hyperType.equals(HypervisorType.None)) {
        guestOSJoin =
            " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) ";
      }
      if (onlyReady) {
        templateHostRefJoin.append(
            " INNER JOIN  template_host_ref thr on (t.id = thr.template_id) INNER JOIN host h on (thr.host_id = h.id)");
        sql = SELECT_TEMPLATE_HOST_REF;
        groupByClause = " GROUP BY t.id, h.data_center_id ";
      }
      if ((templateFilter == TemplateFilter.featured)
          || (templateFilter == TemplateFilter.community)) {
        dataCenterJoin = " INNER JOIN data_center dc on (h.data_center_id = dc.id)";
      }

      sql += guestOSJoin + templateHostRefJoin + dataCenterJoin;
      String whereClause = "";

      // All joins have to be made before we start setting the condition settings
      if ((listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources
              || (!permittedAccounts.isEmpty()
                  && !(templateFilter == TemplateFilter.community
                      || templateFilter == TemplateFilter.featured)))
          && !(caller.getType() != Account.ACCOUNT_TYPE_NORMAL
              && templateFilter == TemplateFilter.all)) {
        whereClause += " INNER JOIN account a on (t.account_id = a.id)";
        if ((templateFilter == TemplateFilter.self
                || templateFilter == TemplateFilter.selfexecutable)
            && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN
                || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
          whereClause +=
              " INNER JOIN domain d on (a.domain_id = d.id) WHERE d.path LIKE '"
                  + domain.getPath()
                  + "%'";
          if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
            whereClause += " AND a.type != " + Account.ACCOUNT_TYPE_PROJECT;
          }
        } else if (listProjectResourcesCriteria
            == ListProjectResourcesCriteria.SkipProjectResources) {
          whereClause += " WHERE a.type != " + Account.ACCOUNT_TYPE_PROJECT;
        }
      }

      if (!permittedAccounts.isEmpty()) {
        for (Account account : permittedAccounts) {
          // accountType = account.getType();
          // accountId = Long.toString(account.getId());
          DomainVO accountDomain = _domainDao.findById(account.getDomainId());

          // get all parent domain ID's all the way till root domain
          DomainVO domainTreeNode = accountDomain;
          while (true) {
            relatedDomainIds.append(domainTreeNode.getId());
            relatedDomainIds.append(",");
            if (domainTreeNode.getParent() != null) {
              domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
            } else {
              break;
            }
          }

          // get all child domain ID's
          if (isAdmin(account.getType())) {
            List<DomainVO> allChildDomains =
                _domainDao.findAllChildren(accountDomain.getPath(), accountDomain.getId());
            for (DomainVO childDomain : allChildDomains) {
              relatedDomainIds.append(childDomain.getId());
              relatedDomainIds.append(",");
            }
          }
          relatedDomainIds.setLength(relatedDomainIds.length() - 1);
        }
      }

      String attr = " AND ";
      if (whereClause.endsWith(" WHERE ")) {
        attr += " WHERE ";
      }

      if (!isIso) {
        if (hypers.isEmpty()) {
          return templateZonePairList;
        } else {
          StringBuilder relatedHypers = new StringBuilder();
          for (HypervisorType hyper : hypers) {
            relatedHypers.append("'");
            relatedHypers.append(hyper.toString());
            relatedHypers.append("'");
            relatedHypers.append(",");
          }
          relatedHypers.setLength(relatedHypers.length() - 1);
          whereClause += attr + " t.hypervisor_type IN (" + relatedHypers + ")";
        }
      }

      if (!permittedAccounts.isEmpty()
          && !(templateFilter == TemplateFilter.featured
              || templateFilter == TemplateFilter.community)
          && !isAdmin(caller.getType())) {
        whereClause += attr + "t.account_id IN (" + permittedAccountsStr + ")";
      }

      if (templateFilter == TemplateFilter.featured) {
        whereClause += attr + "t.public = 1 AND t.featured = 1";
        if (!permittedAccounts.isEmpty()) {
          whereClause +=
              attr + "(dc.domain_id IN (" + relatedDomainIds + ") OR dc.domain_id is NULL)";
        }
      } else if (templateFilter == TemplateFilter.self
          || templateFilter == TemplateFilter.selfexecutable) {
        whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")";
      } else if (templateFilter == TemplateFilter.sharedexecutable) {
        whereClause +=
            " LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE"
                + " (t.account_id IN ("
                + permittedAccountsStr
                + ") OR"
                + " lp.account_id IN ("
                + permittedAccountsStr
                + "))";
      } else if (templateFilter == TemplateFilter.executable && !permittedAccounts.isEmpty()) {
        whereClause += attr + "(t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))";
      } else if (templateFilter == TemplateFilter.community) {
        whereClause += attr + "t.public = 1 AND t.featured = 0";
        if (!permittedAccounts.isEmpty()) {
          whereClause +=
              attr + "(dc.domain_id IN (" + relatedDomainIds + ") OR dc.domain_id is NULL)";
        }
      } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN && !isIso) {
        return templateZonePairList;
      }

      if (whereClause.equals("")) {
        whereClause += " WHERE ";
      } else if (!whereClause.equals(" WHERE ")) {
        whereClause += " AND ";
      }

      sql +=
          whereClause
              + getExtrasWhere(
                  templateFilter,
                  name,
                  keyword,
                  isIso,
                  bootable,
                  hyperType,
                  zoneId,
                  onlyReady,
                  showDomr)
              + groupByClause
              + getOrderByLimit(pageSize, startIndex);

      pstmt = txn.prepareStatement(sql);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        Pair<Long, Long> templateZonePair = new Pair<Long, Long>(rs.getLong(1), rs.getLong(2));
        templateZonePairList.add(templateZonePair);
      }

      // for now, defaulting pageSize to a large val if null; may need to revisit post 2.2RC2
      if (isIso
          && templateZonePairList.size() < (pageSize != null ? pageSize : 500)
          && templateFilter != TemplateFilter.community
          && !(templateFilter == TemplateFilter.self
              && !BaseCmd.isRootAdmin(
                  caller.getType()))) { // evaluates to true If root admin and filter=self
        List<VMTemplateVO> publicIsos = publicIsoSearch(bootable, false);
        for (int i = 0; i < publicIsos.size(); i++) {
          if (keyword != null && publicIsos.get(i).getName().contains(keyword)) {
            templateZonePairList.add(new Pair<Long, Long>(publicIsos.get(i).getId(), null));
            continue;
          } else if (name != null && publicIsos.get(i).getName().contains(name)) {
            templateZonePairList.add(new Pair<Long, Long>(publicIsos.get(i).getId(), null));
            continue;
          } else if (keyword == null && name == null) {
            templateZonePairList.add(new Pair<Long, Long>(publicIsos.get(i).getId(), null));
          }
        }
      }
    } catch (Exception e) {
      s_logger.warn("Error listing templates", e);
    } finally {
      try {
        if (rs != null) {
          rs.close();
        }
        if (pstmt != null) {
          pstmt.close();
        }
        txn.commit();
      } catch (SQLException sqle) {
        s_logger.warn("Error in cleaning up", sqle);
      }
    }

    return templateZonePairList;
  }
  @Override
  public Set<Pair<Long, Long>> searchSwiftTemplates(
      String name,
      String keyword,
      TemplateFilter templateFilter,
      boolean isIso,
      List<HypervisorType> hypers,
      Boolean bootable,
      DomainVO domain,
      Long pageSize,
      Long startIndex,
      Long zoneId,
      HypervisorType hyperType,
      boolean onlyReady,
      boolean showDomr,
      List<Account> permittedAccounts,
      Account caller) {

    StringBuilder builder = new StringBuilder();
    if (!permittedAccounts.isEmpty()) {
      for (Account permittedAccount : permittedAccounts) {
        builder.append(permittedAccount.getAccountId() + ",");
      }
    }

    String permittedAccountsStr = builder.toString();

    if (permittedAccountsStr.length() > 0) {
      // chop the "," off
      permittedAccountsStr = permittedAccountsStr.substring(0, permittedAccountsStr.length() - 1);
    }

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

    Set<Pair<Long, Long>> templateZonePairList = new HashSet<Pair<Long, Long>>();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    String sql = SELECT_TEMPLATE_SWIFT_REF;
    try {
      String joinClause = "";
      String whereClause = " WHERE t.removed IS NULL";

      if (isIso) {
        whereClause += " AND t.format = 'ISO'";
        if (!hyperType.equals(HypervisorType.None)) {
          joinClause =
              " INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) ";
          whereClause += " AND goh.hypervisor_type = '" + hyperType.toString() + "'";
        }
      } else {
        whereClause += " AND t.format <> 'ISO'";
        if (hypers.isEmpty()) {
          return templateZonePairList;
        } else {
          StringBuilder relatedHypers = new StringBuilder();
          for (HypervisorType hyper : hypers) {
            relatedHypers.append("'");
            relatedHypers.append(hyper.toString());
            relatedHypers.append("'");
            relatedHypers.append(",");
          }
          relatedHypers.setLength(relatedHypers.length() - 1);
          whereClause += " AND t.hypervisor_type IN (" + relatedHypers + ")";
        }
      }
      joinClause += " INNER JOIN  template_swift_ref tsr on (t.id = tsr.template_id)";
      if (keyword != null) {
        whereClause += " AND t.name LIKE \"%" + keyword + "%\"";
      } else if (name != null) {
        whereClause += " AND t.name LIKE \"%" + name + "%\"";
      }

      if (bootable != null) {
        whereClause += " AND t.bootable = " + bootable;
      }

      if (!showDomr) {
        whereClause += " AND t.type != '" + Storage.TemplateType.SYSTEM.toString() + "'";
      }

      if (templateFilter == TemplateFilter.featured) {
        whereClause += " AND t.public = 1 AND t.featured = 1";
      } else if ((templateFilter == TemplateFilter.self
              || templateFilter == TemplateFilter.selfexecutable)
          && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
        if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN
            || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
          joinClause +=
              " INNER JOIN account a on (t.account_id = a.id) INNER JOIN domain d on (a.domain_id = d.id)";
          whereClause += "  AND d.path LIKE '" + domain.getPath() + "%'";
        } else {
          whereClause += " AND t.account_id IN (" + permittedAccountsStr + ")";
        }
      } else if (templateFilter == TemplateFilter.sharedexecutable
          && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
        if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) {
          joinClause +=
              " LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE"
                  + " (t.account_id IN ("
                  + permittedAccountsStr
                  + ") OR"
                  + " lp.account_id IN ("
                  + permittedAccountsStr
                  + "))";
        } else {
          joinClause += " INNER JOIN account a on (t.account_id = a.id) ";
        }
      } else if (templateFilter == TemplateFilter.executable && !permittedAccounts.isEmpty()) {
        whereClause += " AND (t.public = 1 OR t.account_id IN (" + permittedAccountsStr + "))";
      } else if (templateFilter == TemplateFilter.community) {
        whereClause += " AND t.public = 1 AND t.featured = 0";
      } else if (templateFilter == TemplateFilter.all
          && caller.getType() == Account.ACCOUNT_TYPE_ADMIN) {
      } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
        return templateZonePairList;
      }

      sql += joinClause + whereClause + getOrderByLimit(pageSize, startIndex);
      pstmt = txn.prepareStatement(sql);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        Pair<Long, Long> templateZonePair = new Pair<Long, Long>(rs.getLong(1), -1L);
        templateZonePairList.add(templateZonePair);
      }

    } catch (Exception e) {
      s_logger.warn("Error listing templates", e);
    } finally {
      try {
        if (rs != null) {
          rs.close();
        }
        if (pstmt != null) {
          pstmt.close();
        }
        txn.commit();
      } catch (SQLException sqle) {
        s_logger.warn("Error in cleaning up", sqle);
      }
    }

    return templateZonePairList;
  }
  @Override
  public List<LoadBalancerVO> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) {
    Account caller = UserContext.current().getCaller();
    Long ipId = cmd.getPublicIpId();
    Long zoneId = cmd.getZoneId();
    String path = null;

    Pair<String, Long> accountDomainPair =
        _accountMgr.finalizeAccountDomainForList(caller, cmd.getAccountName(), cmd.getDomainId());
    String accountName = accountDomainPair.first();
    Long domainId = accountDomainPair.second();

    if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN
        || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
      Domain domain = _domainMgr.getDomain(caller.getDomainId());
      path = domain.getPath();
    }

    Filter searchFilter =
        new Filter(LoadBalancerVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());

    Object id = cmd.getId();
    Object name = cmd.getLoadBalancerRuleName();
    Object keyword = cmd.getKeyword();
    Object instanceId = cmd.getVirtualMachineId();

    SearchBuilder<LoadBalancerVO> sb = _lbDao.createSearchBuilder();
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
    sb.and("sourceIpAddress", sb.entity().getSourceIpAddressId(), SearchCriteria.Op.EQ);
    sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
    sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);

    if (instanceId != null) {
      SearchBuilder<LoadBalancerVMMapVO> lbVMSearch = _lb2VmMapDao.createSearchBuilder();
      lbVMSearch.and("instanceId", lbVMSearch.entity().getInstanceId(), SearchCriteria.Op.EQ);
      sb.join(
          "lbVMSearch",
          lbVMSearch,
          sb.entity().getId(),
          lbVMSearch.entity().getLoadBalancerId(),
          JoinBuilder.JoinType.INNER);
    }

    if (path != null) {
      // for domain admin we should show only subdomains information
      SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
      domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
      sb.join(
          "domainSearch",
          domainSearch,
          sb.entity().getDomainId(),
          domainSearch.entity().getId(),
          JoinBuilder.JoinType.INNER);
    }

    if (zoneId != null) {
      SearchBuilder<IPAddressVO> ipSearch = _ipAddressDao.createSearchBuilder();
      ipSearch.and("zoneId", ipSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
      sb.join(
          "ipSearch",
          ipSearch,
          sb.entity().getSourceIpAddressId(),
          ipSearch.entity().getId(),
          JoinBuilder.JoinType.INNER);
    }

    SearchCriteria<LoadBalancerVO> sc = sb.create();
    if (keyword != null) {
      SearchCriteria<LoadBalancerVO> ssc = _lbDao.createSearchCriteria();
      ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
      ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");

      sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }

    if (name != null) {
      sc.setParameters("name", "%" + name + "%");
    }

    if (id != null) {
      sc.setParameters("id", id);
    }

    if (ipId != null) {
      sc.setParameters("sourceIpAddress", ipId);
    }

    if (instanceId != null) {
      sc.setJoinParameters("lbVMSearch", "instanceId", instanceId);
    }

    if (domainId != null) {
      sc.setParameters("domainId", domainId);
      if (accountName != null) {
        Account account = _accountMgr.getActiveAccountByName(accountName, domainId);
        sc.setParameters("accountId", account.getId());
      }
    }

    if (path != null) {
      sc.setJoinParameters("domainSearch", "path", path + "%");
    }

    if (zoneId != null) {
      sc.setJoinParameters("ipSearch", "zoneId", zoneId);
    }

    return _lbDao.search(sc, searchFilter);
  }
  public TemplateProfile prepare(
      boolean isIso,
      Long userId,
      String name,
      String displayText,
      Integer bits,
      Boolean passwordEnabled,
      Boolean requiresHVM,
      String url,
      Boolean isPublic,
      Boolean featured,
      Boolean isExtractable,
      String format,
      Long guestOSId,
      Long zoneId,
      HypervisorType hypervisorType,
      String chksum,
      Boolean bootable,
      String templateTag,
      Account templateOwner,
      Map details)
      throws ResourceAllocationException {
    // Long accountId = null;
    // parameters verification

    if (isPublic == null) {
      isPublic = Boolean.FALSE;
    }

    if (zoneId.longValue() == -1) {
      zoneId = null;
    }

    if (isIso) {
      if (bootable == null) {
        bootable = Boolean.TRUE;
      }
      GuestOS noneGuestOs = ApiDBUtils.findGuestOSByDisplayName(ApiConstants.ISO_GUEST_OS_NONE);
      if ((guestOSId == null || guestOSId == noneGuestOs.getId()) && bootable == true) {
        throw new InvalidParameterValueException("Please pass a valid GuestOS Id");
      }
      if (bootable == false) {
        guestOSId = noneGuestOs.getId(); // Guest os id of None.
      }
    } else {
      if (bits == null) {
        bits = Integer.valueOf(64);
      }
      if (passwordEnabled == null) {
        passwordEnabled = false;
      }
      if (requiresHVM == null) {
        requiresHVM = true;
      }
    }

    if (isExtractable == null) {
      isExtractable = Boolean.FALSE;
    }

    boolean isAdmin =
        _accountDao.findById(templateOwner.getId()).getType() == Account.ACCOUNT_TYPE_ADMIN;

    if (!isAdmin && zoneId == null) {
      throw new InvalidParameterValueException("Please specify a valid zone Id.");
    }

    if (url.toLowerCase().contains("file://")) {
      throw new InvalidParameterValueException("File:// type urls are currently unsupported");
    }

    boolean allowPublicUserTemplates =
        Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates"));
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
      throw new InvalidParameterValueException("Only private templates/ISO can be created.");
    }

    if (!isAdmin || featured == null) {
      featured = Boolean.FALSE;
    }

    // If command is executed via 8096 port, set userId to the id of System
    // account (1)
    if (userId == null) {
      userId = Long.valueOf(1);
    }

    ImageFormat imgfmt = ImageFormat.valueOf(format.toUpperCase());
    if (imgfmt == null) {
      throw new IllegalArgumentException(
          "Image format is incorrect "
              + format
              + ". Supported formats are "
              + EnumUtils.listValues(ImageFormat.values()));
    }

    // Check that the resource limit for templates/ISOs won't be exceeded
    UserVO user = _userDao.findById(userId);
    if (user == null) {
      throw new IllegalArgumentException("Unable to find user with id " + userId);
    }

    _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);

    if (templateOwner.getType() != Account.ACCOUNT_TYPE_ADMIN && zoneId == null) {
      throw new IllegalArgumentException("Only admins can create templates in all zones");
    }

    // If a zoneId is specified, make sure it is valid
    if (zoneId != null) {
      DataCenterVO zone = _dcDao.findById(zoneId);
      if (zone == null) {
        throw new IllegalArgumentException("Please specify a valid zone.");
      }
      Account caller = UserContext.current().getCaller();
      if (Grouping.AllocationState.Disabled == zone.getAllocationState()
          && !_accountMgr.isRootAdmin(caller.getType())) {
        throw new PermissionDeniedException(
            "Cannot perform this operation, Zone is currently disabled: " + zoneId);
      }
    }

    List<VMTemplateVO> systemvmTmplts = _tmpltDao.listAllSystemVMTemplates();
    for (VMTemplateVO template : systemvmTmplts) {
      if (template.getName().equalsIgnoreCase(name)
          || template.getDisplayText().equalsIgnoreCase(displayText)) {
        throw new IllegalArgumentException("Cannot use reserved names for templates");
      }
    }

    Long id = _tmpltDao.getNextInSequence(Long.class, "id");
    UserContext.current().setEventDetails("Id: " + id + " name: " + name);
    return new TemplateProfile(
        id,
        userId,
        name,
        displayText,
        bits,
        passwordEnabled,
        requiresHVM,
        url,
        isPublic,
        featured,
        isExtractable,
        imgfmt,
        guestOSId,
        zoneId,
        hypervisorType,
        templateOwner.getAccountName(),
        templateOwner.getDomainId(),
        templateOwner.getAccountId(),
        chksum,
        bootable,
        templateTag,
        details);
  }