Validate the users settings conf prior to deploy
961628
def check_settings():
    
    valid=True
    if not get_version() >= '1.0':
        print "FABRIC ERROR: Woven is only compatible with Fabric < 1.0"
        valid = False
    if not env.MEDIA_ROOT or not env.MEDIA_URL:
        print "MEDIA ERROR: You must define a MEDIA_ROOT & MEDIA_URL in your settings.py"
        print "even if plan to deploy your media separately to your project"
        valid = False
    if not env.TEMPLATE_DIRS:
        print "TEMPLATES_DIRS ERROR: You must define a TEMPLATES_DIRS in your settings.py"
        valid=False
    if env.DEFAULT_DATABASE_ENGINE in ['django.db.backends.','django.db.backends.dummy']:
        print "DATABASE SETTINGS ERROR: The default database engine has not been defined in your settings.py file"
        print "At a minimum you must define an sqlite3 database for woven to deploy,"
        print "or define a database backend is managed outside of woven."    
        valid=False
    if not valid: sys.exit(1)
949405
def validate(self):
        """"""
        missing = []
        for k, v in self._map.items():
            attr = getattr(self, k, False)
            if not attr or attr == CONFIG_PLACEHOLDER:
                missing.append(v)
        if missing:
            return "Missing or invalid config values: {}".format(
                ", ".join(sorted(missing))
            )
578388
def check
      raise Errors::ConfigurationInvalid, config.errors.join("; ") unless config.valid?
      distribution.check
    end
195453
protected function validateEditSettings()
    {
        $this->setSubmitted('settings');

        if (!$this->getSubmitted('cron_key')) {
            $this->setSubmitted('cron_key', gplcart_string_random());
        }

        return !$this->hasErrors();
    }
335835
def validate_config(cls, config):
        
        if "config_file" not in config:
            raise ValueError("No config file path given")
        if "socket_file" not in config:
            raise ValueError("No control socket path given")
        if "pid_file" not in config:
            raise ValueError("No PID file path given")
        if "stats" in config and "port" not in config["stats"]:
            raise ValueError("Stats interface defined, but no port given")
        if "proxies" in config:
            cls.validate_proxies_config(config["proxies"])

        return config
794617
def validate_sectionless_conf(self, file_contents, expected):
        """"""
        for line in file_contents.split('\n'):
            if '=' in line:
                args = line.split('=')
                if len(args) <= 1:
                    continue
                key = args[0].strip()
                value = args[1].strip()
                if key in expected.keys():
                    if expected[key] != value:
                        msg = ('Config mismatch.  Expected, actual:  {}, '
                               '{}'.format(expected[key], value))
                        amulet.raise_status(amulet.FAIL, msg=msg)
1000769
def validate_config_parameters(config_json, allowed_keys, allowed_types):
    """"""
    custom_fields = config_json.get(defs.PARAMETERS, [])
    for field in custom_fields:
        validate_field(field, allowed_keys, allowed_types)
        default = field.get(defs.DEFAULT)
        field_type = field.get(defs.TYPE)
        if default:
            validate_field_matches_type(field[defs.VALUE], default, field_type)
631218
def validate(config):
    '''
    
    '''
    if not isinstance(config, list):
        return False, ('Configuration for haproxy beacon must '
                       'be a list.')
    else:
        _config = {}
        list(map(_config.update, config))

        if 'backends' not in _config:
            return False, ('Configuration for haproxy beacon '
                           'requires backends.')
        else:
            if not isinstance(_config['backends'], dict):
                return False, ('Backends for haproxy beacon '
                               'must be a dictionary.')
            else:
                for backend in _config['backends']:
                    log.debug('_config %s', _config['backends'][backend])
                    if 'servers' not in _config['backends'][backend]:
                        return False, ('Backends for haproxy beacon '
                                       'require servers.')
                    else:
                        _servers = _config['backends'][backend]['servers']
                        if not isinstance(_servers, list):
                            return False, ('Servers for haproxy beacon '
                                           'must be a list.')
    return True, 'Valid beacon configuration'
1034822
protected function validateSettings()
    {
        $this->setSubmitted('settings');

        foreach (array('tags', 'protocols') as $field) {
            $string = str_replace(' ', '', $this->getSubmitted($field));
            $this->setSubmitted($field, array_filter(explode(',', $string)));
        }

        return !$this->hasErrors();
    }
1361243
def validate(config):
    '''
    
    '''
    # Configuration for adb beacon should be a dictionary with states array
    if not isinstance(config, list):
        log.info('Configuration for adb beacon must be a list.')
        return False, ('Configuration for adb beacon must be a list.')

    _config = {}
    list(map(_config.update, config))

    if 'states' not in _config:
        log.info('Configuration for adb beacon must include a states array.')
        return False, ('Configuration for adb beacon must include a states array.')
    else:
        if not isinstance(_config['states'], list):
            log.info('Configuration for adb beacon must include a states array.')
            return False, ('Configuration for adb beacon must include a states array.')
        else:
            states = ['offline', 'bootloader', 'device', 'host',
                      'recovery', 'no permissions',
                      'sideload', 'unauthorized', 'unknown', 'missing']
            if any(s not in states for s in _config['states']):
                log.info('Need a one of the following adb '
                         'states: %s', ', '.join(states))
                return False, ('Need a one of the following adb '
                               'states: {0}'.format(', '.join(states)))
    return True, 'Valid beacon configuration'
1043804
def validate_file_permissions(config):
    """"""
    files = config.get('files', {})
    for file_name, options in files.items():
        for key in options.keys():
            if key not in ["owner", "group", "mode"]:
                raise RuntimeError(
                    "Invalid ownership configuration: {}".format(key))
        mode = options.get('mode', config.get('permissions', '600'))
        optional = options.get('optional', config.get('optional', 'False'))
        if '*' in file_name:
            for file in glob.glob(file_name):
                if file not in files.keys():
                    if os.path.isfile(file):
                        _validate_file_mode(mode, file, optional)
        else:
            if os.path.isfile(file_name):
                _validate_file_mode(mode, file_name, optional)
617598
def _get_deploy_options(self, options):
        """"""
        user_data = None
        if options.user_data and options.b64_user_data:
            raise CommandError(
                "Cannot provide both --user-data and --b64-user-data.")
        if options.b64_user_data:
            user_data = options.b64_user_data
        if options.user_data:
            user_data = base64_file(options.user_data).decode("ascii")
        return utils.remove_None({
            'distro_series': options.image,
            'hwe_kernel': options.hwe_kernel,
            'user_data': user_data,
            'comment': options.comment,
            'wait': False,
        })
435824
function validateConfig(configOrFileName) {
    var expectedKeys = [],
        mountPoints = {},
        mountPoint,
        config,
        errMsg,
        key;

    if (typeof configOrFileName === 'string') {
        configFileName = configOrFileName;
        config = require(configFileName);
    } else {
        config = configOrFileName;
    }

    assertObject('config', config);

    // addOn
    expectedKeys.push('addOn');
    assertObject('config.addOn', config.addOn);
    assertBoolean('config.addOn.enable', config.addOn.enable);
    assertArray('config.addOn.basePaths', config.addOn.basePaths);

    // authentication
    expectedKeys.push('authentication');
    assertObject('config.authentication', config.authentication);
    assertBoolean('config.authentication.enable', config.authentication.enable);
    assertBoolean('config.authentication.allowGuests', config.authentication.allowGuests);
    assertBooleanOrString('config.authentication.allowUserRegistration', config.authentication.allowUserRegistration);
    assertBoolean('config.authentication.registeredUsersCanCreate', config.authentication.registeredUsersCanCreate);
    assertBoolean('config.authentication.inferredUsersCanCreate', config.authentication.inferredUsersCanCreate);
    assertBoolean('config.authentication.guestCanCreate', config.authentication.guestCanCreate);
    assertString('config.authentication.guestAccount', config.authentication.guestAccount);
    assertString('config.authentication.logOutUrl', config.authentication.logOutUrl);
    assertNumber('config.authentication.salts', config.authentication.salts);
    assertObject('config.authentication.jwt', config.authentication.jwt);
    assertNumber('config.authentication.jwt.expiresIn', config.authentication.jwt.expiresIn);
    assertString('config.authentication.jwt.privateKey', config.authentication.jwt.privateKey);
    assertString('config.authentication.jwt.publicKey', config.authentication.jwt.publicKey);
    assertArray('config.authentication.publicOrganizations', config.authentication.publicOrganizations);
    config.authentication.publicOrganizations.forEach(function (publicOrg, idx) {
        assertString('config.authentication.publicOrganizations[' + idx, ']', publicOrg);
    });

    if (config.authentication.adminAccount) {
        assertString('config.authentication.adminAccount', config.authentication.adminAccount);
    }

    // bin scripts
    expectedKeys.push('bin');
    assertObject('config.bin', config.bin);
    assertObject('config.bin.log', config.bin.log);

    // blob
    expectedKeys.push('blob');
    assertObject('config.blob', config.blob);
    assertNumber('config.blob.compressionLevel', config.blob.compressionLevel);

    if (config.blob.compressionLevel < 0 || config.blob.compressionLevel > 9) {
        throw new Error('config.blob.compressionLevel must be an integer between 0 and 9. Got: ' +
            config.blob.compressionLevel);
    }

    assertString('config.blob.type', config.blob.type);
    assertString('config.blob.fsDir', config.blob.fsDir);
    assertObject('config.blob.s3', config.blob.s3);

    // client
    expectedKeys.push('client');
    assertObject('config.client', config.client);
    assertString('config.client.appDir', config.client.appDir);
    assertString('config.client.appVersion', config.client.appVersion);
    assertString('config.client.faviconPath', config.client.faviconPath);
    assertString('config.client.pageTitle', config.client.pageTitle, true);
    assertObject('config.client.log', config.client.log);
    assertString('config.client.log.level', config.client.log.level);

    // core
    expectedKeys.push('core');
    assertBoolean('config.core.enableCustomConstraints', config.core.enableCustomConstraints);
    assertNumber('config.core.overlayShardSize', config.core.overlayShardSize);
    if (config.core.overlayShardSize < 1000) {
        throw new Error('Overlay shard size must be at least 1000.');
    }

    // debug
    expectedKeys.push('debug');
    assertBoolean('config.debug', config.debug);

    expectedKeys.push('documentEditing');
    assertObject('config.documentEditing', config.documentEditing);
    assertBoolean('config.documentEditing.enable', config.documentEditing.enable, true);
    assertNumber('config.documentEditing.disconnectTimeout', config.documentEditing.disconnectTimeout);

    // executor
    expectedKeys.push('executor');
    assertObject('config.executor', config.executor);
    assertBoolean('config.executor.enable', config.executor.enable);
    assertString('config.executor.nonce', config.executor.nonce, true);
    warnDeprecated('config.executor.outputDir', config.executor.outputDir);
    assertString('config.executor.labelJobs', config.executor.labelJobs);
    assertNumber('config.executor.workerRefreshInterval', config.executor.workerRefreshInterval);
    assertNumber('config.executor.clearOutputTimeout', config.executor.clearOutputTimeout);
    assertBoolean('config.executor.clearOldDataAtStartUp', config.executor.clearOldDataAtStartUp);

    // mongo configuration
    expectedKeys.push('mongo');
    assertObject('config.mongo', config.mongo);
    assertString('config.mongo.uri', config.mongo.uri);
    assertObject('config.mongo.options', config.mongo.options);

    // plugin
    expectedKeys.push('plugin');
    assertObject('config.plugin', config.plugin);
    assertBoolean('config.plugin.allowServerExecution', config.plugin.allowServerExecution);
    assertArray('config.plugin.basePaths', config.plugin.basePaths);
    assertBoolean('config.plugin.displayAll', config.plugin.displayAll);

    // requirejsPaths
    expectedKeys.push('requirejsPaths');
    assertObject('config.requirejsPaths', config.requirejsPaths);

    // rest
    expectedKeys.push('rest');
    assertObject('config.rest', config.rest);
    assertObject('config.rest.components', config.rest.components);

    for (key in config.rest.components) {
        if (typeof config.rest.components[key] === 'string') {
            mountPoint = key;
            // TODO: Add this warn when the cli tool has been updated.
            // console.warn('config.rest.components[' + key + '] is a string a not an object. ' +
            // 'It is recommended to change to the format described in #xxxx');
        } else {
            assertObject('config.rest.components[' + key + ']', config.rest.components[key]);
            assertString('config.rest.components[' + key + '].mount', config.rest.components[key].mount);
            assertString('config.rest.components[' + key + '].src', config.rest.components[key].src);
            assertObject('config.rest.components[' + key + '].options', config.rest.components[key].options, true);
            mountPoint = config.rest.components[key].mount;
        }

        if (mountPoints[mountPoint] === true) {
            throw new Error('Same mount point [' + mountPoint + '] specified more than once ' +
                'in config.rest.components.');
        } else {
            mountPoints[mountPoint] = true;
        }
    }

    //seedProjects
    expectedKeys.push('seedProjects');
    assertBoolean('config.seedProjects.enable', config.seedProjects.enable);
    assertString('config.seedProjects.defaultProject', config.seedProjects.defaultProject);
    assertArray('config.seedProjects.basePaths', config.seedProjects.basePaths);
    assertArray('config.seedProjects.createAtStartup', config.seedProjects.createAtStartup);
    config.seedProjects.createAtStartup.forEach(function (seedInfo, index) {
        assertObject('config.seedProjects.createAtStartup[' + index + ']', config.seedProjects.createAtStartup[index]);
        assertString('config.seedProjects.createAtStartup[' + index + '].seedId',
            config.seedProjects.createAtStartup[index].seedId);
        assertString('config.seedProjects.createAtStartup[' + index + '].projectName', seedInfo.projectName);
        assertObject('config.seedProjects.createAtStartup[' + index + '].rights', seedInfo.rights, true);
        if (seedInfo.creatorId) {
            assertString('config.seedProjects.createAtStartup[' + index + '].creatorId', seedInfo.creatorId);
        } else if (typeof config.authentication.adminAccount !== 'string') {
            throw new Error('Either config.seedProjects.createAtStartup[' + index +
                '].creatorId or config.authentication.adminAccount should exists!');
        }

        assertString('config.seedProjects.createAtStartup[' + index + '].ownerId', seedInfo.ownerId, true);
    });

    // server configuration
    expectedKeys.push('server');
    assertObject('config.server', config.server);
    assertNumber('config.server.port', config.server.port);
    assertNumber('config.server.timeout', config.server.timeout);
    assertObject('config.server.handle', config.server.handle);
    assertObject('config.server.workerManager', config.server.workerManager);
    assertString('config.server.workerManager.path', config.server.workerManager.path);
    assertObject('config.server.workerManager.options', config.server.workerManager.options);
    assertNumber('config.server.maxWorkers', config.server.maxWorkers);
    warnDeprecated('config.server.sessionStore', config.server.sessionStore,
        'JWTokens are used for authentication, see config.authentication.jwt');

    // server log
    assertObject('config.server.log', config.server.log);
    assertArray('config.server.log.transports', config.server.log.transports);
    // server extlib
    assertArray('config.server.extlibExcludes', config.server.extlibExcludes);
    // server bodyParser config
    assertObject('config.server.bodyParser', config.server.bodyParser);
    assertObject('config.server.bodyParser.json', config.server.bodyParser.json);

    // socketIO
    expectedKeys.push('socketIO');
    assertObject('config.socketIO', config.socketIO);
    assertObject('config.socketIO.clientOptions', config.socketIO.clientOptions);
    assertObject('config.socketIO.serverOptions', config.socketIO.serverOptions);
    assertObject('config.socketIO.adapter', config.socketIO.adapter);
    assertEnum('config.socketIO.adapter.type', config.socketIO.adapter.type.toLowerCase(), 'memory', 'redis');

    // storage
    expectedKeys.push('storage');
    assertObject('config.storage', config.storage);
    assertBoolean('config.storage.broadcastProjectEvents', config.storage.broadcastProjectEvents);
    warnDeprecated('config.storage.emitCommittedCoreObjects', config.storage.emitCommittedCoreObjects,
        'see new config at config.storage.maxEmittedCoreObjects');
    assertNumber('config.storage.maxEmittedCoreObjects', config.storage.maxEmittedCoreObjects);
    warnDeprecated('config.storage.patchRootCommunicationEnabled', config.storage.patchRootCommunicationEnabled,
        'Since 1.7.0 all node changes are transmitted as patch objects (unless newly created).');
    assertNumber('config.storage.cache', config.storage.cache);
    assertNumber('config.storage.loadBucketSize', config.storage.loadBucketSize);
    assertNumber('config.storage.loadBucketTimer', config.storage.loadBucketTimer);
    assertEnum('config.storage.keyType', config.storage.keyType, 'rand160Bits', 'ZSSHA', 'plainSHA1');
    assertObject('config.storage.database', config.storage.database);
    assertEnum('config.storage.database.type', config.storage.database.type.toLowerCase(), 'mongo', 'redis', 'memory');
    assertObject('config.storage.database.options', config.storage.database.options);
    assertBoolean('config.storage.disableHashChecks', config.storage.disableHashChecks);
    assertBoolean('config.storage.requireHashesToMatch', config.storage.requireHashesToMatch);
    if (config.storage.disableHashChecks && config.storage.requireHashesToMatch) {
        throw new Error('Cannot set config.storage.disableHashChecks and requireHashesToMatch ' +
            'to true at the same time!');
    }

    //visualization
    expectedKeys.push('visualization');
    assertObject('config.visualization', config.visualization);
    assertArray('config.visualization.decoratorPaths', config.visualization.decoratorPaths);
    assertArray('config.visualization.svgDirs', config.visualization.svgDirs);
    assertArray('config.visualization.panelPaths', config.visualization.panelPaths);
    assertArray('config.visualization.visualizerDescriptors', config.visualization.visualizerDescriptors);
    assertObject('config.visualization.layout', config.visualization.layout);
    assertArray('config.visualization.layout.basePaths', config.visualization.layout.basePaths);

    //webhooks
    expectedKeys.push('webhooks');
    assertBoolean('config.webhooks.enable', config.webhooks.enable);
    assertEnum('config.webhooks.manager', config.webhooks.manager.toLowerCase(), 'memory', 'redis');
    if (config.webhooks.manager.toLowerCase() === 'redis' && config.socketIO.adapter.type.toLowerCase() !== 'redis') {
        throw new Error('config.webhooks.manager can only be ' +
            '\'redis\' if config.socketIO.adapter.type is \'redis\' as well');
    }

    if (Object.keys(config).length !== expectedKeys.length) {
        errMsg = 'Configuration had unexpected key(s):';
        for (key in config) {
            if (expectedKeys.indexOf(key) < 0) {
                errMsg += ' "' + key + '"';
            }
        }
        throw new Error(errMsg);
    }

    return config;
}
425363
def validate_config(key: str, config: dict) -> None:
    

    try:
        jsonschema.validate(config, CONFIG_JSON_SCHEMA[key])
    except jsonschema.ValidationError as x_validation:
        raise JSONValidation('JSON validation error on {} configuration: {}'.format(key, x_validation.message))
    except jsonschema.SchemaError as x_schema:
        raise JSONValidation('JSON schema error on {} specification: {}'.format(key, x_schema.message))
950867
def config(check):
    """"""
    if check:
        checks = [check]
    else:
        checks = sorted(get_valid_checks())

    files_failed = {}
    files_warned = {}
    num_files = 0

    echo_waiting('Validating default configuration files...')
    for check in checks:
        check_display_queue = []

        config_files = get_config_files(check)
        for config_file in config_files:
            num_files += 1
            file_display_queue = []
            file_name = basepath(config_file)

            try:
                config_data = yaml.safe_load(read_file(config_file))
            except Exception as e:
                files_failed[config_file] = True

                # We must convert to text here to free Exception object before it goes out of scope
                error = str(e)

                check_display_queue.append(lambda: echo_info('{}:'.format(file_name), indent=True))
                check_display_queue.append(lambda: echo_failure('Invalid YAML -', indent=FILE_INDENT))
                check_display_queue.append(lambda: echo_info(error, indent=FILE_INDENT * 2))
                continue

            # Verify there is an `instances` section
            if 'instances' not in config_data:
                files_failed[config_file] = True
                file_display_queue.append(lambda: echo_failure('Missing `instances` section', indent=FILE_INDENT))

            # Verify there is a default instance
            else:
                instances = config_data['instances']
                if check not in IGNORE_DEFAULT_INSTANCE and not isinstance(instances, list):
                    files_failed[config_file] = True
                    file_display_queue.append(lambda: echo_failure('No default instance', indent=FILE_INDENT))

            if file_display_queue:
                check_display_queue.append(lambda: echo_info('{}:'.format(file_name), indent=True))
                check_display_queue.extend(file_display_queue)

        if check_display_queue:
            echo_success('{}:'.format(check))
            for display in check_display_queue:
                display()

    files_failed = len(files_failed)
    files_warned = len(files_warned)
    files_passed = num_files - (files_failed + files_warned)

    if files_failed or files_warned:
        click.echo()

    if files_failed:
        echo_failure('Files with errors: {}'.format(files_failed))

    if files_warned:
        echo_warning('Files with warnings: {}'.format(files_warned))

    if files_passed:
        if files_failed or files_warned:
            echo_success('Files valid: {}'.format(files_passed))
        else:
            echo_success('All {} configuration files are valid!'.format(num_files))

    if files_failed:
        abort()
1044658
def _validate_config(self):
        """"""
        if len(cfg.CONF.ml2_arista.get('switch_info')) < 1:
            msg = _('Required option - when "sec_group_support" is enabled, '
                    'at least one switch must be specified ')
            LOG.exception(msg)
            raise arista_exc.AristaConfigError(msg=msg)
648003
function validate(config, source) {

  if (typeof config.rules === 'object') {
    Object.keys(config.rules).forEach(function(id) {
      validateRuleOptions(id, config.rules[id], source);
    });
  }
}