summaryrefslogtreecommitdiff
path: root/compose/config/validation.py
blob: 971cfe371f9111a70e1d916b7baf514ea518377f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import json
import os
from functools import wraps

from docker.utils.ports import split_port
from jsonschema import Draft4Validator
from jsonschema import FormatChecker
from jsonschema import RefResolver
from jsonschema import ValidationError

from .errors import ConfigurationError


DOCKER_CONFIG_HINTS = {
    'cpu_share': 'cpu_shares',
    'add_host': 'extra_hosts',
    'hosts': 'extra_hosts',
    'extra_host': 'extra_hosts',
    'device': 'devices',
    'link': 'links',
    'memory_swap': 'memswap_limit',
    'port': 'ports',
    'privilege': 'privileged',
    'priviliged': 'privileged',
    'privilige': 'privileged',
    'volume': 'volumes',
    'workdir': 'working_dir',
}


VALID_NAME_CHARS = '[a-zA-Z0-9\._\-]'


@FormatChecker.cls_checks(
    format="ports",
    raises=ValidationError(
        "Invalid port formatting, it should be "
        "'[[remote_ip:]remote_port:]port[/protocol]'"))
def format_ports(instance):
    try:
        split_port(instance)
    except ValueError:
        return False
    return True


def validate_service_names(func):
    @wraps(func)
    def func_wrapper(config):
        for service_name in config.keys():
            if type(service_name) is int:
                raise ConfigurationError(
                    "Service name: {} needs to be a string, eg '{}'".format(service_name, service_name)
                )
        return func(config)
    return func_wrapper


def validate_top_level_object(func):
    @wraps(func)
    def func_wrapper(config):
        if not isinstance(config, dict):
            raise ConfigurationError(
                "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
            )
        return func(config)
    return func_wrapper


def validate_extends_file_path(service_name, extends_options, filename):
    """
    The service to be extended must either be defined in the config key 'file',
    or within 'filename'.
    """
    error_prefix = "Invalid 'extends' configuration for %s:" % service_name

    if 'file' not in extends_options and filename is None:
        raise ConfigurationError(
            "%s you need to specify a 'file', e.g. 'file: something.yml'" % error_prefix
        )


def validate_extended_service_exists(extended_service_name, full_extended_config, extended_config_path):
    if extended_service_name not in full_extended_config:
        msg = (
            "Cannot extend service '%s' in %s: Service not found"
        ) % (extended_service_name, extended_config_path)
        raise ConfigurationError(msg)


def get_unsupported_config_msg(service_name, error_key):
    msg = "Unsupported config option for '{}' service: '{}'".format(service_name, error_key)
    if error_key in DOCKER_CONFIG_HINTS:
        msg += " (did you mean '{}'?)".format(DOCKER_CONFIG_HINTS[error_key])
    return msg


def process_errors(errors, service_name=None):
    """
    jsonschema gives us an error tree full of information to explain what has
    gone wrong. Process each error and pull out relevant information and re-write
    helpful error messages that are relevant.
    """
    def _parse_key_from_error_msg(error):
        return error.message.split("'")[1]

    def _clean_error_message(message):
        return message.replace("u'", "'")

    def _parse_valid_types_from_validator(validator):
        """
        A validator value can be either an array of valid types or a string of
        a valid type. Parse the valid types and prefix with the correct article.
        """
        pre_msg_type_prefix = "a"
        last_msg_type_prefix = "a"
        types_requiring_an = ["array", "object"]

        if isinstance(validator, list):
            last_type = validator.pop()
            types_from_validator = ", ".join(validator)

            if validator[0] in types_requiring_an:
                pre_msg_type_prefix = "an"

            if last_type in types_requiring_an:
                last_msg_type_prefix = "an"

            msg = "{} {} or {} {}".format(
                pre_msg_type_prefix,
                types_from_validator,
                last_msg_type_prefix,
                last_type
            )
        else:
            if validator in types_requiring_an:
                pre_msg_type_prefix = "an"
            msg = "{} {}".format(pre_msg_type_prefix, validator)

        return msg

    def _parse_oneof_validator(error):
        """
        oneOf has multiple schemas, so we need to reason about which schema, sub
        schema or constraint the validation is failing on.
        Inspecting the context value of a ValidationError gives us information about
        which sub schema failed and which kind of error it is.
        """
        constraint = [context for context in error.context if len(context.path) > 0]
        if constraint:
            valid_types = _parse_valid_types_from_validator(constraint[0].validator_value)
            msg = "contains {}, which is an invalid type, it should be {}".format(
                constraint[0].instance,
                valid_types
            )
            return msg

        uniqueness = [context for context in error.context if context.validator == 'uniqueItems']
        if uniqueness:
            msg = "contains non unique items, please remove duplicates from {}".format(
                uniqueness[0].instance
            )
            return msg

        types = [context.validator_value for context in error.context if context.validator == 'type']
        if len(types) == 1:
            valid_types = _parse_valid_types_from_validator(types[0])
        else:
            valid_types = _parse_valid_types_from_validator(types)

        msg = "contains an invalid type, it should be {}".format(valid_types)

        return msg

    root_msgs = []
    invalid_keys = []
    required = []
    type_errors = []
    other_errors = []

    for error in errors:
        # handle root level errors
        if len(error.path) == 0 and not error.instance.get('name'):
            if error.validator == 'type':
                msg = "Top level object needs to be a dictionary. Check your .yml file that you have defined a service at the top level."
                root_msgs.append(msg)
            elif error.validator == 'additionalProperties':
                invalid_service_name = _parse_key_from_error_msg(error)
                msg = "Invalid service name '{}' - only {} characters are allowed".format(invalid_service_name, VALID_NAME_CHARS)
                root_msgs.append(msg)
            else:
                root_msgs.append(_clean_error_message(error.message))

        else:
            if not service_name:
                # field_schema errors will have service name on the path
                service_name = error.path[0]
                error.path.popleft()
            else:
                # service_schema errors have the service name passed in, as that
                # is not available on error.path or necessarily error.instance
                service_name = service_name

            if error.validator == 'additionalProperties':
                invalid_config_key = _parse_key_from_error_msg(error)
                invalid_keys.append(get_unsupported_config_msg(service_name, invalid_config_key))
            elif error.validator == 'anyOf':
                if 'image' in error.instance and 'build' in error.instance:
                    required.append(
                        "Service '{}' has both an image and build path specified. "
                        "A service can either be built to image or use an existing "
                        "image, not both.".format(service_name))
                elif 'image' not in error.instance and 'build' not in error.instance:
                    required.append(
                        "Service '{}' has neither an image nor a build path "
                        "specified. Exactly one must be provided.".format(service_name))
                elif 'image' in error.instance and 'dockerfile' in error.instance:
                    required.append(
                        "Service '{}' has both an image and alternate Dockerfile. "
                        "A service can either be built to image or use an existing "
                        "image, not both.".format(service_name))
                else:
                    required.append(_clean_error_message(error.message))
            elif error.validator == 'oneOf':
                config_key = error.path[0]
                msg = _parse_oneof_validator(error)

                type_errors.append("Service '{}' configuration key '{}' {}".format(
                    service_name, config_key, msg)
                )
            elif error.validator == 'type':
                msg = _parse_valid_types_from_validator(error.validator_value)

                if len(error.path) > 0:
                    config_key = " ".join(["'%s'" % k for k in error.path])
                    type_errors.append(
                        "Service '{}' configuration key {} contains an invalid "
                        "type, it should be {}".format(
                            service_name,
                            config_key,
                            msg))
                else:
                    root_msgs.append(
                        "Service '{}' doesn\'t have any configuration options. "
                        "All top level keys in your docker-compose.yml must map "
                        "to a dictionary of configuration options.'".format(service_name))
            elif error.validator == 'required':
                config_key = error.path[0]
                required.append(
                    "Service '{}' option '{}' is invalid, {}".format(
                        service_name,
                        config_key,
                        _clean_error_message(error.message)))
            elif error.validator == 'dependencies':
                dependency_key = list(error.validator_value.keys())[0]
                required_keys = ",".join(error.validator_value[dependency_key])
                required.append("Invalid '{}' configuration for '{}' service: when defining '{}' you must set '{}' as well".format(
                    dependency_key, service_name, dependency_key, required_keys))
            else:
                config_key = " ".join(["'%s'" % k for k in error.path])
                err_msg = "Service '{}' configuration key {} value {}".format(service_name, config_key, error.message)
                other_errors.append(err_msg)

    return "\n".join(root_msgs + invalid_keys + required + type_errors + other_errors)


def validate_against_fields_schema(config):
    schema_filename = "fields_schema.json"
    return _validate_against_schema(config, schema_filename)


def validate_against_service_schema(config, service_name):
    schema_filename = "service_schema.json"
    return _validate_against_schema(config, schema_filename, service_name)


def _validate_against_schema(config, schema_filename, service_name=None):
    config_source_dir = os.path.dirname(os.path.abspath(__file__))
    schema_file = os.path.join(config_source_dir, schema_filename)

    with open(schema_file, "r") as schema_fh:
        schema = json.load(schema_fh)

    resolver = RefResolver('file://' + config_source_dir + '/', schema)
    validation_output = Draft4Validator(schema, resolver=resolver, format_checker=FormatChecker(["ports"]))

    errors = [error for error in sorted(validation_output.iter_errors(config), key=str)]
    if errors:
        error_msg = process_errors(errors, service_name)
        raise ConfigurationError("Validation failed, reason(s):\n{}".format(error_msg))