Ales Komarek | 6041b1b | 2017-11-22 15:26:27 +0100 | [diff] [blame] | 1 | |
| 2 | # Import python libs |
| 3 | import logging |
| 4 | import glob |
| 5 | import os |
| 6 | import yaml |
| 7 | |
| 8 | # Import salt modules |
| 9 | import salt.client |
| 10 | |
| 11 | # Import third party libs |
| 12 | from jsonschema import validate |
| 13 | from jsonschema.validators import validator_for |
| 14 | from jsonschema.exceptions import SchemaError |
| 15 | |
| 16 | |
| 17 | __virtualname__ = 'modelschema' |
| 18 | |
| 19 | LOG = logging.getLogger(__name__) |
| 20 | |
| 21 | BASE_DIR = '/usr/share/salt-formulas/env/_formulas' |
| 22 | |
| 23 | |
| 24 | def _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 | |
| 46 | def 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 |