public static CallContext register(long callingUserId, long callingAccountId) throws CloudAuthenticationException { Account account = s_entityMgr.findById(Account.class, callingAccountId); if (account == null) { throw new CloudAuthenticationException("The account is no longer current.") .add(Account.class, Long.toString(callingAccountId)); } User user = s_entityMgr.findById(User.class, callingUserId); if (user == null) { throw new CloudAuthenticationException("The user is no longer current.") .add(User.class, Long.toString(callingUserId)); } return register(user, account); }
public static CallContext register(String callingUserUuid, String callingAccountUuid) { Account account = s_entityMgr.findByUuid(Account.class, callingAccountUuid); if (account == null) { throw new CloudAuthenticationException("The account is no longer current.") .add(Account.class, callingAccountUuid); } User user = s_entityMgr.findByUuid(User.class, callingUserUuid); if (user == null) { throw new CloudAuthenticationException("The user is no longer current.") .add(User.class, callingUserUuid); } return register(user, account); }
public SslCertResponse createCertResponse(SslCertVO cert, List<LoadBalancerCertMapVO> lbCertMap) { SslCertResponse response = new SslCertResponse(); Account account = _accountDao.findByIdIncludingRemoved(cert.getAccountId()); response.setObjectName("sslcert"); response.setId(cert.getUuid()); response.setCertificate(cert.getCertificate()); response.setPrivatekey(cert.getKey()); response.setFingerprint(cert.getFingerPrint()); response.setAccountName(account.getAccountName()); if (cert.getChain() != null) response.setCertchain(cert.getChain()); if (lbCertMap != null && !lbCertMap.isEmpty()) { List<String> lbIds = new ArrayList<String>(); for (LoadBalancerCertMapVO mapVO : lbCertMap) { LoadBalancer lb = _entityMgr.findById(LoadBalancerVO.class, mapVO.getLbId()); lbIds.add(lb.getUuid()); } response.setLbIds(lbIds); } return response; }
@DB @Override @ActionEvent( eventType = EventTypes.EVENT_LB_CERT_DELETE, eventDescription = "Deleting a certificate to cloudstack", async = false) public void deleteSslCert(DeleteSslCertCmd deleteSslCertCmd) { CallContext ctx = CallContext.current(); Account caller = ctx.getCallingAccount(); Long certId = deleteSslCertCmd.getId(); SslCertVO certVO = _sslCertDao.findById(certId); if (certVO == null) { throw new InvalidParameterValueException("Invalid certificate id: " + certId); } _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, certVO); List<LoadBalancerCertMapVO> lbCertRule = _lbCertDao.listByCertId(certId); if ((lbCertRule != null) && (!lbCertRule.isEmpty())) { String lbUuids = ""; for (LoadBalancerCertMapVO rule : lbCertRule) { LoadBalancerVO lb = _entityMgr.findById(LoadBalancerVO.class, rule.getLbId()); lbUuids += " " + lb.getUuid(); } throw new CloudRuntimeException("Certificate in use by a loadbalancer(s)" + lbUuids); } _sslCertDao.remove(certId); }
private String getBaseAsyncCreateResponse(long jobId, BaseAsyncCreateCmd cmd, String objectUuid) { CreateCmdResponse response = new CreateCmdResponse(); AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId); response.setJobId(job.getUuid()); response.setId(objectUuid); response.setResponseName(cmd.getCommandName()); return ApiResponseSerializer.toSerializedString(response, cmd.getResponseType()); }
@Override public boolean finalizeVirtualMachineProfile( final VirtualMachineProfile profile, final DeployDestination dest, final ReservationContext context) { final DomainRouterVO domainRouterVO = _routerDao.findById(profile.getId()); final Long vpcId = domainRouterVO.getVpcId(); if (vpcId != null) { if (domainRouterVO.getState() == State.Starting || domainRouterVO.getState() == State.Running) { String defaultDns1 = null; String defaultDns2 = null; // remove public and guest nics as we will plug them later final Iterator<NicProfile> it = profile.getNics().iterator(); while (it.hasNext()) { final NicProfile nic = it.next(); if (nic.getTrafficType() == TrafficType.Public || nic.getTrafficType() == TrafficType.Guest) { // save dns information if (nic.getTrafficType() == TrafficType.Public) { defaultDns1 = nic.getIPv4Dns1(); defaultDns2 = nic.getIPv4Dns2(); } s_logger.debug( "Removing nic " + nic + " of type " + nic.getTrafficType() + " from the nics passed on vm start. " + "The nic will be plugged later"); it.remove(); } } // add vpc cidr/dns/networkdomain to the boot load args final StringBuilder buf = profile.getBootArgsBuilder(); final Vpc vpc = _entityMgr.findById(Vpc.class, vpcId); buf.append(" vpccidr=" + vpc.getCidr() + " domain=" + vpc.getNetworkDomain()); buf.append(" dns1=").append(defaultDns1); if (defaultDns2 != null) { buf.append(" dns2=").append(defaultDns2); } } } return super.finalizeVirtualMachineProfile(profile, dest, context); }
@Override public boolean replaceNetworkACL(NetworkACL acl, NetworkVO network) throws ResourceUnavailableException { NetworkOffering guestNtwkOff = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); if (guestNtwkOff == null) { throw new InvalidParameterValueException( "Can't find network offering associated with network: " + network.getUuid()); } // verify that ACLProvider is supported by network offering if (!_ntwkModel.areServicesSupportedByNetworkOffering( guestNtwkOff.getId(), Service.NetworkACL)) { throw new InvalidParameterValueException( "Cannot apply NetworkACL. Network Offering does not support NetworkACL service"); } if (network.getNetworkACLId() != null) { // Revoke ACL Items of the existing ACL if the new ACL is empty // Existing rules won't be removed otherwise List<NetworkACLItemVO> aclItems = _networkACLItemDao.listByACL(acl.getId()); if (aclItems == null || aclItems.isEmpty()) { s_logger.debug("New network ACL is empty. Revoke existing rules before applying ACL"); if (!revokeACLItemsForNetwork(network.getId())) { throw new CloudRuntimeException( "Failed to replace network ACL. Error while removing existing ACL items for network: " + network.getId()); } } } network.setNetworkACLId(acl.getId()); // Update Network ACL if (_networkDao.update(network.getId(), network)) { s_logger.debug( "Updated network: " + network.getId() + " with Network ACL Id: " + acl.getId() + ", Applying ACL items"); // Apply ACL to network return applyACLToNetwork(network.getId()); } return false; }
@Bean public EntityManager entityManager() { EntityManager mock = Mockito.mock(EntityManager.class); try { Mockito.when(mock.findById(Matchers.same(Account.class), Matchers.anyLong())) .thenReturn(_accountDao.findById(Account.ACCOUNT_ID_SYSTEM)); Mockito.when(mock.findById(Matchers.same(User.class), Matchers.anyLong())) .thenReturn(_userDao.findById(User.UID_SYSTEM)); Mockito.when(mock.findById(Matchers.same(NetworkOffering.class), Matchers.any(Long.class))) .thenAnswer( new Answer<NetworkOffering>() { @Override public NetworkOffering answer(final InvocationOnMock invocation) throws Throwable { Long id = (Long) invocation.getArguments()[1]; return _networkOfferingDao.findById(id); } }); Mockito.when(mock.findById(Matchers.same(IpAddress.class), Matchers.any(Long.class))) .thenAnswer( new Answer<IpAddress>() { @Override public IpAddress answer(final InvocationOnMock invocation) throws Throwable { Long id = (Long) invocation.getArguments()[1]; return _ipAddressDao.findById(id); } }); Mockito.when(mock.findById(Matchers.same(DataCenter.class), Matchers.any(Long.class))) .thenAnswer( new Answer<DataCenter>() { @Override public DataCenter answer(final InvocationOnMock invocation) throws Throwable { Long id = (Long) invocation.getArguments()[1]; return _zoneDao.findById(id); } }); } catch (Exception e) { e.printStackTrace(); } CallContext.init(mock); return mock; }
@Override public List<SslCertResponse> listSslCerts(ListSslCertsCmd listSslCertCmd) { CallContext ctx = CallContext.current(); Account caller = ctx.getCallingAccount(); Long certId = listSslCertCmd.getCertId(); Long accountId = listSslCertCmd.getAccountId(); Long lbRuleId = listSslCertCmd.getLbId(); List<SslCertResponse> certResponseList = new ArrayList<SslCertResponse>(); if (certId == null && accountId == null && lbRuleId == null) { throw new InvalidParameterValueException( "Invalid parameters either certificate ID or Account ID or Loadbalancer ID required"); } List<LoadBalancerCertMapVO> certLbMap = null; SslCertVO certVO = null; if (certId != null) { certVO = _sslCertDao.findById(certId); if (certVO == null) { throw new InvalidParameterValueException("Invalid certificate id: " + certId); } _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, true, certVO); certLbMap = _lbCertDao.listByCertId(certId); certResponseList.add(createCertResponse(certVO, certLbMap)); return certResponseList; } if (lbRuleId != null) { LoadBalancer lb = _entityMgr.findById(LoadBalancerVO.class, lbRuleId); if (lb == null) { throw new InvalidParameterValueException("found no loadbalancer wth id: " + lbRuleId); } _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, true, lb); // get the cert id LoadBalancerCertMapVO lbCertMapRule; lbCertMapRule = _lbCertDao.findByLbRuleId(lbRuleId); if (lbCertMapRule == null) { s_logger.debug("No certificate bound to loadbalancer id: " + lbRuleId); return certResponseList; } certVO = _sslCertDao.findById(lbCertMapRule.getCertId()); certLbMap = _lbCertDao.listByCertId(lbCertMapRule.getCertId()); certResponseList.add(createCertResponse(certVO, certLbMap)); return certResponseList; } // reached here look by accountId List<SslCertVO> certVOList = _sslCertDao.listByAccountId(accountId); if (certVOList == null || certVOList.isEmpty()) return certResponseList; _accountMgr.checkAccess(caller, SecurityChecker.AccessType.UseEntry, true, certVOList.get(0)); for (SslCertVO cert : certVOList) { certLbMap = _lbCertDao.listByCertId(cert.getId()); certResponseList.add(createCertResponse(cert, certLbMap)); } return certResponseList; }
@Override public boolean finalizeCommandsOnStart(final Commands cmds, final VirtualMachineProfile profile) { final DomainRouterVO domainRouterVO = _routerDao.findById(profile.getId()); final boolean isVpc = domainRouterVO.getVpcId() != null; if (!isVpc) { return super.finalizeCommandsOnStart(cmds, profile); } if (domainRouterVO.getState() == State.Starting || domainRouterVO.getState() == State.Running) { // 1) FORM SSH CHECK COMMAND final NicProfile controlNic = getControlNic(profile); if (controlNic == null) { s_logger.error("Control network doesn't exist for the router " + domainRouterVO); return false; } finalizeSshAndVersionAndNetworkUsageOnStart(cmds, profile, domainRouterVO, controlNic); // 2) FORM PLUG NIC COMMANDS final List<Pair<Nic, Network>> guestNics = new ArrayList<Pair<Nic, Network>>(); final List<Pair<Nic, Network>> publicNics = new ArrayList<Pair<Nic, Network>>(); final Map<String, String> vlanMacAddress = new HashMap<String, String>(); final List<? extends Nic> routerNics = _nicDao.listByVmId(profile.getId()); for (final Nic routerNic : routerNics) { final Network network = _networkModel.getNetwork(routerNic.getNetworkId()); if (network.getTrafficType() == TrafficType.Guest) { final Pair<Nic, Network> guestNic = new Pair<Nic, Network>(routerNic, network); guestNics.add(guestNic); } else if (network.getTrafficType() == TrafficType.Public) { final Pair<Nic, Network> publicNic = new Pair<Nic, Network>(routerNic, network); publicNics.add(publicNic); final String vlanTag = BroadcastDomainType.getValue(routerNic.getBroadcastUri()); vlanMacAddress.put(vlanTag, routerNic.getMacAddress()); } } final List<Command> usageCmds = new ArrayList<Command>(); // 3) PREPARE PLUG NIC COMMANDS try { // add VPC router to public networks final List<PublicIp> sourceNat = new ArrayList<PublicIp>(1); for (final Pair<Nic, Network> nicNtwk : publicNics) { final Nic publicNic = nicNtwk.first(); final Network publicNtwk = nicNtwk.second(); final IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId( publicNtwk.getId(), publicNic.getIPv4Address()); if (userIp.isSourceNat()) { final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId())); sourceNat.add(publicIp); if (domainRouterVO.getPublicIpAddress() == null) { final DomainRouterVO routerVO = _routerDao.findById(domainRouterVO.getId()); routerVO.setPublicIpAddress(publicNic.getIPv4Address()); routerVO.setPublicNetmask(publicNic.getIPv4Netmask()); routerVO.setPublicMacAddress(publicNic.getMacAddress()); _routerDao.update(routerVO.getId(), routerVO); } } final PlugNicCommand plugNicCmd = new PlugNicCommand( _nwHelper.getNicTO( domainRouterVO, publicNic.getNetworkId(), publicNic.getBroadcastUri().toString()), domainRouterVO.getInstanceName(), domainRouterVO.getType()); cmds.addCommand(plugNicCmd); final VpcVO vpc = _vpcDao.findById(domainRouterVO.getVpcId()); final NetworkUsageCommand netUsageCmd = new NetworkUsageCommand( domainRouterVO.getPrivateIpAddress(), domainRouterVO.getInstanceName(), true, publicNic.getIPv4Address(), vpc.getCidr()); usageCmds.add(netUsageCmd); UserStatisticsVO stats = _userStatsDao.findBy( domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNtwk.getId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString()); if (stats == null) { stats = new UserStatisticsVO( domainRouterVO.getAccountId(), domainRouterVO.getDataCenterId(), publicNic.getIPv4Address(), domainRouterVO.getId(), domainRouterVO.getType().toString(), publicNtwk.getId()); _userStatsDao.persist(stats); } } // create ip assoc for source nat if (!sourceNat.isEmpty()) { _commandSetupHelper.createVpcAssociatePublicIPCommands( domainRouterVO, sourceNat, cmds, vlanMacAddress); } // add VPC router to guest networks for (final Pair<Nic, Network> nicNtwk : guestNics) { final Nic guestNic = nicNtwk.first(); // plug guest nic final PlugNicCommand plugNicCmd = new PlugNicCommand( _nwHelper.getNicTO(domainRouterVO, guestNic.getNetworkId(), null), domainRouterVO.getInstanceName(), domainRouterVO.getType()); cmds.addCommand(plugNicCmd); if (!_networkModel.isPrivateGateway(guestNic.getNetworkId())) { // set guest network final VirtualMachine vm = _vmDao.findById(domainRouterVO.getId()); final NicProfile nicProfile = _networkModel.getNicProfile(vm, guestNic.getNetworkId(), null); final SetupGuestNetworkCommand setupCmd = _commandSetupHelper.createSetupGuestNetworkCommand( domainRouterVO, true, nicProfile); cmds.addCommand(setupCmd); } else { // set private network final PrivateIpVO ipVO = _privateIpDao.findByIpAndSourceNetworkId( guestNic.getNetworkId(), guestNic.getIPv4Address()); final Network network = _networkDao.findById(guestNic.getNetworkId()); BroadcastDomainType.getValue(network.getBroadcastUri()); final String netmask = NetUtils.getCidrNetmask(network.getCidr()); final PrivateIpAddress ip = new PrivateIpAddress( ipVO, network.getBroadcastUri().toString(), network.getGateway(), netmask, guestNic.getMacAddress()); final List<PrivateIpAddress> privateIps = new ArrayList<PrivateIpAddress>(1); privateIps.add(ip); _commandSetupHelper.createVpcAssociatePrivateIPCommands( domainRouterVO, privateIps, cmds, true); final Long privateGwAclId = _vpcGatewayDao.getNetworkAclIdForPrivateIp( ipVO.getVpcId(), ipVO.getNetworkId(), ipVO.getIpAddress()); if (privateGwAclId != null) { // set network acl on private gateway final List<NetworkACLItemVO> networkACLs = _networkACLItemDao.listByACL(privateGwAclId); s_logger.debug( "Found " + networkACLs.size() + " network ACLs to apply as a part of VPC VR " + domainRouterVO + " start for private gateway ip = " + ipVO.getIpAddress()); _commandSetupHelper.createNetworkACLsCommands( networkACLs, domainRouterVO, cmds, ipVO.getNetworkId(), true); } } } } catch (final Exception ex) { s_logger.warn( "Failed to add router " + domainRouterVO + " to network due to exception ", ex); return false; } // 4) RE-APPLY ALL STATIC ROUTE RULES final List<? extends StaticRoute> routes = _staticRouteDao.listByVpcId(domainRouterVO.getVpcId()); final List<StaticRouteProfile> staticRouteProfiles = new ArrayList<StaticRouteProfile>(routes.size()); final Map<Long, VpcGateway> gatewayMap = new HashMap<Long, VpcGateway>(); for (final StaticRoute route : routes) { VpcGateway gateway = gatewayMap.get(route.getVpcGatewayId()); if (gateway == null) { gateway = _entityMgr.findById(VpcGateway.class, route.getVpcGatewayId()); gatewayMap.put(gateway.getId(), gateway); } staticRouteProfiles.add(new StaticRouteProfile(route, gateway)); } s_logger.debug( "Found " + staticRouteProfiles.size() + " static routes to apply as a part of vpc route " + domainRouterVO + " start"); if (!staticRouteProfiles.isEmpty()) { _commandSetupHelper.createStaticRouteCommands(staticRouteProfiles, domainRouterVO, cmds); } // 5) RE-APPLY ALL REMOTE ACCESS VPNs final RemoteAccessVpnVO vpn = _vpnDao.findByAccountAndVpc(domainRouterVO.getAccountId(), domainRouterVO.getVpcId()); if (vpn != null) { _commandSetupHelper.createApplyVpnCommands(true, vpn, domainRouterVO, cmds); } // 6) REPROGRAM GUEST NETWORK boolean reprogramGuestNtwks = true; if (profile.getParameter(Param.ReProgramGuestNetworks) != null && (Boolean) profile.getParameter(Param.ReProgramGuestNetworks) == false) { reprogramGuestNtwks = false; } final VirtualRouterProvider vrProvider = _vrProviderDao.findById(domainRouterVO.getElementId()); if (vrProvider == null) { throw new CloudRuntimeException( "Cannot find related virtual router provider of router: " + domainRouterVO.getHostName()); } final Provider provider = Network.Provider.getProvider(vrProvider.getType().toString()); if (provider == null) { throw new CloudRuntimeException( "Cannot find related provider of virtual router provider: " + vrProvider.getType().toString()); } for (final Pair<Nic, Network> nicNtwk : guestNics) { final Nic guestNic = nicNtwk.first(); final AggregationControlCommand startCmd = new AggregationControlCommand( Action.Start, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork( guestNic.getNetworkId(), domainRouterVO.getId())); cmds.addCommand(startCmd); if (reprogramGuestNtwks) { finalizeIpAssocForNetwork( cmds, domainRouterVO, provider, guestNic.getNetworkId(), vlanMacAddress); finalizeNetworkRulesForNetwork(cmds, domainRouterVO, provider, guestNic.getNetworkId()); } finalizeUserDataAndDhcpOnStart(cmds, domainRouterVO, provider, guestNic.getNetworkId()); final AggregationControlCommand finishCmd = new AggregationControlCommand( Action.Finish, domainRouterVO.getInstanceName(), controlNic.getIPv4Address(), _routerControlHelper.getRouterIpInNetwork( guestNic.getNetworkId(), domainRouterVO.getId())); cmds.addCommand(finishCmd); } // Add network usage commands cmds.addCommands(usageCmds); } return true; }