use of com.cloud.user.UserVO in project cloudstack by apache.
the class ListAndSwitchSAMLAccountCmdTest method testListAndSwitchSAMLAccountCmd.
@Test
public void testListAndSwitchSAMLAccountCmd() throws Exception {
// Setup
final Map<String, Object[]> params = new HashMap<String, Object[]>();
final String sessionKeyValue = "someSessionIDValue";
Mockito.when(session.getAttribute(ApiConstants.SESSIONKEY)).thenReturn(sessionKeyValue);
Mockito.when(session.getAttribute("userid")).thenReturn(2L);
params.put(ApiConstants.USER_ID, new String[] { "2" });
params.put(ApiConstants.DOMAIN_ID, new String[] { "1" });
Mockito.when(userDao.findByUuid(Mockito.anyString())).thenReturn(new UserVO(2L));
Mockito.when(domainDao.findByUuid(Mockito.anyString())).thenReturn(new DomainVO());
// Mock/field setup
ListAndSwitchSAMLAccountCmd cmd = new ListAndSwitchSAMLAccountCmd();
Field apiServerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_apiServer");
apiServerField.setAccessible(true);
apiServerField.set(cmd, apiServer);
Field managerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_samlAuthManager");
managerField.setAccessible(true);
managerField.set(cmd, samlAuthManager);
Field accountServiceField = BaseCmd.class.getDeclaredField("_accountService");
accountServiceField.setAccessible(true);
accountServiceField.set(cmd, accountService);
Field userAccountDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userAccountDao");
userAccountDaoField.setAccessible(true);
userAccountDaoField.set(cmd, userAccountDao);
Field userDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userDao");
userDaoField.setAccessible(true);
userDaoField.set(cmd, userDao);
Field domainDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_domainDao");
domainDaoField.setAccessible(true);
domainDaoField.set(cmd, domainDao);
// invalid session test
try {
cmd.authenticate("command", params, null, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
} catch (ServerApiException exception) {
assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
} finally {
Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
}
// invalid sessionkey value test
params.put(ApiConstants.SESSIONKEY, new String[] { "someOtherValue" });
try {
Mockito.when(session.isNew()).thenReturn(false);
cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
} catch (ServerApiException exception) {
assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
} finally {
Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
}
// valid sessionkey value test
params.put(ApiConstants.SESSIONKEY, new String[] { sessionKeyValue });
try {
cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
} catch (ServerApiException exception) {
assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
} finally {
Mockito.verify(accountService, Mockito.times(1)).getUserAccountById(Mockito.anyLong());
}
// valid sessionkey, invalid useraccount type (non-saml) value test
UserAccountVO mockedUserAccount = new UserAccountVO();
mockedUserAccount.setId(2L);
mockedUserAccount.setAccountState(Account.State.enabled.toString());
mockedUserAccount.setUsername("someUsername");
mockedUserAccount.setExternalEntity("some IDP ID");
mockedUserAccount.setDomainId(0L);
mockedUserAccount.setSource(User.Source.UNKNOWN);
Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
try {
cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
} catch (ServerApiException exception) {
assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
} finally {
// accountService should have been called twice by now, for this case and the case above
Mockito.verify(accountService, Mockito.times(2)).getUserAccountById(Mockito.anyLong());
}
// all valid test
mockedUserAccount.setSource(User.Source.SAML2);
Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(true);
LoginCmdResponse loginCmdResponse = new LoginCmdResponse();
loginCmdResponse.setUserId("1");
loginCmdResponse.setDomainId("1");
loginCmdResponse.setType("1");
loginCmdResponse.setUsername("userName");
loginCmdResponse.setAccount("someAccount");
loginCmdResponse.setFirstName("firstName");
loginCmdResponse.setLastName("lastName");
loginCmdResponse.setSessionKey("newSessionKeyString");
Mockito.when(apiServer.loginUser(Mockito.any(HttpSession.class), Mockito.anyString(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyString(), Mockito.any(InetAddress.class), Mockito.anyMap())).thenReturn(loginCmdResponse);
try {
cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
} catch (ServerApiException exception) {
fail("SAML list and switch account API failed to pass for all valid data: " + exception.getMessage());
} finally {
// accountService should have been called 4 times by now, for this case twice and 2 for cases above
Mockito.verify(accountService, Mockito.times(4)).getUserAccountById(Mockito.anyLong());
Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString());
}
}
use of com.cloud.user.UserVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method finalizeVirtualMachineProfile.
@Override
public boolean finalizeVirtualMachineProfile(final VirtualMachineProfile profile, final DeployDestination dest, final ReservationContext context) {
boolean dnsProvided = true;
boolean dhcpProvided = true;
boolean publicNetwork = false;
final DataCenterVO dc = _dcDao.findById(dest.getDataCenter().getId());
_dcDao.loadDetails(dc);
// 1) Set router details
final DomainRouterVO router = _routerDao.findById(profile.getVirtualMachine().getId());
final Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(router.getId());
router.setDetails(details);
// 2) Prepare boot loader elements related with Control network
final StringBuilder buf = profile.getBootArgsBuilder();
buf.append(" template=domP");
buf.append(" name=").append(profile.getHostName());
if (Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) {
buf.append(" vmpassword=").append(_configDao.getValue("system.vm.password"));
}
NicProfile controlNic = null;
String defaultDns1 = null;
String defaultDns2 = null;
String defaultIp6Dns1 = null;
String defaultIp6Dns2 = null;
for (final NicProfile nic : profile.getNics()) {
final int deviceId = nic.getDeviceId();
boolean ipv4 = false, ipv6 = false;
if (nic.getIPv4Address() != null) {
ipv4 = true;
buf.append(" eth").append(deviceId).append("ip=").append(nic.getIPv4Address());
buf.append(" eth").append(deviceId).append("mask=").append(nic.getIPv4Netmask());
}
if (nic.getIPv6Address() != null) {
ipv6 = true;
buf.append(" eth").append(deviceId).append("ip6=").append(nic.getIPv6Address());
buf.append(" eth").append(deviceId).append("ip6prelen=").append(NetUtils.getIp6CidrSize(nic.getIPv6Cidr()));
}
if (nic.isDefaultNic()) {
if (ipv4) {
buf.append(" gateway=").append(nic.getIPv4Gateway());
}
if (ipv6) {
buf.append(" ip6gateway=").append(nic.getIPv6Gateway());
}
defaultDns1 = nic.getIPv4Dns1();
defaultDns2 = nic.getIPv4Dns2();
defaultIp6Dns1 = nic.getIPv6Dns1();
defaultIp6Dns2 = nic.getIPv6Dns2();
}
if (nic.getTrafficType() == TrafficType.Management) {
buf.append(" localgw=").append(dest.getPod().getGateway());
} else if (nic.getTrafficType() == TrafficType.Control) {
controlNic = nic;
buf.append(createRedundantRouterArgs(controlNic, router));
// DOMR control command is sent over management server in VMware
if (dest.getHost().getHypervisorType() == HypervisorType.VMware || dest.getHost().getHypervisorType() == HypervisorType.Hyperv) {
s_logger.info("Check if we need to add management server explicit route to DomR. pod cidr: " + dest.getPod().getCidrAddress() + "/" + dest.getPod().getCidrSize() + ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + ApiServiceConfiguration.ManagementHostIPAdr.value());
if (s_logger.isInfoEnabled()) {
s_logger.info("Add management server explicit route to DomR.");
}
// always add management explicit route, for basic
// networking setup, DomR may have two interfaces while both
// are on the same subnet
_mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
if (NetUtils.isValidCIDR(_mgmtCidr)) {
buf.append(" mgmtcidr=").append(_mgmtCidr);
buf.append(" localgw=").append(dest.getPod().getGateway());
}
if (dc.getNetworkType() == NetworkType.Basic) {
// ask domR to setup SSH on guest network
buf.append(" sshonguest=true");
}
}
} else if (nic.getTrafficType() == TrafficType.Guest) {
dnsProvided = _networkModel.isProviderSupportServiceInNetwork(nic.getNetworkId(), Service.Dns, Provider.VirtualRouter);
dhcpProvided = _networkModel.isProviderSupportServiceInNetwork(nic.getNetworkId(), Service.Dhcp, Provider.VirtualRouter);
// build bootloader parameter for the guest
buf.append(createGuestBootLoadArgs(nic, defaultDns1, defaultDns2, router));
} else if (nic.getTrafficType() == TrafficType.Public) {
publicNetwork = true;
}
}
if (controlNic == null) {
throw new CloudRuntimeException("Didn't start a control port");
}
final String rpValue = _configDao.getValue(Config.NetworkRouterRpFilter.key());
if (rpValue != null && rpValue.equalsIgnoreCase("true")) {
_disableRpFilter = true;
} else {
_disableRpFilter = false;
}
String rpFilter = " ";
String type = null;
if (router.getVpcId() != null) {
type = "vpcrouter";
if (_disableRpFilter) {
rpFilter = " disable_rp_filter=true";
}
} else if (!publicNetwork) {
type = "dhcpsrvr";
} else {
type = "router";
if (_disableRpFilter) {
rpFilter = " disable_rp_filter=true";
}
}
if (_disableRpFilter) {
rpFilter = " disable_rp_filter=true";
}
buf.append(" type=" + type + rpFilter);
final String domain_suffix = dc.getDetail(ZoneConfig.DnsSearchOrder.getName());
if (domain_suffix != null) {
buf.append(" dnssearchorder=").append(domain_suffix);
}
if (profile.getHypervisorType() == HypervisorType.VMware || profile.getHypervisorType() == HypervisorType.Hyperv) {
buf.append(" extra_pubnics=" + _routerExtraPublicNics);
}
/*
* If virtual router didn't provide DNS service but provide DHCP
* service, we need to override the DHCP response to return DNS server
* rather than virtual router itself.
*/
if (dnsProvided || dhcpProvided) {
if (defaultDns1 != null) {
buf.append(" dns1=").append(defaultDns1);
}
if (defaultDns2 != null) {
buf.append(" dns2=").append(defaultDns2);
}
if (defaultIp6Dns1 != null) {
buf.append(" ip6dns1=").append(defaultIp6Dns1);
}
if (defaultIp6Dns2 != null) {
buf.append(" ip6dns2=").append(defaultIp6Dns2);
}
boolean useExtDns = !dnsProvided;
/* For backward compatibility */
useExtDns = useExtDns || UseExternalDnsServers.valueIn(dc.getId());
if (useExtDns) {
buf.append(" useextdns=true");
}
}
if (Boolean.valueOf(_configDao.getValue(Config.BaremetalProvisionDoneNotificationEnabled.key()))) {
final QueryBuilder<UserVO> acntq = QueryBuilder.create(UserVO.class);
acntq.and(acntq.entity().getUsername(), SearchCriteria.Op.EQ, "baremetal-system-account");
final UserVO user = acntq.find();
if (user == null) {
s_logger.warn(String.format("global setting[baremetal.provision.done.notification] is enabled but user baremetal-system-account is not found. Baremetal provision done notification will not be enabled"));
} else {
buf.append(String.format(" baremetalnotificationsecuritykey=%s", user.getSecretKey()));
buf.append(String.format(" baremetalnotificationapikey=%s", user.getApiKey()));
buf.append(" host=").append(ApiServiceConfiguration.ManagementHostIPAdr.value());
buf.append(" port=").append(_configDao.getValue(Config.BaremetalProvisionDoneNotificationPort.key()));
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Boot Args for " + profile + ": " + buf.toString());
}
return true;
}
use of com.cloud.user.UserVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method rebootRouter.
@Override
@ActionEvent(eventType = EventTypes.EVENT_ROUTER_REBOOT, eventDescription = "rebooting router Vm", async = true)
public VirtualRouter rebootRouter(final long routerId, final boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
final Account caller = CallContext.current().getCallingAccount();
// verify parameters
final DomainRouterVO router = _routerDao.findById(routerId);
if (router == null) {
throw new InvalidParameterValueException("Unable to find domain router with id " + routerId + ".");
}
_accountMgr.checkAccess(caller, null, true, router);
// Can reboot domain router only in Running state
if (router == null || router.getState() != VirtualMachine.State.Running) {
s_logger.warn("Unable to reboot, virtual router is not in the right state " + router.getState());
throw new ResourceUnavailableException("Unable to reboot domR, it is not in right state " + router.getState(), DataCenter.class, router.getDataCenterId());
}
final UserVO user = _userDao.findById(CallContext.current().getCallingUserId());
s_logger.debug("Stopping and starting router " + router + " as a part of router reboot");
if (stop(router, false, user, caller) != null) {
return startRouter(routerId, reprogramNetwork);
} else {
throw new CloudRuntimeException("Failed to reboot router " + router);
}
}
use of com.cloud.user.UserVO in project cloudstack by apache.
the class NetworkHelperImpl method deployRouter.
@Override
public DomainRouterVO deployRouter(final RouterDeploymentDefinition routerDeploymentDefinition, final boolean startRouter) throws InsufficientAddressCapacityException, InsufficientServerCapacityException, InsufficientCapacityException, StorageUnavailableException, ResourceUnavailableException {
final ServiceOfferingVO routerOffering = _serviceOfferingDao.findById(routerDeploymentDefinition.getServiceOfferingId());
final Account owner = routerDeploymentDefinition.getOwner();
// Router is the network element, we don't know the hypervisor type yet.
// Try to allocate the domR twice using diff hypervisors, and when
// failed both times, throw the exception up
final List<HypervisorType> hypervisors = getHypervisors(routerDeploymentDefinition);
int allocateRetry = 0;
int startRetry = 0;
DomainRouterVO router = null;
for (final Iterator<HypervisorType> iter = hypervisors.iterator(); iter.hasNext(); ) {
final HypervisorType hType = iter.next();
try {
final long id = _routerDao.getNextInSequence(Long.class, "id");
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("Allocating the VR with id=%s in datacenter %s with the hypervisor type %s", id, routerDeploymentDefinition.getDest().getDataCenter(), hType));
}
final String templateName = retrieveTemplateName(hType, routerDeploymentDefinition.getDest().getDataCenter().getId());
final VMTemplateVO template = _templateDao.findRoutingTemplate(hType, templateName);
if (template == null) {
s_logger.debug(hType + " won't support system vm, skip it");
continue;
}
final boolean offerHA = routerOffering.getOfferHA();
// routerDeploymentDefinition.getVpc().getId() ==> do not use
// VPC because it is not a VPC offering.
final Long vpcId = routerDeploymentDefinition.getVpc() != null ? routerDeploymentDefinition.getVpc().getId() : null;
long userId = CallContext.current().getCallingUserId();
if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
final List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
if (!userVOs.isEmpty()) {
userId = userVOs.get(0).getId();
}
}
router = new DomainRouterVO(id, routerOffering.getId(), routerDeploymentDefinition.getVirtualProvider().getId(), VirtualMachineName.getRouterName(id, s_vmInstanceName), template.getId(), template.getHypervisorType(), template.getGuestOSId(), owner.getDomainId(), owner.getId(), userId, routerDeploymentDefinition.isRedundant(), RedundantState.UNKNOWN, offerHA, false, vpcId);
router.setDynamicallyScalable(template.isDynamicallyScalable());
router.setRole(Role.VIRTUAL_ROUTER);
router = _routerDao.persist(router);
reallocateRouterNetworks(routerDeploymentDefinition, router, template, null);
router = _routerDao.findById(router.getId());
} catch (final InsufficientCapacityException ex) {
if (allocateRetry < 2 && iter.hasNext()) {
s_logger.debug("Failed to allocate the VR with hypervisor type " + hType + ", retrying one more time");
continue;
} else {
throw ex;
}
} finally {
allocateRetry++;
}
if (startRouter) {
try {
router = startVirtualRouter(router, _accountMgr.getSystemUser(), _accountMgr.getSystemAccount(), routerDeploymentDefinition.getParams());
break;
} catch (final InsufficientCapacityException ex) {
if (startRetry < 2 && iter.hasNext()) {
s_logger.debug("Failed to start the VR " + router + " with hypervisor type " + hType + ", " + "destroying it and recreating one more time");
// destroy the router
destroyRouter(router.getId(), _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM), User.UID_SYSTEM);
continue;
} else {
throw ex;
}
} finally {
startRetry++;
}
} else {
// return stopped router
return router;
}
}
return router;
}
use of com.cloud.user.UserVO in project cloudstack by apache.
the class QuotaAlertManagerImplTest method testSendQuotaAlert.
@Test
public void testSendQuotaAlert() throws UnsupportedEncodingException, MessagingException {
Mockito.doCallRealMethod().when(quotaAlertManager).sendQuotaAlert(Mockito.any(QuotaAlertManagerImpl.DeferredQuotaEmail.class));
AccountVO account = new AccountVO();
account.setId(2L);
account.setDomainId(1L);
account.setType(Account.ACCOUNT_TYPE_NORMAL);
account.setAccountName("admin");
account.setUuid("uuid");
QuotaAccountVO quotaAccount = new QuotaAccountVO(2L);
quotaAccount.setQuotaBalance(new BigDecimal(404));
quotaAccount.setQuotaMinBalance(new BigDecimal(100));
quotaAccount.setQuotaBalanceDate(new Date());
quotaAccount.setQuotaAlertDate(null);
quotaAccount.setQuotaEnforce(0);
QuotaAlertManagerImpl.DeferredQuotaEmail email = new QuotaAlertManagerImpl.DeferredQuotaEmail(account, quotaAccount, new BigDecimal(100), QuotaConfig.QuotaEmailTemplateTypes.QUOTA_LOW);
QuotaEmailTemplatesVO quotaEmailTemplatesVO = new QuotaEmailTemplatesVO();
quotaEmailTemplatesVO.setTemplateSubject("Low quota");
quotaEmailTemplatesVO.setTemplateBody("Low quota {{accountID}}");
List<QuotaEmailTemplatesVO> emailTemplates = new ArrayList<>();
emailTemplates.add(quotaEmailTemplatesVO);
Mockito.when(quotaEmailTemplateDao.listAllQuotaEmailTemplates(Mockito.anyString())).thenReturn(emailTemplates);
DomainVO domain = new DomainVO();
domain.setUuid("uuid");
domain.setName("/domain");
Mockito.when(domainDao.findByIdIncludingRemoved(Mockito.anyLong())).thenReturn(new DomainVO());
UserVO user = new UserVO();
user.setUsername("user1");
user.setEmail("user1@apache.org");
List<UserVO> users = new ArrayList<>();
users.add(user);
Mockito.when(userDao.listByAccount(Mockito.anyLong())).thenReturn(users);
quotaAlertManager.sendQuotaAlert(email);
assertTrue(email.getSendDate() != null);
Mockito.verify(emailQuotaAlert, Mockito.times(1)).sendQuotaAlert(Mockito.anyList(), Mockito.anyString(), Mockito.anyString());
}
Aggregations