blob: 1a8217976f6579c612422290b3be43e7330ffbae [file] [log] [blame]
Ales Komarek6041b1b2017-11-22 15:26:27 +01001
2# Import python libs
3import logging
4import glob
5import os
6import yaml
7
8# Import salt modules
9import salt.client
10
11# Import third party libs
12from jsonschema import validate
13from jsonschema.validators import validator_for
14from jsonschema.exceptions import SchemaError
15
16
17__virtualname__ = 'modelschema'
18
19LOG = logging.getLogger(__name__)
20
21BASE_DIR = '/usr/share/salt-formulas/env/_formulas'
22
23
24def _get_schemas():
25 '''
26 Method will return all known schemas.
27 '''
28 output = {}
29 schemas = glob.glob('{}/*/schemas/*.yaml'.format(BASE_DIR))
30 for schema in schemas:
31 if os.path.exists(schema):
32 filename = schema.split('/')[-1].replace('.yaml', '')
33 service_name, role_name = filename.split('-')
34 if service_name not in output:
35 output[service_name] = {}
36 with open(schema, 'r') as stream:
37 try:
38 data = yaml.load(stream)
39 except yaml.YAMLError as exc:
40 data = None
41 LOG.error(exc)
42 output[service_name][role_name] = data
43 return output
44
45
46def validate_node_model(target, service, role):
47 '''
48 Validates pillar by schema for given given minion, service and role.
49 If no service and role is specified, method will validate all
50 defined services on minion.
51
52 CLI Example:
53 .. code-block:: bash
54 salt-run modelschema.validate_node_model
55 '''
56 client = salt.client.LocalClient(__opts__['conf_file'])
57 schema = _get_schemas()[service][role]
58 result = {}
59
60 validator = validator_for(schema)
61 try:
62 validator.check_schema(schema)
63 except SchemaError as exception:
64 LOG.error(exception)
65 return result
66
67 minions = client.cmd(target, 'pillar.data', timeout=1)
68 for minion, pillar in minions.items():
69 model = pillar[service][role]
70 validation_result = validator(schema).validate(model)
71 result[minion] = validation_result
72 return result