1 # ============LICENSE_START=======================================================
3 # ================================================================================
4 # Copyright (c) 2017-2018 AT&T Intellectual Property. All rights reserved.
5 # ================================================================================
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 # ============LICENSE_END=========================================================
19 # ECOMP is a trademark and service mark of AT&T Intellectual Property.
21 # -*- coding: utf-8 -*-
26 from functools import partial, reduce
29 from jsonschema import validate, ValidationError
32 from dcae_cli.util import reraise_with_msg, fetch_file_from_web
33 from dcae_cli.util import config as cli_config
34 from dcae_cli.util.exc import DcaeException
35 from dcae_cli.util.logger import get_logger
38 log = get_logger('Schema')
40 # UPDATE: This message applies to the component spec which has been moved on a
43 # WARNING: The below has a "oneOf" for service provides, that will validate as long as any of them are chosen.
44 # However, this is wrong because what we really want is something like:
45 # if component_type == docker
47 # elif component_type == cdap
49 # The unlikely but problematic case is the cdap developer gets a hold of the docker documentation, uses that, it validates, and blows up at cdap runtime
52 # TODO: The next step here is to decide how to manage the links to the schemas. Either:
54 # a) Manage the links in the dcae-cli tool here and thus need to ask if this
55 # belongs in the config to point to some remote server or even point to local
57 # UPDATE: This item has been mostly completed where at least the path is configurable now.
59 # b) Read the links to the schemas from the spec - self-describing jsons. Is
65 class FetchSchemaError(RuntimeError):
68 def _fetch_schema(schema_path):
70 server_url = cli_config.get_server_url()
71 return fetch_file_from_web(server_url, schema_path)
72 except requests.HTTPError as e:
73 raise FetchSchemaError("HTTP error from fetching schema", e)
74 except Exception as e:
75 raise FetchSchemaError("Unexpected error from fetching schema", e)
79 '''Returns a dict from a dict or json string'''
80 if isinstance(obj, str):
81 return json.loads(obj)
85 def _validate(fetch_schema_func, schema_path, spec):
86 '''Validate the given spec
88 Fetch the schema and then validate. Upon a error from fetching or validation,
89 a DcaeException is raised.
93 fetch_schema_func: function that takes schema_path -> dict representation of schema
94 throws a FetchSchemaError upon any failure
95 schema_path: string - path to schema
96 spec: dict or string representation of JSON of schema instance
100 Nothing, silence is golden
103 schema = fetch_schema_func(schema_path)
104 validate(_safe_dict(spec), schema)
105 except ValidationError as e:
106 reraise_with_msg(e, as_dcae=True)
107 except FetchSchemaError as e:
108 reraise_with_msg(e, as_dcae=True)
110 _validate_using_nexus = partial(_validate, _fetch_schema)
113 def apply_defaults(properties_definition, properties):
114 """Utility method to enforce expected defaults
116 This method is used to enforce properties that are *expected* to have at least
117 the default if not set by a user. Expected properties are not required but
118 have a default set. jsonschema does not provide this.
122 properties_definition: dict of the schema definition of the properties to use
123 for verifying and applying defaults
124 properties: dict of the target properties to verify and apply defaults to
128 dict - a new version of properties that has the expected default values
130 # Recursively process all inner objects. Look for more properties and not match
132 for k,v in six.iteritems(properties_definition):
133 if "properties" in v:
134 properties[k] = apply_defaults(v["properties"], properties.get(k, {}))
137 defaults = [ (k, v["default"]) for k, v in properties_definition.items() if "default" in v ]
139 def apply_default(accumulator, default):
141 if k not in accumulator:
142 # Not doing data type checking and any casting. Assuming that this
143 # should have been taken care of in validation
147 return reduce(apply_default, defaults, properties)
149 def apply_defaults_docker_config(config):
150 """Apply expected defaults to Docker config
153 config: Docker config dict
156 Updated Docker config dict
158 # Apply health check defaults
159 healthcheck_type = config["healthcheck"]["type"]
160 component_spec = _fetch_schema(cli_config.get_path_component_spec())
162 if healthcheck_type in ["http", "https"]:
163 apply_defaults_func = partial(apply_defaults,
164 component_spec["definitions"]["docker_healthcheck_http"]["properties"])
165 elif healthcheck_type in ["script"]:
166 apply_defaults_func = partial(apply_defaults,
167 component_spec["definitions"]["docker_healthcheck_script"]["properties"])
169 # You should never get here
170 apply_defaults_func = lambda x: x
172 config["healthcheck"] = apply_defaults_func(config["healthcheck"])
176 def validate_component(spec):
177 _validate_using_nexus(cli_config.get_path_component_spec(), spec)
179 # REVIEW: Could not determine how to do this nicely in json schema. This is
180 # not ideal. We want json schema to be the "it" for validation.
181 ctype = component_type = spec["self"]["component_type"]
184 invalid = [s for s in spec["streams"].get("subscribes", []) \
185 if s["type"] in ["data_router", "data router"]]
187 raise DcaeException("Cdap component as data router subscriber is not supported.")
189 def validate_format(spec):
190 path = cli_config.get_path_data_format()
191 _validate_using_nexus(path, spec)