Search in sources :

Example 51 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class SnapshotManagerImpl method listSnapshots.

@Override
public Pair<List<? extends Snapshot>, Integer> listSnapshots(final ListSnapshotsCmd cmd) {
    final Long volumeId = cmd.getVolumeId();
    final String name = cmd.getSnapshotName();
    final Long id = cmd.getId();
    final String keyword = cmd.getKeyword();
    final String snapshotTypeStr = cmd.getSnapshotType();
    final String intervalTypeStr = cmd.getIntervalType();
    final Map<String, String> tags = cmd.getTags();
    final Long zoneId = cmd.getZoneId();
    final Account caller = CallContext.current().getCallingAccount();
    final List<Long> permittedAccounts = new ArrayList<>();
    // Verify parameters
    if (volumeId != null) {
        final VolumeVO volume = this._volsDao.findById(volumeId);
        if (volume != null) {
            this._accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
        }
    }
    final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    this._accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    final Long domainId = domainIdRecursiveListProject.first();
    final Boolean isRecursive = domainIdRecursiveListProject.second();
    final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    final Filter searchFilter = new Filter(SnapshotVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchBuilder<SnapshotVO> sb = this._snapshotDao.createSearchBuilder();
    this._accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    // exclude those Destroyed snapshot, not showing on UI
    sb.and("statusNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
    sb.and("volumeId", sb.entity().getVolumeId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("snapshotTypeEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.IN);
    sb.and("snapshotTypeNEQ", sb.entity().getsnapshotType(), SearchCriteria.Op.NEQ);
    sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
    if (tags != null && !tags.isEmpty()) {
        final SearchBuilder<ResourceTagVO> tagSearch = this._resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    final SearchCriteria<SnapshotVO> sc = sb.create();
    this._accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sc.setParameters("statusNEQ", Snapshot.State.Destroyed);
    if (volumeId != null) {
        sc.setParameters("volumeId", volumeId);
    }
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Snapshot.toString());
        for (final String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (zoneId != null) {
        sc.setParameters("dataCenterId", zoneId);
    }
    if (name != null) {
        sc.setParameters("name", "%" + name + "%");
    }
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (keyword != null) {
        final SearchCriteria<SnapshotVO> ssc = this._snapshotDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (snapshotTypeStr != null) {
        final Type snapshotType = SnapshotVO.getSnapshotType(snapshotTypeStr);
        if (snapshotType == null) {
            throw new InvalidParameterValueException("Unsupported snapshot type " + snapshotTypeStr);
        }
        if (snapshotType == Type.RECURRING) {
            sc.setParameters("snapshotTypeEQ", Type.HOURLY.ordinal(), Type.DAILY.ordinal(), Type.WEEKLY.ordinal(), Type.MONTHLY.ordinal());
        } else {
            sc.setParameters("snapshotTypeEQ", snapshotType.ordinal());
        }
    } else if (intervalTypeStr != null && volumeId != null) {
        final Type type = SnapshotVO.getSnapshotType(intervalTypeStr);
        if (type == null) {
            throw new InvalidParameterValueException("Unsupported snapstho interval type " + intervalTypeStr);
        }
        sc.setParameters("snapshotTypeEQ", type.ordinal());
    } else {
        // Show only MANUAL and RECURRING snapshot types
        sc.setParameters("snapshotTypeNEQ", Snapshot.Type.TEMPLATE.ordinal());
    }
    final Pair<List<SnapshotVO>, Integer> result = this._snapshotDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.legacymodel.user.Account) Ternary(com.cloud.legacymodel.utils.Ternary) ArrayList(java.util.ArrayList) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) ResourceObjectType(com.cloud.server.ResourceTag.ResourceObjectType) ScopeType(com.cloud.storage.ScopeType) HypervisorType(com.cloud.model.enumeration.HypervisorType) Type(com.cloud.storage.Snapshot.Type) ResourceType(com.cloud.legacymodel.configuration.Resource.ResourceType) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.legacymodel.utils.Pair)

Example 52 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class DomainManagerImpl method searchForDomains.

@Override
public Pair<List<? extends Domain>, Integer> searchForDomains(final ListDomainsCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    Long domainId = cmd.getId();
    final boolean listAll = cmd.listAll();
    boolean isRecursive = false;
    if (domainId != null) {
        final Domain domain = getDomain(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist");
        }
        _accountMgr.checkAccess(caller, domain);
    } else {
        if (!_accountMgr.isRootAdmin(caller.getId())) {
            domainId = caller.getDomainId();
        }
        if (listAll) {
            isRecursive = true;
        }
    }
    final Filter searchFilter = new Filter(DomainVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final String domainName = cmd.getDomainName();
    final Integer level = cmd.getLevel();
    final Object keyword = cmd.getKeyword();
    final SearchBuilder<DomainVO> sb = _domainDao.createSearchBuilder();
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
    sb.and("level", sb.entity().getLevel(), SearchCriteria.Op.EQ);
    sb.and("path", sb.entity().getPath(), SearchCriteria.Op.LIKE);
    sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
    final SearchCriteria<DomainVO> sc = sb.create();
    if (keyword != null) {
        final SearchCriteria<DomainVO> ssc = _domainDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (domainName != null) {
        sc.setParameters("name", domainName);
    }
    if (level != null) {
        sc.setParameters("level", level);
    }
    if (domainId != null) {
        if (isRecursive) {
            sc.setParameters("path", getDomain(domainId).getPath() + "%");
        } else {
            sc.setParameters("id", domainId);
        }
    }
    // return only Active domains to the API
    sc.setParameters("state", Domain.State.Active);
    final Pair<List<DomainVO>, Integer> result = _domainDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.legacymodel.user.Account) DomainVO(com.cloud.domain.DomainVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) List(java.util.List) Domain(com.cloud.legacymodel.domain.Domain) Pair(com.cloud.legacymodel.utils.Pair)

Example 53 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class AccountManagerImplTest method testAuthenticateUser.

@Test
public void testAuthenticateUser() throws UnknownHostException {
    final Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> successAuthenticationPair = new Pair<>(true, null);
    final Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> failureAuthenticationPair = new Pair<>(false, UserAuthenticator.ActionOnFailedAuthentication.INCREMENT_INCORRECT_LOGIN_ATTEMPT_COUNT);
    final UserAccountVO userAccountVO = new UserAccountVO();
    userAccountVO.setSource(User.Source.UNKNOWN);
    userAccountVO.setState(Account.State.disabled.toString());
    Mockito.when(_userAccountDao.getUserAccount("test", 1L)).thenReturn(userAccountVO);
    Mockito.when(userAuthenticator.authenticate("test", "fail", 1L, null)).thenReturn(failureAuthenticationPair);
    Mockito.when(userAuthenticator.authenticate("test", null, 1L, null)).thenReturn(successAuthenticationPair);
    Mockito.when(userAuthenticator.authenticate("test", "", 1L, null)).thenReturn(successAuthenticationPair);
    // Test for incorrect password. authentication should fail
    UserAccount userAccount = accountManager.authenticateUser("test", "fail", 1L, InetAddress.getByName("127.0.0.1"), null);
    Assert.assertNull(userAccount);
    // Test for null password. authentication should fail
    userAccount = accountManager.authenticateUser("test", null, 1L, InetAddress.getByName("127.0.0.1"), null);
    Assert.assertNull(userAccount);
    // Test for empty password. authentication should fail
    userAccount = accountManager.authenticateUser("test", "", 1L, InetAddress.getByName("127.0.0.1"), null);
    Assert.assertNull(userAccount);
    // Verifying that the authentication method is only called when password is specified
    Mockito.verify(userAuthenticator, Mockito.times(1)).authenticate("test", "fail", 1L, null);
    Mockito.verify(userAuthenticator, Mockito.never()).authenticate("test", null, 1L, null);
    Mockito.verify(userAuthenticator, Mockito.never()).authenticate("test", "", 1L, null);
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Pair(com.cloud.legacymodel.utils.Pair) Test(org.junit.Test)

Example 54 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class FirstFitPlannerTest method initializeForTest.

private void initializeForTest(final VirtualMachineProfileImpl vmProfile, final DataCenterDeployment plan, final ExcludeList avoids) {
    final Zone zone = mock(Zone.class);
    final VMInstanceVO vm = mock(VMInstanceVO.class);
    final UserVmVO userVm = mock(UserVmVO.class);
    final ServiceOfferingVO offering = mock(ServiceOfferingVO.class);
    final AccountVO account = mock(AccountVO.class);
    when(account.getId()).thenReturn(accountId);
    when(account.getAccountId()).thenReturn(accountId);
    when(vmProfile.getOwner()).thenReturn(account);
    when(vmProfile.getVirtualMachine()).thenReturn(vm);
    when(vmProfile.getId()).thenReturn(12L);
    when(vmDao.findById(12L)).thenReturn(userVm);
    when(userVm.getAccountId()).thenReturn(accountId);
    when(vm.getDataCenterId()).thenReturn(dataCenterId);
    when(zoneRepository.findById(1L)).thenReturn(Optional.of(zone));
    when(avoids.shouldAvoid(zone)).thenReturn(false);
    when(plan.getDataCenterId()).thenReturn(dataCenterId);
    when(plan.getClusterId()).thenReturn(null);
    when(plan.getPodId()).thenReturn(null);
    // Mock offering details.
    when(vmProfile.getServiceOffering()).thenReturn(offering);
    when(offering.getId()).thenReturn(offeringId);
    when(vmProfile.getServiceOfferingId()).thenReturn(offeringId);
    when(offering.getCpu()).thenReturn(noOfCpusInOffering);
    when(offering.getRamSize()).thenReturn(ramInOffering);
    final List<Long> clustersWithEnoughCapacity = new ArrayList<>();
    clustersWithEnoughCapacity.add(1L);
    clustersWithEnoughCapacity.add(2L);
    clustersWithEnoughCapacity.add(3L);
    clustersWithEnoughCapacity.add(4L);
    clustersWithEnoughCapacity.add(5L);
    clustersWithEnoughCapacity.add(6L);
    when(capacityDao.listClustersInZoneOrPodByHostCapacities(dataCenterId, noOfCpusInOffering, ramInOffering * 1024L * 1024L, Capacity.CAPACITY_TYPE_CPU, true)).thenReturn(clustersWithEnoughCapacity);
    final Map<Long, Double> clusterCapacityMap = new HashMap<>();
    clusterCapacityMap.put(1L, 2048D);
    clusterCapacityMap.put(2L, 2048D);
    clusterCapacityMap.put(3L, 2048D);
    clusterCapacityMap.put(4L, 2048D);
    clusterCapacityMap.put(5L, 2048D);
    clusterCapacityMap.put(6L, 2048D);
    final Pair<List<Long>, Map<Long, Double>> clustersOrderedByCapacity = new Pair<>(clustersWithEnoughCapacity, clusterCapacityMap);
    when(capacityDao.orderClustersByAggregateCapacity(dataCenterId, Capacity.CAPACITY_TYPE_CPU, true)).thenReturn(clustersOrderedByCapacity);
    final List<Long> disabledClusters = new ArrayList<>();
    final List<Long> clustersWithDisabledPods = new ArrayList<>();
    when(clusterDao.listDisabledClusters(dataCenterId, null)).thenReturn(disabledClusters);
    when(clusterDao.listClustersWithDisabledPods(dataCenterId)).thenReturn(clustersWithDisabledPods);
    final List<Long> hostList0 = new ArrayList<>();
    final List<Long> hostList1 = new ArrayList<>();
    final List<Long> hostList2 = new ArrayList<>();
    final List<Long> hostList3 = new ArrayList<>();
    final List<Long> hostList4 = new ArrayList<>();
    final List<Long> hostList5 = new ArrayList<>();
    final List<Long> hostList6 = new ArrayList<>();
    hostList0.add(new Long(1));
    hostList1.add(new Long(10));
    hostList2.add(new Long(11));
    hostList3.add(new Long(12));
    hostList4.add(new Long(13));
    hostList5.add(new Long(14));
    hostList6.add(new Long(15));
    final String[] implicitHostTags = { "GPU" };
    final int ramInBytes = ramInOffering * 1024 * 1024;
    when(serviceOfferingDetailsDao.findDetail(Matchers.anyLong(), anyString())).thenReturn(null);
    when(hostGpuGroupsDao.listHostIds()).thenReturn(hostList0);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(1), HostType.Routing.toString())).thenReturn(hostList1);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(2), HostType.Routing.toString())).thenReturn(hostList2);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(3), HostType.Routing.toString())).thenReturn(hostList3);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(4), HostType.Routing.toString())).thenReturn(hostList4);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(5), HostType.Routing.toString())).thenReturn(hostList5);
    when(capacityDao.listHostsWithEnoughCapacity(noOfCpusInOffering, ramInBytes, new Long(6), HostType.Routing.toString())).thenReturn(hostList6);
    when(hostTagsDao.getDistinctImplicitHostTags(hostList1, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList2, implicitHostTags)).thenReturn(Arrays.asList("abc", "123", "pqr", "456", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList3, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList4, implicitHostTags)).thenReturn(Arrays.asList("abc"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList5, implicitHostTags)).thenReturn(Arrays.asList("abc", "pqr", "xyz"));
    when(hostTagsDao.getDistinctImplicitHostTags(hostList6, implicitHostTags)).thenReturn(Arrays.asList("abc", "123", "pqr", "xyz"));
}
Also used : HashMap(java.util.HashMap) Zone(com.cloud.db.model.Zone) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) AccountVO(com.cloud.user.AccountVO) List(java.util.List) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) Map(java.util.Map) HashMap(java.util.HashMap) Pair(com.cloud.legacymodel.utils.Pair)

Example 55 with Pair

use of com.cloud.legacymodel.utils.Pair in project cosmic by MissionCriticalCloud.

the class SshHelper method sshExecute.

public static Pair<Boolean, String> sshExecute(final String host, final int port, final String user, final File pemKeyFile, final String password, final String command, final int connectTimeoutInMs, final int kexTimeoutInMs, final int waitResultTimeoutInMs) throws Exception {
    com.trilead.ssh2.Connection conn = null;
    com.trilead.ssh2.Session sess = null;
    try {
        conn = new com.trilead.ssh2.Connection(host, port);
        conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
        if (pemKeyFile == null) {
            if (!conn.authenticateWithPassword(user, password)) {
                final String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        } else {
            if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
                final String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        }
        sess = openConnectionSession(conn);
        sess.execCommand(command);
        final InputStream stdout = sess.getStdout();
        final InputStream stderr = sess.getStderr();
        final byte[] buffer = new byte[8192];
        final StringBuffer sbResult = new StringBuffer();
        int currentReadBytes = 0;
        while (true) {
            throwSshExceptionIfStdoutOrStdeerIsNull(stdout, stderr);
            if ((stdout.available() == 0) && (stderr.available() == 0)) {
                final int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, waitResultTimeoutInMs);
                throwSshExceptionIfConditionsTimeout(conditions);
                if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
                    break;
                }
                if (canEndTheSshConnection(waitResultTimeoutInMs, sess, conditions)) {
                    break;
                }
            }
            while (stdout.available() > 0) {
                currentReadBytes = stdout.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
            while (stderr.available() > 0) {
                currentReadBytes = stderr.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
        }
        final String result = sbResult.toString();
        if (sess.getExitStatus() == null) {
            // Exit status is NOT available. Returning failure result.
            s_logger.error(String.format("SSH execution of command %s has no exit status set. Result output: %s", command, result));
            return new Pair<>(false, result);
        }
        if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
            s_logger.error(String.format("SSH execution of command %s has an error status code in return. Result output: %s", command, result));
            return new Pair<>(false, result);
        }
        return new Pair<>(true, result);
    } finally {
        if (sess != null) {
            sess.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
Also used : Session(com.trilead.ssh2.Session) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) Pair(com.cloud.legacymodel.utils.Pair)

Aggregations

Pair (com.cloud.legacymodel.utils.Pair)139 ArrayList (java.util.ArrayList)87 List (java.util.List)64 Account (com.cloud.legacymodel.user.Account)49 Filter (com.cloud.utils.db.Filter)48 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)38 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)27 HashMap (java.util.HashMap)27 Ternary (com.cloud.legacymodel.utils.Ternary)23 ListProjectResourcesCriteria (com.cloud.projects.Project.ListProjectResourcesCriteria)22 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)20 SSHKeyPair (com.cloud.legacymodel.user.SSHKeyPair)16 TemplateFilter (com.cloud.legacymodel.storage.VirtualMachineTemplate.TemplateFilter)13 Map (java.util.Map)13 DB (com.cloud.utils.db.DB)11 DomainVO (com.cloud.domain.DomainVO)10 VolumeVO (com.cloud.storage.VolumeVO)10 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)9 Network (com.cloud.legacymodel.network.Network)9 ResourceTagVO (com.cloud.tags.ResourceTagVO)9