Search in sources :

Example 41 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class ApiResponseHelper method queryJobResult.

@Override
public AsyncJobResponse queryJobResult(final QueryAsyncJobResultCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    final AsyncJob job = this._entityMgr.findById(AsyncJob.class, cmd.getId());
    if (job == null) {
        throw new InvalidParameterValueException("Unable to find a job by id " + cmd.getId());
    }
    final User userJobOwner = this._accountMgr.getUserIncludingRemoved(job.getUserId());
    final Account jobOwner = this._accountMgr.getAccount(userJobOwner.getAccountId());
    // check permissions
    if (this._accountMgr.isNormalUser(caller.getId())) {
        // regular user can see only jobs he owns
        if (caller.getId() != jobOwner.getId()) {
            throw new PermissionDeniedException("Account " + caller + " is not authorized to see job id=" + job.getId());
        }
    } else if (this._accountMgr.isDomainAdmin(caller.getId())) {
        this._accountMgr.checkAccess(caller, null, true, jobOwner);
    }
    return createAsyncJobResponse(this._jobMgr.queryJob(cmd.getId(), true));
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) VpnUser(com.cloud.legacymodel.network.VpnUser) User(com.cloud.legacymodel.user.User) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) AsyncJob(com.cloud.framework.jobs.AsyncJob)

Example 42 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class ApiServer method checkCommandAvailable.

private void checkCommandAvailable(final User user, final String commandName, final String remoteAddress) throws PermissionDeniedException {
    if (user == null) {
        throw new PermissionDeniedException("User is null for role based API access check for command" + commandName);
    }
    // Get the CIDRs from where this account is allowed to make calls
    final Account account = _accountMgr.getAccount(user.getAccountId());
    final String accessAllowedCidrs = ApiServiceConfiguration.ApiAllowedSourceCidrList.valueIn(account.getId()).replaceAll("\\s", "");
    final Boolean ApiSourceCidrChecksEnabled = ApiServiceConfiguration.ApiSourceCidrChecksEnabled.value();
    if (ApiSourceCidrChecksEnabled) {
        s_logger.debug("CIDRs from which account '" + account.toString() + "' is allowed to perform API calls: " + accessAllowedCidrs);
        InetAddress hostName = null;
        try {
            hostName = InetAddress.getByName(remoteAddress);
        } catch (final UnknownHostException e) {
            s_logger.warn("UnknownHostException when trying to lookup ip-address. Something is seriously wrong here. Blocking access.", e);
        }
        // Block when is not in the list of allowed IPs, or when hostname is unknown (didn't resolve to ip address)
        if (hostName == null || !NetUtils.isIpInCidrList(hostName, accessAllowedCidrs.split(","))) {
            s_logger.warn("Request by account '" + account.toString() + "' was denied since " + remoteAddress + " does not match " + accessAllowedCidrs);
            throw new PermissionDeniedException("Calls for domain '" + account.getAccountName() + "' are not allowed from ip address '" + remoteAddress.replaceAll("/", "") + "'.");
        }
    }
    for (final APIChecker apiChecker : _apiAccessCheckers) {
        apiChecker.checkAccess(user, commandName);
    }
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) UnknownHostException(java.net.UnknownHostException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) InetAddress(java.net.InetAddress) APIChecker(com.cloud.acl.APIChecker)

Example 43 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class ApiServer method handleRequest.

@Override
public String handleRequest(final Map params, final String responseType, final StringBuilder auditTrailSb) throws ServerApiException {
    checkCharacterInkParams(params);
    final String response;
    String[] command = null;
    try {
        command = (String[]) params.get("command");
        if (command == null) {
            s_logger.error("invalid request, no command sent");
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("dumping request parameters");
                for (final Object key : params.keySet()) {
                    final String keyStr = (String) key;
                    final String[] value = (String[]) params.get(key);
                    s_logger.trace("   key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0]));
                }
            }
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent");
        } else {
            // Don't allow Login/Logout APIs to go past this point
            if (_authManager.getAPIAuthenticator(command[0]) != null) {
                return null;
            }
            final Map<String, String> paramMap = new HashMap<>();
            final Set keys = params.keySet();
            final Iterator keysIter = keys.iterator();
            while (keysIter.hasNext()) {
                final String key = (String) keysIter.next();
                if ("command".equalsIgnoreCase(key)) {
                    continue;
                }
                final String[] value = (String[]) params.get(key);
                paramMap.put(key, value[0]);
            }
            final Class<?> cmdClass = getCmdClass(command[0]);
            if (cmdClass != null) {
                final APICommand annotation = cmdClass.getAnnotation(APICommand.class);
                if (annotation == null) {
                    s_logger.error("No APICommand annotation found for class " + cmdClass.getCanonicalName());
                    throw new CloudRuntimeException("No APICommand annotation found for class " + cmdClass.getCanonicalName());
                }
                BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
                cmdObj = ComponentContext.inject(cmdObj);
                cmdObj.configure();
                cmdObj.setFullUrlParams(paramMap);
                cmdObj.setResponseType(responseType);
                cmdObj.setHttpMethod(paramMap.get(ApiConstants.HTTPMETHOD).toString());
                // This is where the command is either serialized, or directly dispatched
                final StringBuilder log = new StringBuilder();
                response = queueCommand(cmdObj, paramMap, log);
                buildAuditTrail(auditTrailSb, command[0], log.toString());
            } else {
                final String errorString = "Unknown API command: " + command[0];
                s_logger.warn(errorString);
                auditTrailSb.append(" " + errorString);
                throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString);
            }
        }
    } catch (final InvalidParameterValueException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (final IllegalArgumentException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
    } catch (final PermissionDeniedException ex) {
        final ArrayList<ExceptionProxyObject> idList = ex.getIdProxyList();
        if (idList != null) {
            final StringBuffer buf = new StringBuffer();
            for (final ExceptionProxyObject obj : idList) {
                buf.append(obj.getDescription());
                buf.append(":");
                buf.append(obj.getUuid());
                buf.append(" ");
            }
            s_logger.info("PermissionDenied: " + ex.getMessage() + " on objs: [" + buf.toString() + "]");
        } else {
            s_logger.info("PermissionDenied: " + ex.getMessage());
        }
        throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex);
    } catch (final AccountLimitException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex);
    } catch (final InsufficientCapacityException ex) {
        s_logger.info(ex.getMessage());
        String errorMsg = ex.getMessage();
        if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex);
    } catch (final ResourceAllocationException ex) {
        s_logger.info(ex.getMessage());
        throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage(), ex);
    } catch (final ResourceUnavailableException ex) {
        s_logger.info(ex.getMessage());
        String errorMsg = ex.getMessage();
        if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex);
    } catch (final ServerApiException ex) {
        s_logger.info(ex.getDescription());
        throw ex;
    } catch (final Exception ex) {
        s_logger.error("Unhandled exception executing api command: " + ((command == null) ? "null" : printCommand(command)), ex);
        String errorMsg = ex.getMessage();
        if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
            // hide internal details to non-admin user for security reason
            errorMsg = BaseCmd.USER_ERROR_MESSAGE;
        }
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex);
    }
    return response;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) EventBusException(com.cloud.framework.events.EventBusException) HttpException(org.apache.http.HttpException) AccountLimitException(com.cloud.legacymodel.exceptions.AccountLimitException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) RequestLimitException(com.cloud.legacymodel.exceptions.RequestLimitException) URISyntaxException(java.net.URISyntaxException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ParseException(java.text.ParseException) CloudAuthenticationException(com.cloud.legacymodel.exceptions.CloudAuthenticationException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConnectionClosedException(org.apache.http.ConnectionClosedException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Iterator(java.util.Iterator) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ExceptionProxyObject(com.cloud.legacymodel.exceptions.ExceptionProxyObject) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ExceptionProxyObject(com.cloud.legacymodel.exceptions.ExceptionProxyObject) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) AccountLimitException(com.cloud.legacymodel.exceptions.AccountLimitException)

Example 44 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method createPhysicalNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true)
public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List<String> isolationMethods, final String broadcastDomainRangeStr, final Long domainId, final List<String> tags, final String name) {
    // Check if zone exists
    if (zoneId == null) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    final Zone zone = zoneRepository.findById(zoneId).orElse(null);
    if (zone == null) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    if (AllocationState.Enabled == zone.getAllocationState()) {
        // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
        throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId);
    }
    final NetworkType zoneType = zone.getNetworkType();
    if (zoneType == NetworkType.Basic) {
        if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) {
            // TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
            throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic " + "Zone");
        }
    }
    if (tags != null && tags.size() > 1) {
        throw new InvalidParameterException("Only one tag can be specified for a physical network at this time");
    }
    if (isolationMethods != null && isolationMethods.size() > 1) {
        throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time");
    }
    if (vnetRange != null) {
        // Verify zone type
        if (zoneType == NetworkType.Basic) {
            throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network");
        }
    }
    BroadcastDomainRange broadcastDomainRange = null;
    if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) {
        try {
            broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase());
        } catch (final IllegalArgumentException ex) {
            throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}");
        }
        // in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic
        if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) {
            throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only");
        } else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) {
            throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only");
        }
    }
    if (broadcastDomainRange == null) {
        if (zoneType == NetworkType.Basic) {
            broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.POD;
        } else {
            broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.ZONE;
        }
    }
    try {
        final BroadcastDomainRange broadcastDomainRangeFinal = broadcastDomainRange;
        return Transaction.execute(new TransactionCallback<PhysicalNetworkVO>() {

            @Override
            public PhysicalNetworkVO doInTransaction(final TransactionStatus status) {
                // Create the new physical network in the database
                final long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
                PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name);
                pNetwork.setTags(tags);
                pNetwork.setIsolationMethods(isolationMethods);
                pNetwork = _physicalNetworkDao.persist(pNetwork);
                // Add vnet entries for the new zone if zone type is Advanced
                if (vnetRange != null) {
                    addOrRemoveVnets(vnetRange.split(","), pNetwork);
                }
                // add VirtualRouter as the default network service provider
                addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
                // add VPCVirtualRouter as the default network service provider
                addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
                return pNetwork;
            }
        });
    } catch (final Exception ex) {
        s_logger.warn("Exception: ", ex);
        throw new CloudRuntimeException("Fail to create a physical network");
    }
}
Also used : Zone(com.cloud.db.model.Zone) BroadcastDomainRange(com.cloud.network.PhysicalNetwork.BroadcastDomainRange) TransactionStatus(com.cloud.utils.db.TransactionStatus) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) SQLException(java.sql.SQLException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) UnknownHostException(java.net.UnknownHostException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) UnsupportedServiceException(com.cloud.legacymodel.exceptions.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InvalidParameterException(java.security.InvalidParameterException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) NetworkType(com.cloud.model.enumeration.NetworkType) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 45 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class NetworkServiceImpl method createGuestNetwork.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network")
public Network createGuestNetwork(final CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
    final Long networkOfferingId = cmd.getNetworkOfferingId();
    String gateway = cmd.getGateway();
    final String startIP = cmd.getStartIp();
    String endIP = cmd.getEndIp();
    final String netmask = cmd.getNetmask();
    final String networkDomain = cmd.getNetworkDomain();
    final String vlanId = cmd.getVlan();
    final String name = cmd.getNetworkName();
    final String displayText = cmd.getDisplayText();
    final Account caller = CallContext.current().getCallingAccount();
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    Long zoneId = cmd.getZoneId();
    final String aclTypeStr = cmd.getAclType();
    final Long domainId = cmd.getDomainId();
    boolean isDomainSpecific = false;
    final Boolean subdomainAccess = cmd.getSubdomainAccess();
    final Long vpcId = cmd.getVpcId();
    final String startIPv6 = cmd.getStartIpv6();
    String endIPv6 = cmd.getEndIpv6();
    String ip6Gateway = cmd.getIp6Gateway();
    final String ip6Cidr = cmd.getIp6Cidr();
    Boolean displayNetwork = cmd.getDisplayNetwork();
    final Long aclId = cmd.getAclId();
    final String isolatedPvlan = cmd.getIsolatedPvlan();
    final String dns1 = cmd.getDns1();
    final String dns2 = cmd.getDns2();
    final String ipExclusionList = cmd.getIpExclusionList();
    final String getDhcpTftpServer = cmd.getDhcpTftpServer();
    final String getDhcpBootfileName = cmd.getDhcpBootfileName();
    // Validate network offering
    final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
    if (ntwkOff == null || ntwkOff.isSystemOnly()) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id");
        if (ntwkOff != null) {
            ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
        }
        throw ex;
    }
    if (!GuestType.Private.equals(ntwkOff.getGuestType()) && vpcId == null) {
        throw new InvalidParameterValueException("VPC ID is required");
    }
    if (GuestType.Private.equals(ntwkOff.getGuestType()) && (startIP != null || endIP != null || vpcId != null || gateway != null || netmask != null)) {
        throw new InvalidParameterValueException("StartIp/endIp/vpcId/gateway/netmask can't be specified for guest type " + GuestType.Private);
    }
    // validate physical network and zone
    // Check if physical network exists
    PhysicalNetwork pNtwk = null;
    if (physicalNetworkId != null) {
        pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
        if (pNtwk == null) {
            throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id");
        }
    }
    if (zoneId == null) {
        zoneId = pNtwk.getDataCenterId();
    }
    if (displayNetwork == null) {
        displayNetwork = true;
    }
    final Zone zone = zoneRepository.findById(zoneId).orElse(null);
    if (zone == null) {
        throw new InvalidParameterValueException("Specified zone id was not found");
    }
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        // See DataCenterVO.java
        final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
        ex.addProxyObject(zone.getUuid(), "zoneId");
        throw ex;
    }
    // Only domain and account ACL types are supported in Acton.
    ACLType aclType = null;
    if (aclTypeStr != null) {
        if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) {
            aclType = ACLType.Account;
        } else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) {
            aclType = ACLType.Domain;
        } else {
            throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types");
        }
        // In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account
        if (ntwkOff.getGuestType() != GuestType.Shared) {
            if (aclType != ACLType.Account) {
                throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + ntwkOff.getGuestType());
            }
        } else if (ntwkOff.getGuestType() == GuestType.Shared) {
            if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) {
                throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + GuestType.Shared);
            }
        }
    } else {
        aclType = (ntwkOff.getGuestType() == GuestType.Shared) ? ACLType.Domain : ACLType.Account;
    }
    // Only Admin can create Shared networks
    if (ntwkOff.getGuestType() == GuestType.Shared && !_accountMgr.isAdmin(caller.getId())) {
        throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared);
    }
    // Check if the network is domain specific
    if (aclType == ACLType.Domain) {
        // only Admin can create domain with aclType=Domain
        if (!_accountMgr.isAdmin(caller.getId())) {
            throw new PermissionDeniedException("Only admin can create networks with aclType=Domain");
        }
        // only shared networks can be Domain specific
        if (ntwkOff.getGuestType() != GuestType.Shared) {
            throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain);
        }
        if (domainId != null) {
            if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != GuestType.Shared) {
                throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " + GuestType.Shared);
            }
            final DomainVO domain = _domainDao.findById(domainId);
            if (domain == null) {
                throw new InvalidParameterValueException("Unable to find domain by specified id");
            }
            _accountMgr.checkAccess(caller, domain);
        }
        isDomainSpecific = true;
    } else if (subdomainAccess != null) {
        throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain");
    }
    Account owner = null;
    if (cmd.getAccountName() != null && domainId != null || cmd.getProjectId() != null) {
        owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), domainId, cmd.getProjectId());
    } else {
        owner = caller;
    }
    boolean ipv4 = true, ipv6 = false;
    if (startIP != null) {
        ipv4 = true;
    }
    if (startIPv6 != null) {
        ipv6 = true;
    }
    if (gateway != null) {
        try {
            // getByName on a literal representation will only check validity of the address
            // http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#getByName(java.lang.String)
            final InetAddress gatewayAddress = InetAddress.getByName(gateway);
            if (gatewayAddress instanceof Inet6Address) {
                ipv6 = true;
            } else {
                ipv4 = true;
            }
        } catch (final UnknownHostException e) {
            s_logger.error("Unable to convert gateway IP to a InetAddress", e);
            throw new InvalidParameterValueException("Gateway parameter is invalid");
        }
    }
    String cidr = cmd.getCidr();
    if (ipv4) {
        // validate the CIDR
        if (cidr != null && !NetUtils.isValidIp4Cidr(cidr)) {
            throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
        }
        // validate gateway with cidr
        if (cidr != null && gateway != null && !NetUtils.isIpWithtInCidrRange(gateway, cidr)) {
            throw new InvalidParameterValueException("The gateway ip " + gateway + " should be part of the CIDR of the network " + cidr);
        }
        // if end ip is not specified, default it to startIp
        if (startIP != null) {
            if (!NetUtils.isValidIp4(startIP)) {
                throw new InvalidParameterValueException("Invalid format for the startIp parameter");
            }
            if (endIP == null) {
                endIP = startIP;
            } else if (!NetUtils.isValidIp4(endIP)) {
                throw new InvalidParameterValueException("Invalid format for the endIp parameter");
            }
        }
        if (startIP != null && endIP != null) {
            if (!(gateway != null && netmask != null)) {
                throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in");
            }
        }
        if (gateway != null && netmask != null) {
            if (NetUtils.isNetworkorBroadcastIP(gateway, netmask)) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("The gateway IP provided is " + gateway + " and netmask is " + netmask + ". The IP is either broadcast or network IP.");
                }
                throw new InvalidParameterValueException("Invalid gateway IP provided. Either the IP is broadcast or network IP.");
            }
            if (!NetUtils.isValidIp4(gateway)) {
                throw new InvalidParameterValueException("Invalid gateway");
            }
            if (!NetUtils.isValidIp4Netmask(netmask)) {
                throw new InvalidParameterValueException("Invalid netmask");
            }
            cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
        }
        checkIpExclusionList(ipExclusionList, cidr, null);
    }
    if (ipv6) {
        // validate the ipv6 CIDR
        if (ip6Cidr != null && !NetUtils.isValidIp4Cidr(ip6Cidr)) {
            throw new InvalidParameterValueException("Invalid format for the CIDR parameter");
        }
        if (endIPv6 == null) {
            endIPv6 = startIPv6;
        }
        _networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
        if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != GuestType.Shared) {
            throw new InvalidParameterValueException("Can only support create IPv6 network with advance shared network!");
        }
    }
    if (isolatedPvlan != null && (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != GuestType.Shared)) {
        throw new InvalidParameterValueException("Can only support create Private VLAN network with advance shared network!");
    }
    if (isolatedPvlan != null && ipv6) {
        throw new InvalidParameterValueException("Can only support create Private VLAN network with IPv4!");
    }
    // Regular user can create Guest Isolated Source Nat enabled network only
    if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != GuestType.Isolated && areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) {
        throw new InvalidParameterValueException("Regular user can create a network only from the network offering having traffic type " + TrafficType.Guest + " and network type " + GuestType.Isolated + " with a service " + Service.SourceNat.getName() + " enabled");
    }
    // Don't allow to specify vlan if the caller is a normal user
    if (_accountMgr.isNormalUser(caller.getId()) && (ntwkOff.getSpecifyVlan() || vlanId != null)) {
        throw new InvalidParameterValueException("Only ROOT admin and domain admins are allowed to specify vlanId");
    }
    if (ipv4) {
        // For non-root admins check cidr limit - if it's allowed by global config value
        if (!_accountMgr.isRootAdmin(caller.getId()) && cidr != null) {
            final String[] cidrPair = cidr.split("\\/");
            final int cidrSize = Integer.parseInt(cidrPair[1]);
            if (cidrSize < _cidrLimit) {
                throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
            }
        }
    }
    // Vlan is created in 1 cases - works in Advance zone only:
    // 1) GuestType is Shared
    boolean createVlan = startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced && (ntwkOff.getGuestType() == GuestType.Shared || !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat));
    if (!createVlan) {
        // Only support advance shared network in IPv6, which means createVlan is a must
        if (ipv6) {
            createVlan = true;
        }
    }
    // Can add vlan range only to the network which allows it
    if (createVlan && !ntwkOff.getSpecifyIpRanges()) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Network offering with specified id doesn't support adding multiple ip ranges");
        ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
        throw ex;
    }
    if (ntwkOff.getGuestType() != GuestType.Private && gateway == null && cidr != null) {
        gateway = NetUtils.getCidrHostAddress(cidr);
    }
    if (ntwkOff.getGuestType() != GuestType.Private && ip6Gateway == null && ip6Cidr != null) {
        ip6Gateway = NetUtils.getCidrHostAddress6(ip6Cidr);
    }
    if (ntwkOff.getGuestType() == GuestType.Private && (dns1 != null || dns2 != null)) {
        throw new InvalidParameterValueException("Network of type Private does not support setting DNS servers");
    }
    Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, name, displayText, caller, physicalNetworkId, zoneId, domainId, isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, isolatedPvlan, ntwkOff, pNtwk, aclType, owner, cidr, createVlan, dns1, dns2, ipExclusionList, getDhcpTftpServer, getDhcpBootfileName);
    // if the network offering has persistent set to true, implement the network
    if (ntwkOff.getIsPersistent()) {
        try {
            if (network.getState() == Network.State.Setup) {
                s_logger.debug("Network id=" + network.getId() + " is already provisioned");
                return network;
            }
            final DeployDestination dest = new DeployDestination(zone, null, null, null);
            final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
            final Journal journal = new Journal.LogJournal("Implementing " + network, s_logger);
            final ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
            s_logger.debug("Implementing network " + network + " as a part of network provision for persistent network");
            final Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(network.getId(), dest, context);
            if (implementedNetwork == null || implementedNetwork.first() == null) {
                s_logger.warn("Failed to provision the network " + network);
            }
            network = implementedNetwork.second();
        } catch (final ResourceUnavailableException ex) {
            s_logger.warn("Failed to implement persistent guest network " + network + "due to: " + ex.getMessage());
            final CloudRuntimeException e = new CloudRuntimeException("Failed to implement persistent guest network", ex);
            e.addProxyObject(network.getUuid(), "networkId");
            throw e;
        }
    }
    return network;
}
Also used : Account(com.cloud.legacymodel.user.Account) Journal(com.cloud.utils.Journal) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) ACLType(com.cloud.legacymodel.acl.ControlledEntity.ACLType) UnknownHostException(java.net.UnknownHostException) Zone(com.cloud.db.model.Zone) Inet6Address(java.net.Inet6Address) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) DeployDestination(com.cloud.deploy.DeployDestination) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) InetAddress(java.net.InetAddress) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)73 Account (com.cloud.legacymodel.user.Account)64 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)59 ActionEvent (com.cloud.event.ActionEvent)26 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)25 ArrayList (java.util.ArrayList)14 UserAccount (com.cloud.legacymodel.user.UserAccount)13 DB (com.cloud.utils.db.DB)13 DataCenterVO (com.cloud.dc.DataCenterVO)11 HashMap (java.util.HashMap)11 DomainVO (com.cloud.domain.DomainVO)9 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)9 Project (com.cloud.projects.Project)9 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)8 Pair (com.cloud.legacymodel.utils.Pair)8 VMTemplateVO (com.cloud.storage.VMTemplateVO)8 TransactionStatus (com.cloud.utils.db.TransactionStatus)8 List (java.util.List)8 Domain (com.cloud.legacymodel.domain.Domain)7 VolumeVO (com.cloud.storage.VolumeVO)7