Search in sources :

Example 1 with ConfigurationVO

use of com.cloud.framework.config.impl.ConfigurationVO in project cosmic by MissionCriticalCloud.

the class ConfigKey method value.

public T value() {
    if (_value == null || isDynamic()) {
        final ConfigurationVO vo = s_depot != null ? s_depot.global().findById(key()) : null;
        _value = valueOf((vo != null && vo.getValue() != null) ? vo.getValue() : defaultValue());
    }
    return _value;
}
Also used : ConfigurationVO(com.cloud.framework.config.impl.ConfigurationVO)

Example 2 with ConfigurationVO

use of com.cloud.framework.config.impl.ConfigurationVO in project cosmic by MissionCriticalCloud.

the class ConfigurationDaoImpl method getValueAndInitIfNotExist.

@Override
@DB
public String getValueAndInitIfNotExist(final String name, final String category, final String initValue, final String desc) {
    String returnValue = initValue;
    try {
        final ConfigurationVO config = findByName(name);
        if (config != null) {
            if (config.getValue() != null) {
                returnValue = config.getValue();
            } else {
                update(name, category, initValue);
            }
        } else {
            final ConfigurationVO newConfig = new ConfigurationVO(category, "DEFAULT", "management-server", name, initValue, desc);
            persist(newConfig);
        }
        return returnValue;
    } catch (final Exception e) {
        s_logger.warn("Unable to update Configuration Value", e);
        throw new CloudRuntimeException("Unable to initialize configuration variable: " + name);
    }
}
Also used : ConfigurationVO(com.cloud.framework.config.impl.ConfigurationVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DB(com.cloud.utils.db.DB)

Example 3 with ConfigurationVO

use of com.cloud.framework.config.impl.ConfigurationVO in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method updateConfiguration.

@Override
@ActionEvent(eventType = EventTypes.EVENT_CONFIGURATION_VALUE_EDIT, eventDescription = "updating configuration")
public Configuration updateConfiguration(final UpdateCfgCmd cmd) throws InvalidParameterValueException {
    final Long userId = CallContext.current().getCallingUserId();
    final Account caller = CallContext.current().getCallingAccount();
    final User user = _userDao.findById(userId);
    final String name = cmd.getCfgName();
    String value = cmd.getValue();
    final Long zoneId = cmd.getZoneId();
    final Long clusterId = cmd.getClusterId();
    final Long storagepoolId = cmd.getStoragepoolId();
    final Long accountId = cmd.getAccountId();
    CallContext.current().setEventDetails(" Name: " + name + " New Value: " + (name.toLowerCase().contains("password") ? "*****" : value == null ? "" : value));
    // check if config value exists
    final ConfigurationVO config = _configDao.findByName(name);
    final String catergory;
    // FIX ME - All configuration parameters are not moved from config.java to configKey
    if (config == null) {
        if (_configDepot.get(name) == null) {
            s_logger.warn("Probably the component manager where configuration variable " + name + " is defined needs to implement Configurable interface");
            throw new InvalidParameterValueException("Config parameter with name " + name + " doesn't exist");
        }
        catergory = _configDepot.get(name).category();
    } else {
        catergory = config.getCategory();
    }
    if (value == null) {
        return _configDao.findByName(name);
    }
    value = value.trim();
    if (value.isEmpty() || value.equals("null")) {
        value = null;
    }
    String scope = null;
    Long id = null;
    int paramCountCheck = 0;
    // Non-ROOT may only update the Account scope
    if (!_accountMgr.isRootAdmin(caller.getId()) && accountId == null) {
        throw new InvalidParameterValueException("Please specify AccountId to update the config for the given account.");
    }
    if (accountId != null) {
        final Account accountToUpdate = _accountDao.findById(accountId);
        _accountMgr.checkAccess(caller, null, true, accountToUpdate);
        scope = ConfigKey.Scope.Account.toString();
        id = accountId;
        paramCountCheck++;
    }
    if (_accountMgr.isRootAdmin(caller.getId())) {
        if (zoneId != null) {
            scope = ConfigKey.Scope.Zone.toString();
            id = zoneId;
            paramCountCheck++;
        }
        if (clusterId != null) {
            scope = ConfigKey.Scope.Cluster.toString();
            id = clusterId;
            paramCountCheck++;
        }
        if (storagepoolId != null) {
            scope = ConfigKey.Scope.StoragePool.toString();
            id = storagepoolId;
            paramCountCheck++;
        }
    }
    if (paramCountCheck > 1) {
        throw new InvalidParameterValueException("cannot handle multiple IDs, provide only one ID corresponding to the scope");
    }
    final String updatedValue = updateConfiguration(userId, name, catergory, value, scope, id);
    if (value == null && updatedValue == null || updatedValue.equalsIgnoreCase(value)) {
        return _configDao.findByName(name);
    } else {
        throw new CloudRuntimeException("Unable to update configuration parameter " + name);
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) ConfigurationVO(com.cloud.framework.config.impl.ConfigurationVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ActionEvent(com.cloud.event.ActionEvent)

Example 4 with ConfigurationVO

use of com.cloud.framework.config.impl.ConfigurationVO in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerImpl method validateConfigurationValue.

private String validateConfigurationValue(final String name, String value, final String scope) {
    final ConfigurationVO cfg = _configDao.findByName(name);
    if (cfg == null) {
        s_logger.error("Missing configuration variable " + name + " in configuration table");
        return "Invalid configuration variable.";
    }
    final String configScope = cfg.getScope();
    if (scope != null) {
        if (!configScope.contains(scope)) {
            s_logger.error("Invalid scope id provided for the parameter " + name);
            return "Invalid scope id provided for the parameter " + name;
        }
    }
    final Class<?> type;
    final Config c = Config.getConfig(name);
    if (c == null) {
        s_logger.warn("Did not find configuration " + name + " in Config.java. Perhaps moved to ConfigDepot");
        final ConfigKey<?> configKey = _configDepot.get(name);
        if (configKey == null) {
            s_logger.warn("Did not find configuration " + name + " in ConfigDepot too.");
            return null;
        }
        type = configKey.type();
    } else {
        type = c.getType();
    }
    String errMsg = null;
    try {
        if (type.equals(Integer.class)) {
            errMsg = "There was error in trying to parse value: " + value + ". Please enter a valid integer value for parameter " + name;
            Integer.parseInt(value);
        } else if (type.equals(Float.class)) {
            errMsg = "There was error in trying to parse value: " + value + ". Please enter a valid float value for parameter " + name;
            Float.parseFloat(value);
        }
    } catch (final Exception e) {
        // catching generic exception as some throws NullPointerException and some throws NumberFormatExcpeion
        s_logger.error(errMsg);
        return errMsg;
    }
    if (value == null) {
        if (type.equals(Boolean.class)) {
            return "Please enter either 'true' or 'false'.";
        }
        if (overprovisioningFactorsForValidation.contains(name)) {
            final String msg = "value cannot be null for the parameter " + name;
            s_logger.error(msg);
            return msg;
        }
        return null;
    }
    value = value.trim();
    try {
        if (overprovisioningFactorsForValidation.contains(name) && Float.parseFloat(value) < 1f) {
            final String msg = name + " should be greater than or equal to 1";
            s_logger.error(msg);
            throw new InvalidParameterValueException(msg);
        }
    } catch (final NumberFormatException e) {
        final String msg = "There was an error trying to parse the float value for: " + name;
        s_logger.error(msg);
        throw new InvalidParameterValueException(msg);
    }
    if (type.equals(Boolean.class)) {
        if (!(value.equals("true") || value.equals("false"))) {
            s_logger.error("Configuration variable " + name + " is expecting true or false instead of " + value);
            return "Please enter either 'true' or 'false'.";
        }
        return null;
    }
    if (type.equals(Integer.class) && configValuesForValidation.contains(name)) {
        try {
            final int val = Integer.parseInt(value);
            if (val <= 0) {
                throw new InvalidParameterValueException("Please enter a positive value for the configuration parameter:" + name);
            }
            // TODO - better validation for all password pamameters
            if ("vm.password.length".equalsIgnoreCase(name) && val < 10) {
                throw new InvalidParameterValueException("Please enter a value greater than 6 for the configuration parameter:" + name);
            }
            if ("remote.access.vpn.psk.length".equalsIgnoreCase(name)) {
                if (val < 8) {
                    throw new InvalidParameterValueException("Please enter a value greater than 8 for the configuration parameter:" + name);
                }
                if (val > 256) {
                    throw new InvalidParameterValueException("Please enter a value less than 256 for the configuration parameter:" + name);
                }
            }
        } catch (final NumberFormatException e) {
            s_logger.error("There was an error trying to parse the integer value for:" + name);
            throw new InvalidParameterValueException("There was an error trying to parse the integer value for:" + name);
        }
    }
    if (type.equals(Float.class)) {
        try {
            final Float val = Float.parseFloat(value);
            if (weightBasedParametersForValidation.contains(name) && (val < 0f || val > 1f)) {
                throw new InvalidParameterValueException("Please enter a value between 0 and 1 for the configuration parameter: " + name);
            }
        } catch (final NumberFormatException e) {
            s_logger.error("There was an error trying to parse the float value for:" + name);
            throw new InvalidParameterValueException("There was an error trying to parse the float value for:" + name);
        }
    }
    if (c == null) {
        // return in case of Configkey parameters
        return null;
    }
    final String range = c.getRange();
    if (range == null) {
        return null;
    }
    if (type.equals(String.class)) {
        if (range.equals("privateip")) {
            try {
                if (!NetUtils.isSiteLocalAddress(value)) {
                    s_logger.error("privateip range " + value + " is not a site local address for configuration variable " + name);
                    return "Please enter a site local IP address.";
                }
            } catch (final NullPointerException e) {
                s_logger.error("Error parsing ip address for " + name);
                throw new InvalidParameterValueException("Error parsing ip address");
            }
        } else if (range.equals("netmask")) {
            if (!NetUtils.isValidIp4Netmask(value)) {
                s_logger.error("netmask " + value + " is not a valid net mask for configuration variable " + name);
                return "Please enter a valid netmask.";
            }
        } else if (range.equals("hypervisorList")) {
            final String[] hypervisors = value.split(",");
            if (hypervisors == null) {
                return "Please enter hypervisor list, separated by comma";
            }
            for (final String hypervisor : hypervisors) {
                if (HypervisorType.getType(hypervisor) == HypervisorType.Any || HypervisorType.getType(hypervisor) == HypervisorType.None) {
                    return "Please enter a valid hypervisor type";
                }
            }
        } else if (range.equalsIgnoreCase("instanceName")) {
            if (!NetUtils.verifyInstanceName(value)) {
                return "Instance name can not contain hyphen, space or plus sign";
            }
        } else if (range.equalsIgnoreCase("domainName")) {
            String domainName = value;
            if (value.startsWith("*")) {
                // skip the "*."
                domainName = value.substring(2);
            }
            // max length for FQDN is 253 + 2, code adds xxx-xxx-xxx-xxx to domain name when creating URL
            if (domainName.length() >= 238 || !domainName.matches(DOMAIN_NAME_PATTERN)) {
                return "Please enter a valid string for domain name, prefixed with '*.' if applicable";
            }
        } else if (range.equals("routes")) {
            final String[] routes = value.split(",");
            for (final String route : routes) {
                if (route != null) {
                    final String routeToVerify = route.trim();
                    if (!NetUtils.isValidIp4Cidr(routeToVerify)) {
                        throw new InvalidParameterValueException("Invalid value for blacklisted route: " + route + ". Valid format is list" + " of cidrs separated by coma. Example: 10.1.1.0/24,192.168.0.0/24");
                    }
                }
            }
        } else {
            final String[] options = range.split(",");
            for (final String option : options) {
                if (option.trim().equalsIgnoreCase(value)) {
                    return null;
                }
            }
            s_logger.error("configuration value for " + name + " is invalid");
            return "Please enter : " + range;
        }
    } else if (type.equals(Integer.class)) {
        final String[] options = range.split("-");
        if (options.length != 2) {
            final String msg = "configuration range " + range + " for " + name + " is invalid";
            s_logger.error(msg);
            return msg;
        }
        final int min = Integer.parseInt(options[0]);
        final int max = Integer.parseInt(options[1]);
        final int val = Integer.parseInt(value);
        if (val < min || val > max) {
            s_logger.error("configuration value for " + name + " is invalid");
            return "Please enter : " + range;
        }
    }
    return null;
}
Also used : IPRangeConfig(com.cloud.test.IPRangeConfig) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ConfigurationVO(com.cloud.framework.config.impl.ConfigurationVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException)

Example 5 with ConfigurationVO

use of com.cloud.framework.config.impl.ConfigurationVO in project cosmic by MissionCriticalCloud.

the class ManagementServerImpl method searchForConfigurations.

@Override
public Pair<List<? extends Configuration>, Integer> searchForConfigurations(final ListCfgsByCmd cmd) {
    final Filter searchFilter = new Filter(ConfigurationVO.class, "name", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchCriteria<ConfigurationVO> sc = _configDao.createSearchCriteria();
    final Long userId = CallContext.current().getCallingUserId();
    final Account caller = CallContext.current().getCallingAccount();
    final User user = _userDao.findById(userId);
    final Object name = cmd.getConfigName();
    final Object category = cmd.getCategory();
    final Object keyword = cmd.getKeyword();
    final Long zoneId = cmd.getZoneId();
    final Long clusterId = cmd.getClusterId();
    final Long storagepoolId = cmd.getStoragepoolId();
    final Long accountId = cmd.getAccountId();
    String scope = null;
    Long id = null;
    int paramCountCheck = 0;
    if (!_accountMgr.isRootAdmin(caller.getId()) && accountId == null) {
        throw new InvalidParameterValueException("Please specify AccountId to list the config for the given account.");
    }
    if (accountId != null) {
        final Account accountToUpdate = _accountDao.findById(accountId);
        _accountMgr.checkAccess(caller, null, true, accountToUpdate);
        scope = ConfigKey.Scope.Account.toString();
        id = accountId;
        paramCountCheck++;
    }
    if (_accountMgr.isRootAdmin(caller.getId())) {
        if (zoneId != null) {
            scope = ConfigKey.Scope.Zone.toString();
            id = zoneId;
            paramCountCheck++;
        }
        if (clusterId != null) {
            scope = ConfigKey.Scope.Cluster.toString();
            id = clusterId;
            paramCountCheck++;
        }
        if (storagepoolId != null) {
            scope = ConfigKey.Scope.StoragePool.toString();
            id = storagepoolId;
            paramCountCheck++;
        }
    }
    if (paramCountCheck > 1) {
        throw new InvalidParameterValueException("cannot handle multiple IDs, provide only one ID corresponding to the scope");
    }
    if (keyword != null) {
        final SearchCriteria<ConfigurationVO> ssc = _configDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("instance", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("component", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("category", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("value", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (name != null) {
        sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%");
    }
    if (category != null) {
        sc.addAnd("category", SearchCriteria.Op.EQ, category);
    }
    // hidden configurations are not displayed using the search API
    sc.addAnd("category", SearchCriteria.Op.NEQ, "Hidden");
    if (scope != null && !scope.isEmpty()) {
        // getting the list of parameters at requested scope
        sc.addAnd("scope", SearchCriteria.Op.EQ, scope);
    }
    final Pair<List<ConfigurationVO>, Integer> result = _configDao.searchAndCount(sc, searchFilter);
    if (scope != null && !scope.isEmpty()) {
        // Populate values corresponding the resource id
        final List<ConfigurationVO> configVOList = new ArrayList<>();
        for (final ConfigurationVO param : result.first()) {
            final ConfigurationVO configVo = _configDao.findByName(param.getName());
            if (configVo != null) {
                final ConfigKey<?> key = _configDepot.get(param.getName());
                if (key != null) {
                    configVo.setValue(key.valueIn(id).toString());
                    configVOList.add(configVo);
                } else {
                    s_logger.warn("ConfigDepot could not find parameter " + param.getName() + " for scope " + scope);
                }
            } else {
                s_logger.warn("Configuration item  " + param.getName() + " not found in " + scope);
            }
        }
        return new Pair<>(configVOList, configVOList.size());
    }
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) ArrayList(java.util.ArrayList) ConfigurationVO(com.cloud.framework.config.impl.ConfigurationVO) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair)

Aggregations

ConfigurationVO (com.cloud.framework.config.impl.ConfigurationVO)13 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)5 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)4 ConfigurationException (javax.naming.ConfigurationException)3 IPRangeConfig (com.cloud.test.IPRangeConfig)2 Account (com.cloud.user.Account)2 User (com.cloud.user.User)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 ApiServiceConfiguration (com.cloud.config.ApiServiceConfiguration)1 Config (com.cloud.configuration.Config)1 VlanVO (com.cloud.dc.VlanVO)1 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)1 ActionEvent (com.cloud.event.ActionEvent)1 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)1 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)1 InternalErrorException (com.cloud.exception.InternalErrorException)1 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)1 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)1