@Override public TemplateProfile prepare(RegisterTemplateCmd cmd) throws ResourceAllocationException { // check if the caller can operate with the template owner Account caller = UserContext.current().getCaller(); Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); _accountMgr.checkAccess(caller, null, owner); return prepare( false, UserContext.current().getCallerUserId(), cmd.getTemplateName(), cmd.getDisplayText(), cmd.getBits(), cmd.isPasswordEnabled(), cmd.getRequiresHvm(), cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), cmd.getFormat(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.getType(cmd.getHypervisor()), cmd.getChecksum(), true, cmd.getTemplateTag(), owner, cmd.getDetails()); }
public TemplateProfile prepare(RegisterIsoCmd cmd) throws ResourceAllocationException { // check if the caller can operate with the template owner Account caller = UserContext.current().getCaller(); Account owner = _accountMgr.getAccount(cmd.getEntityOwnerId()); _accountMgr.checkAccess(caller, null, owner); return prepare( true, UserContext.current().getCallerUserId(), cmd.getIsoName(), cmd.getDisplayText(), 64, false, true, cmd.getUrl(), cmd.isPublic(), cmd.isFeatured(), cmd.isExtractable(), ImageFormat.ISO.toString(), cmd.getOsTypeId(), cmd.getZoneId(), HypervisorType.None, cmd.getChecksum(), cmd.isBootable(), null, owner, null); }
public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) { Long templateId = cmd.getId(); Long userId = UserContext.current().getCallerUserId(); Account account = UserContext.current().getCaller(); Long zoneId = cmd.getZoneId(); VMTemplateVO template = _tmpltDao.findById(templateId.longValue()); if (template == null) { throw new InvalidParameterValueException("unable to find template with id " + templateId); } userId = accountAndUserValidation(account, userId, null, template, "Unable to delete template "); UserVO user = _userDao.findById(userId); if (user == null) { throw new InvalidParameterValueException("Please specify a valid user."); } if (template.getFormat() == ImageFormat.ISO) { throw new InvalidParameterValueException("Please specify a valid template."); } return new TemplateProfile(userId, template, zoneId); }
public Long getDomainId() { if (domainId != null) { return domainId; } else { return UserContext.current().getCaller().getDomainId(); } }
public String getAccountName() { if (accountName != null) { return accountName; } else { return UserContext.current().getCaller().getAccountName(); } }
@Override public void execute() { UserVm result; try { UserContext.current().setEventDetails("Vm Id: " + getEntityId()); if (getHypervisor() == HypervisorType.BareMetal) { result = _bareMetalVmService.startVirtualMachine(this); } else { result = _userVmService.startVirtualMachine(this); } if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to deploy vm"); } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } }
@Override public void interceptComplete(AnnotatedElement element, EventVO event) { Method method = (Method) element; ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); if (actionEvent != null) { UserContext ctx = UserContext.current(); long userId = ctx.getCallerUserId(); long accountId = ctx.getAccountId(); long startEventId = ctx.getStartEventId(); String eventDescription = actionEvent.eventDescription(); if (ctx.getEventDetails() != null) { eventDescription += ". " + ctx.getEventDetails(); } if (actionEvent.create()) { // This start event has to be used for subsequent events of this action startEventId = EventUtils.saveCreatedEvent( userId, accountId, EventVO.LEVEL_INFO, actionEvent.eventType(), "Successfully created entity for " + eventDescription); ctx.setStartEventId(startEventId); } else { EventUtils.saveEvent( userId, accountId, EventVO.LEVEL_INFO, actionEvent.eventType(), "Successfully completed " + eventDescription, startEventId); } } }
@Override public void interceptException(AnnotatedElement element, EventVO event) { Method method = (Method) element; ActionEvent actionEvent = method.getAnnotation(ActionEvent.class); if (actionEvent != null) { UserContext ctx = UserContext.current(); long userId = ctx.getCallerUserId(); long accountId = ctx.getAccountId(); long startEventId = ctx.getStartEventId(); String eventDescription = actionEvent.eventDescription(); if (ctx.getEventDetails() != null) { eventDescription += ". " + ctx.getEventDetails(); } if (actionEvent.create()) { long eventId = EventUtils.saveCreatedEvent( userId, accountId, EventVO.LEVEL_ERROR, actionEvent.eventType(), "Error while creating entity for " + eventDescription); ctx.setStartEventId(eventId); } else { EventUtils.saveEvent( userId, accountId, EventVO.LEVEL_ERROR, actionEvent.eventType(), "Error while " + eventDescription, startEventId); } } }
@Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { try { UserContext.current().setEventDetails("Vm Id: " + getId()); UserVm result; result = _userVmService.startVirtualMachine(this); if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to start a vm"); } } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } catch (StorageUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ExecutionException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } }
@Override public boolean processDisconnect(long agentId, Status state) { UserContext context = UserContext.current(); context.setAccountId(1); /* Stopped VMware Host's virtual routers */ HostVO host = _hostDao.findById(agentId); if (host.getHypervisorType() != HypervisorType.VMware) { return true; } List<DomainRouterVO> routers = _routerDao.listByHostId(agentId); for (DomainRouterVO router : routers) { try { State oldState = router.getState(); _routerMgr.stopRouter(router.getId(), true); // In case only vCenter is disconnected, we want to shut down router directly if (oldState == State.Running) { shutdownRouterVM(router); } } catch (ResourceUnavailableException e) { s_logger.warn( "Fail to stop router " + router.getInstanceName() + " when host disconnected!", e); } catch (ConcurrentOperationException e) { s_logger.warn( "Fail to stop router " + router.getInstanceName() + " when host disconnected!", e); } } return true; }
@Override public List<? extends VpnUser> listVpnUsers(long vpnOwnerId, String userName) { Account caller = UserContext.current().getCaller(); Account owner = _accountDao.findById(vpnOwnerId); _accountMgr.checkAccess(caller, null, true, owner); return _vpnUsersDao.listByAccount(vpnOwnerId); }
@Override @DB @ActionEvent( eventType = EventTypes.EVENT_LOAD_BALANCER_CREATE, eventDescription = "creating load balancer") public LoadBalancer createLoadBalancerRule(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException, InsufficientAddressCapacityException { UserContext caller = UserContext.current(); int defPortStart = lb.getDefaultPortStart(); int defPortEnd = lb.getDefaultPortEnd(); if (!NetUtils.isValidPort(defPortEnd)) { throw new InvalidParameterValueException("privatePort is an invalid value: " + defPortEnd); } if (defPortStart > defPortEnd) { throw new InvalidParameterValueException( "private port range is invalid: " + defPortStart + "-" + defPortEnd); } if ((lb.getAlgorithm() == null) || !NetUtils.isValidAlgorithm(lb.getAlgorithm())) { throw new InvalidParameterValueException("Invalid algorithm: " + lb.getAlgorithm()); } LoadBalancer result = _elbMgr.handleCreateLoadBalancerRule(lb, caller.getCaller()); if (result == null) { result = createLoadBalancer(lb, openFirewall); } return result; }
@Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, null, true); if (accountId == null) { accountId = UserContext.current().getCaller().getId(); } return accountId; }
@Override public long getEntityOwnerId() { Long accountId = getAccountId(accountName, domainId, projectId); if (accountId == null) { return UserContext.current().getCaller().getId(); } return accountId; }
@Override @DB public RemoteAccessVpnVO startRemoteAccessVpn(long vpnId, boolean openFirewall) throws ResourceUnavailableException { Account caller = UserContext.current().getCaller(); RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(vpnId); if (vpn == null) { throw new InvalidParameterValueException("Unable to find your vpn: " + vpnId); } _accountMgr.checkAccess(caller, null, true, vpn); Network network = _networkMgr.getNetwork(vpn.getNetworkId()); boolean started = false; try { boolean firewallOpened = true; if (openFirewall) { firewallOpened = _firewallMgr.applyIngressFirewallRules(vpn.getServerAddressId(), caller); } if (firewallOpened) { for (RemoteAccessVPNServiceProvider element : _vpnServiceProviders) { if (element.startVpn(network, vpn)) { started = true; break; } } } return vpn; } finally { if (started) { Transaction txn = Transaction.currentTxn(); txn.start(); vpn.setState(RemoteAccessVpn.State.Running); _remoteAccessVpnDao.update(vpn.getServerAddressId(), vpn); // Start billing of existing VPN users in ADD and Active state List<VpnUserVO> vpnUsers = _vpnUsersDao.listByAccount(vpn.getAccountId()); for (VpnUserVO user : vpnUsers) { if (user.getState() != VpnUser.State.Revoke) { UsageEventUtils.publishUsageEvent( EventTypes.EVENT_VPN_USER_ADD, user.getAccountId(), 0, user.getId(), user.getUsername(), user.getClass().getName(), user.getUuid()); } } txn.commit(); } } }
@Override public void execute() { UserContext.current().setEventDetails("Project Id: " + id); boolean result = _projectService.deleteProject(id); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete project"); } }
@Override public void execute() { UserContext.current().setEventDetails("Load balancer Id: " + getId()); boolean result = _lbService.deleteLoadBalancerRule(id, true); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer"); } }
@Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); if (account != null) { return account.getId(); } return Account .ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events // are tracked }
@Override public void create() throws ResourceAllocationException { UserContext.current().setEventDetails("Project Name: " + getName()); Project project = _projectService.createProject(getName(), getDisplayText(), getAccountName(), getDomainId()); if (project != null) { this.setEntityId(project.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a project"); } }
@Override public void execute() { UserContext.current().setEventDetails("Domain Id: " + getId()); Domain domain = _mgr.updateDomain(this); if (domain != null) { DomainResponse response = _responseGenerator.createDomainResponse(domain); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update domain"); } }
@Override public List<UserVmVO> listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException { Account caller = UserContext.current().getCaller(); Long loadBalancerId = cmd.getId(); Boolean applied = cmd.isApplied(); if (applied == null) { applied = Boolean.TRUE; } LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId); if (loadBalancer == null) { return null; } _accountMgr.checkAccess(caller, null, loadBalancer); List<UserVmVO> loadBalancerInstances = new ArrayList<UserVmVO>(); List<LoadBalancerVMMapVO> vmLoadBalancerMappings = null; vmLoadBalancerMappings = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId); List<Long> appliedInstanceIdList = new ArrayList<Long>(); if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) { for (LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) { appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId()); } } IPAddressVO addr = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()); List<UserVmVO> userVms = _vmDao.listVirtualNetworkInstancesByAcctAndZone( loadBalancer.getAccountId(), addr.getDataCenterId(), loadBalancer.getNetworkId()); for (UserVmVO userVm : userVms) { // if the VM is destroyed, being expunged, in an error state, or in an unknown state, skip it switch (userVm.getState()) { case Destroyed: case Expunging: case Error: case Unknown: continue; } boolean isApplied = appliedInstanceIdList.contains(userVm.getId()); if ((isApplied && applied) || (!isApplied && !applied)) { loadBalancerInstances.add(userVm); } } return loadBalancerInstances; }
@Override public void execute() { UserContext.current().setEventDetails("Vm Id: " + getId()); VirtualMachine instance = _mgr.startSystemVM(getId()); if (instance != null) { SystemVmResponse response = _responseGenerator.createSystemVmResponse(instance); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to start system vm"); } }
@Override public void execute() throws ResourceUnavailableException, ConcurrentOperationException { UserContext.current().setEventDetails("Vm Id: " + getId()); VirtualMachine result = _mgr.stopSystemVM(this); if (result != null) { SystemVmResponse response = _responseGenerator.createSystemVmResponse(result); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Fail to stop system vm"); } }
@Override public void execute() { UserContext.current().setEventDetails("Load balancer stickiness policy Id: " + getId()); boolean result = _lbService.deleteLBStickinessPolicy(getId(), true); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException( ApiErrorCode.INTERNAL_ERROR, "Failed to delete load balancer stickiness policy"); } }
@Override public Pair<List<? extends VpnUser>, Integer> searchForVpnUsers(ListVpnUsersCmd cmd) { String username = cmd.getUsername(); Long id = cmd.getId(); Account caller = UserContext.current().getCaller(); List<Long> permittedAccounts = new ArrayList<Long>(); Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>( cmd.getDomainId(), cmd.isRecursive(), null); _accountMgr.buildACLSearchParameters( caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); Filter searchFilter = new Filter(VpnUserVO.class, "username", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder<VpnUserVO> sb = _vpnUsersDao.createSearchBuilder(); _accountMgr.buildACLSearchBuilder( sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.EQ); sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); SearchCriteria<VpnUserVO> sc = sb.create(); _accountMgr.buildACLSearchCriteria( sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); // list only active users sc.setParameters("state", State.Active); if (id != null) { sc.setParameters("id", id); } if (username != null) { sc.setParameters("username", username); } Pair<List<VpnUserVO>, Integer> result = _vpnUsersDao.searchAndCount(sc, searchFilter); return new Pair<List<? extends VpnUser>, Integer>(result.first(), result.second()); }
@Override public void execute() throws ResourceUnavailableException { boolean result = true; FirewallRule rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); if (getOpenFirewall()) { result = result && _firewallService.applyFirewallRules( ipAddressId, UserContext.current().getCaller()); } result = result && _rulesService.applyStaticNatRules(ipAddressId, UserContext.current().getCaller()); rule = _entityMgr.findById(FirewallRule.class, getEntityId()); StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false); IpForwardingRuleResponse fwResponse = _responseGenerator.createIpForwardingRuleResponse(staticNatRule); fwResponse.setResponseName(getCommandName()); this.setResponseObject(fwResponse); } finally { if (!result || rule == null) { if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } _rulesService.revokeStaticNatRule(getEntityId(), true); throw new ServerApiException( ApiErrorCode.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr"); } } }
@Override public void execute() { UserContext.current().setEventDetails("Rule Id: " + id); boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _rulesService.revokeStaticNatRule(id, true); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException( ApiErrorCode.INTERNAL_ERROR, "Failed to delete ip forwarding rule"); } }
@Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException { UserContext.current().setEventDetails("Vm Id: " + getId()); UserVm result = _userVmService.updateVirtualMachine(this); if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update vm"); } }
@Override public long getEntityOwnerId() { Account caller = UserContext.current().getCaller(); if ((accountName != null && domainId == null) || (domainId != null && accountName == null)) { throw new InvalidParameterValueException( "Account name and domain id must be specified together"); } if (accountName != null) { return _accountService.finalizeOwner(caller, accountName, domainId, null).getId(); } return caller.getId(); }
@Override @DB public boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd) { // input validation Account caller = UserContext.current().getCaller(); Long id = cmd.getId(); IngressRuleVO rule = _ingressRuleDao.findById(id); if (rule == null) { s_logger.debug("Unable to find ingress rule with id " + id); throw new InvalidParameterValueException("Unable to find ingress rule with id " + id); } // Check permissions SecurityGroup securityGroup = _securityGroupDao.findById(rule.getSecurityGroupId()); _accountMgr.checkAccess(caller, null, securityGroup); SecurityGroupVO groupHandle = null; final Transaction txn = Transaction.currentTxn(); try { txn.start(); // acquire lock on parent group (preserving this logic) groupHandle = _securityGroupDao.acquireInLockTable(rule.getSecurityGroupId()); if (groupHandle == null) { s_logger.warn("Could not acquire lock on security group id: " + rule.getSecurityGroupId()); return false; } _ingressRuleDao.remove(id); s_logger.debug("revokeSecurityGroupIngress succeeded for ingress rule id: " + id); final ArrayList<Long> affectedVms = new ArrayList<Long>(); affectedVms.addAll(_securityGroupVMMapDao.listVmIdsBySecurityGroup(groupHandle.getId())); scheduleRulesetUpdateToHosts(affectedVms, true, null); return true; } catch (Exception e) { s_logger.warn("Exception caught when deleting ingress rules ", e); throw new CloudRuntimeException("Exception caught when deleting ingress rules", e); } finally { if (groupHandle != null) { _securityGroupDao.releaseFromLockTable(groupHandle.getId()); } txn.commit(); } }