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());
}
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());
}
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);
}
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"));
}
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();
}
}
}
Aggregations