diff options
author | Koren Lev <korenlev@gmail.com> | 2017-07-27 15:04:07 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@opnfv.org> | 2017-07-27 15:04:07 +0000 |
commit | 162c03ef301396072c1934e7e7e0c40a841b4fe2 (patch) | |
tree | 7a2a2781949252436450ff5832962785061a774a /app/api/responders/resource | |
parent | b88c78e3cf2bef22aa2f1c4d0bf305e303bc15f0 (diff) | |
parent | 7e83d0876ddb84a45e130eeba28bc40ef53c074b (diff) |
Merge "Calipso initial release for OPNFV"
Diffstat (limited to 'app/api/responders/resource')
-rw-r--r-- | app/api/responders/resource/__init__.py | 10 | ||||
-rw-r--r-- | app/api/responders/resource/aggregates.py | 157 | ||||
-rw-r--r-- | app/api/responders/resource/clique_constraints.py | 67 | ||||
-rw-r--r-- | app/api/responders/resource/clique_types.py | 103 | ||||
-rw-r--r-- | app/api/responders/resource/cliques.py | 73 | ||||
-rw-r--r-- | app/api/responders/resource/constants.py | 30 | ||||
-rw-r--r-- | app/api/responders/resource/environment_configs.py | 381 | ||||
-rw-r--r-- | app/api/responders/resource/inventory.py | 65 | ||||
-rw-r--r-- | app/api/responders/resource/links.py | 76 | ||||
-rw-r--r-- | app/api/responders/resource/messages.py | 78 | ||||
-rw-r--r-- | app/api/responders/resource/monitoring_config_templates.py | 65 | ||||
-rw-r--r-- | app/api/responders/resource/scans.py | 111 | ||||
-rw-r--r-- | app/api/responders/resource/scheduled_scans.py | 113 |
13 files changed, 1329 insertions, 0 deletions
diff --git a/app/api/responders/resource/__init__.py b/app/api/responders/resource/__init__.py new file mode 100644 index 0000000..1e85a2a --- /dev/null +++ b/app/api/responders/resource/__init__.py @@ -0,0 +1,10 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### + diff --git a/app/api/responders/resource/aggregates.py b/app/api/responders/resource/aggregates.py new file mode 100644 index 0000000..36fcfa4 --- /dev/null +++ b/app/api/responders/resource/aggregates.py @@ -0,0 +1,157 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.responders.responder_base import ResponderBase +from api.validation.data_validate import DataValidate + + +class Aggregates(ResponderBase): + def __init__(self): + super().__init__() + self.AGGREGATE_TYPES = ["environment", "message", "constant"] + self.AGGREGATES_MAP = { + "environment": self.get_environments_aggregates, + "message": self.get_messages_aggregates, + "constant": self.get_constants_aggregates + } + + def on_get(self, req, resp): + self.log.debug("Getting aggregates information") + + filters = self.parse_query_params(req) + filters_requirements = { + "env_name": self.require(str), + "type": self.require(str, validate=DataValidate.LIST, + requirement=self.AGGREGATE_TYPES, + mandatory=True, + error_messages={"mandatory": + "type must be specified: " + + "environment/" + + " message/" + + "constant"}) + } + self.validate_query_data(filters, filters_requirements) + query = self.build_query(filters) + query_type = query["type"] + if query_type == "environment": + env_name = query.get("env_name") + if not env_name: + self.bad_request("env_name must be specified") + if not self.check_environment_name(env_name): + self.bad_request("unknown environment: " + env_name) + + aggregates = self.AGGREGATES_MAP[query_type](query) + self.set_successful_response(resp, aggregates) + + def build_query(self, filters): + query = {} + env_name = filters.get("env_name") + query_type = filters["type"] + query["type"] = filters["type"] + if query_type == "environment": + if env_name: + query['env_name'] = env_name + return query + return query + + def get_environments_aggregates(self, query): + env_name = query['env_name'] + aggregates = { + "type": query["type"], + "env_name": env_name, + "aggregates": { + "object_types": { + + } + } + } + pipeline = [ + { + '$match': { + 'environment': env_name + } + }, + { + '$group': { + '_id': '$type', + 'total': { + '$sum': 1 + } + } + } + ] + groups = self.aggregate(pipeline, "inventory") + for group in groups: + aggregates['aggregates']['object_types'][group['_id']] = \ + group['total'] + return aggregates + + def get_messages_aggregates(self, query): + aggregates = { + "type": query['type'], + "aggregates": { + "levels": {}, + "environments": {} + } + } + env_pipeline = [ + { + '$group': { + '_id': '$environment', + 'total': { + '$sum': 1 + } + } + } + ] + environments = self.aggregate(env_pipeline, "messages") + for environment in environments: + aggregates['aggregates']['environments'][environment['_id']] = \ + environment['total'] + level_pipeline = [ + { + '$group': { + '_id': '$level', + 'total': { + '$sum': 1 + } + } + } + ] + levels = self.aggregate(level_pipeline, "messages") + for level in levels: + aggregates['aggregates']['levels'][level['_id']] = \ + level['total'] + + return aggregates + + def get_constants_aggregates(self, query): + aggregates = { + "type": query['type'], + "aggregates": { + "names": {} + } + } + pipeline = [ + { + '$project': { + '_id': 0, + 'name': 1, + 'total': { + '$size': '$data' + } + } + } + ] + constants = self.aggregate(pipeline, "constants") + for constant in constants: + aggregates['aggregates']['names'][constant['name']] = \ + constant['total'] + + return aggregates diff --git a/app/api/responders/resource/clique_constraints.py b/app/api/responders/resource/clique_constraints.py new file mode 100644 index 0000000..eddead9 --- /dev/null +++ b/app/api/responders/resource/clique_constraints.py @@ -0,0 +1,67 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.responders.responder_base import ResponderBase +from api.validation.data_validate import DataValidate +from bson.objectid import ObjectId + + +class CliqueConstraints(ResponderBase): + def __init__(self): + super().__init__() + self.ID = '_id' + self.PROJECTION = { + self.ID: True + } + self.COLLECTION = 'clique_constraints' + + def on_get(self, req, resp): + self.log.debug("Getting clique_constraints") + filters = self.parse_query_params(req) + focal_point_types = self.get_constants_by_name("object_types") + filters_requirements = { + 'id': self.require(ObjectId, True), + 'focal_point_type': self.require(str, False, DataValidate.LIST, + focal_point_types), + 'constraint': self.require([list, str]), + 'page': self.require(int, True), + 'page_size': self.require(int, True) + } + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + query = self.build_query(filters) + if self.ID in query: + clique_constraint = self.get_object_by_id(self.COLLECTION, + query, + [ObjectId], self.ID) + self.set_successful_response(resp, clique_constraint) + else: + clique_constraints_ids = self.get_objects_list(self.COLLECTION, + query, + page, page_size, self.PROJECTION) + self.set_successful_response( + resp, {"clique_constraints": clique_constraints_ids} + ) + + def build_query(self, filters): + query = {} + filters_keys = ['focal_point_type'] + self.update_query_with_filters(filters, filters_keys, query) + constraints = filters.get('constraint') + if constraints: + if type(constraints) != list: + constraints = [constraints] + + query['constraints'] = { + '$all': constraints + } + _id = filters.get('id') + if _id: + query[self.ID] = _id + return query diff --git a/app/api/responders/resource/clique_types.py b/app/api/responders/resource/clique_types.py new file mode 100644 index 0000000..9a39dc8 --- /dev/null +++ b/app/api/responders/resource/clique_types.py @@ -0,0 +1,103 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.responders.responder_base import ResponderBase +from api.validation.data_validate import DataValidate +from bson.objectid import ObjectId + + +class CliqueTypes(ResponderBase): + def __init__(self): + super().__init__() + self.COLLECTION = "clique_types" + self.ID = "_id" + self.PROJECTION = { + self.ID: True, + "focal_point_type": True, + "link_types": True, + "environment": True + } + + def on_get(self, req, resp): + self.log.debug("Getting clique types") + + filters = self.parse_query_params(req) + focal_point_types = self.get_constants_by_name("object_types") + link_types = self.get_constants_by_name("link_types") + filters_requirements = { + 'env_name': self.require(str, mandatory=True), + 'id': self.require(ObjectId, True), + 'focal_point_type': self.require(str, + validate=DataValidate.LIST, + requirement=focal_point_types), + 'link_type': self.require([list, str], + validate=DataValidate.LIST, + requirement=link_types), + 'page': self.require(int, True), + 'page_size': self.require(int, True) + } + + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + query = self.build_query(filters) + if self.ID in query: + clique_type = self.get_object_by_id(self.COLLECTION, query, + [ObjectId], self.ID) + self.set_successful_response(resp, clique_type) + else: + clique_types_ids = self.get_objects_list(self.COLLECTION, + query, + page, page_size, self.PROJECTION) + self.set_successful_response(resp, + {"clique_types": clique_types_ids}) + + def on_post(self, req, resp): + self.log.debug("Posting new clique_type") + error, clique_type = self.get_content_from_request(req) + if error: + self.bad_request(error) + focal_point_types = self.get_constants_by_name("object_types") + link_types = self.get_constants_by_name("link_types") + clique_type_requirements = { + 'environment': self.require(str, mandatory=True), + 'focal_point_type': self.require(str, False, DataValidate.LIST, + focal_point_types, True), + 'link_types': self.require(list, False, DataValidate.LIST, + link_types, True), + 'name': self.require(str, mandatory=True) + } + + self.validate_query_data(clique_type, clique_type_requirements) + + env_name = clique_type['environment'] + if not self.check_environment_name(env_name): + self.bad_request("unkown environment: " + env_name) + + self.write(clique_type, self.COLLECTION) + self.set_successful_response(resp, + {"message": "created a new clique_type " + "for environment {0}" + .format(env_name)}, + "201") + + def build_query(self, filters): + query = {} + filters_keys = ['focal_point_type'] + self.update_query_with_filters(filters, filters_keys, query) + link_types = filters.get('link_type') + if link_types: + if type(link_types) != list: + link_types = [link_types] + query['link_types'] = {'$all': link_types} + _id = filters.get('id') + if _id: + query[self.ID] = _id + + query['environment'] = filters['env_name'] + return query diff --git a/app/api/responders/resource/cliques.py b/app/api/responders/resource/cliques.py new file mode 100644 index 0000000..ece347a --- /dev/null +++ b/app/api/responders/resource/cliques.py @@ -0,0 +1,73 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.validation.data_validate import DataValidate +from api.responders.responder_base import ResponderBase +from bson.objectid import ObjectId + +from utils.util import generate_object_ids + + +class Cliques(ResponderBase): + def __init__(self): + super().__init__() + self.COLLECTION = "cliques" + self.ID = '_id' + self.PROJECTION = { + self.ID: True, + "focal_point_type": True, + "environment": True + } + + def on_get(self, req, resp): + self.log.debug("Getting cliques") + + filters = self.parse_query_params(req) + focal_point_types = self.get_constants_by_name("object_types") + link_types = self.get_constants_by_name("link_types") + filters_requirements = { + 'env_name': self.require(str, mandatory=True), + 'id': self.require(ObjectId, True), + 'focal_point': self.require(ObjectId, True), + 'focal_point_type': self.require(str, validate=DataValidate.LIST, + requirement=focal_point_types), + 'link_type': self.require(str, validate=DataValidate.LIST, + requirement=link_types), + 'link_id': self.require(ObjectId, True), + 'page': self.require(int, True), + 'page_size': self.require(int, True) + } + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + query = self.build_query(filters) + + if self.ID in query: + clique = self.get_object_by_id(self.COLLECTION, query, + [ObjectId], self.ID) + self.set_successful_response(resp, clique) + else: + cliques_ids = self.get_objects_list(self.COLLECTION, query, + page, page_size, self.PROJECTION) + self.set_successful_response(resp, {"cliques": cliques_ids}) + + def build_query(self, filters): + query = {} + filters_keys = ['focal_point', 'focal_point_type'] + self.update_query_with_filters(filters, filters_keys, query) + link_type = filters.get('link_type') + if link_type: + query['links_detailed.link_type'] = link_type + link_id = filters.get('link_id') + if link_id: + query['links_detailed._id'] = link_id + _id = filters.get('id') + if _id: + query[self.ID] = _id + query['environment'] = filters['env_name'] + return query diff --git a/app/api/responders/resource/constants.py b/app/api/responders/resource/constants.py new file mode 100644 index 0000000..be71b5d --- /dev/null +++ b/app/api/responders/resource/constants.py @@ -0,0 +1,30 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.responders.responder_base import ResponderBase +from bson.objectid import ObjectId + + +class Constants(ResponderBase): + def __init__(self): + super().__init__() + self.ID = '_id' + self.COLLECTION = 'constants' + + def on_get(self, req, resp): + self.log.debug("Getting constants with name") + filters = self.parse_query_params(req) + filters_requirements = { + "name": self.require(str, mandatory=True), + } + self.validate_query_data(filters, filters_requirements) + query = {"name": filters['name']} + constant = self.get_object_by_id(self.COLLECTION, query, + [ObjectId], self.ID) + self.set_successful_response(resp, constant) diff --git a/app/api/responders/resource/environment_configs.py b/app/api/responders/resource/environment_configs.py new file mode 100644 index 0000000..bee6a4d --- /dev/null +++ b/app/api/responders/resource/environment_configs.py @@ -0,0 +1,381 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.validation import regex +from api.validation.data_validate import DataValidate +from api.responders.responder_base import ResponderBase +from bson.objectid import ObjectId +from datetime import datetime +from utils.constants import EnvironmentFeatures +from utils.inventory_mgr import InventoryMgr + + +class EnvironmentConfigs(ResponderBase): + def __init__(self): + super(EnvironmentConfigs, self).__init__() + self.inv = InventoryMgr() + self.ID = "name" + self.PROJECTION = { + self.ID: True, + "_id": False, + "name": True, + "distribution": True + } + self.COLLECTION = "environments_config" + self.CONFIGURATIONS_NAMES = ["mysql", "OpenStack", + "CLI", "AMQP", "Monitoring", + "NFV_provider", "ACI"] + self.OPTIONAL_CONFIGURATIONS_NAMES = ["AMQP", "Monitoring", + "NFV_provider", "ACI"] + + self.provision_types = self.\ + get_constants_by_name("environment_provision_types") + self.env_types = self.get_constants_by_name("env_types") + self.monitoring_types = self.\ + get_constants_by_name("environment_monitoring_types") + self.distributions = self.\ + get_constants_by_name("distributions") + self.mechanism_drivers = self.\ + get_constants_by_name("mechanism_drivers") + self.operational_values = self.\ + get_constants_by_name("environment_operational_status") + self.type_drivers = self.\ + get_constants_by_name("type_drivers") + + self.CONFIGURATIONS_REQUIREMENTS = { + "mysql": { + "name": self.require(str, mandatory=True), + "host": self.require(str, + validate=DataValidate.REGEX, + requirement=[regex.IP, regex.HOSTNAME], + mandatory=True), + "password": self.require(str, mandatory=True), + "port": self.require(int, + True, + DataValidate.REGEX, + regex.PORT, + mandatory=True), + "user": self.require(str, mandatory=True) + }, + "OpenStack": { + "name": self.require(str, mandatory=True), + "admin_token": self.require(str, mandatory=True), + "host": self.require(str, + validate=DataValidate.REGEX, + requirement=[regex.IP, regex.HOSTNAME], + mandatory=True), + "port": self.require(int, + True, + validate=DataValidate.REGEX, + requirement=regex.PORT, + mandatory=True), + "pwd": self.require(str, mandatory=True), + "user": self.require(str, mandatory=True) + }, + "CLI": { + "name": self.require(str, mandatory=True), + "host": self.require(str, + validate=DataValidate.REGEX, + requirement=[regex.IP, regex.HOSTNAME], + mandatory=True), + "user": self.require(str, mandatory=True), + "pwd": self.require(str), + "key": self.require(str, + validate=DataValidate.REGEX, + requirement=regex.PATH) + }, + "AMQP": { + "name": self.require(str, mandatory=True), + "host": self.require(str, + validate=DataValidate.REGEX, + requirement=[regex.IP, regex.HOSTNAME], + mandatory=True), + "password": self.require(str, mandatory=True), + "port": self.require(int, + True, + validate=DataValidate.REGEX, + requirement=regex.PORT, + mandatory=True), + "user": self.require(str, mandatory=True) + }, + "Monitoring": { + "name": self.require(str, mandatory=True), + "config_folder": self.require(str, + validate=DataValidate.REGEX, + requirement=regex.PATH, + mandatory=True), + "provision": self.require(str, + validate=DataValidate.LIST, + requirement=self.provision_types, + mandatory=True), + "env_type": self.require(str, + validate=DataValidate.LIST, + requirement=self.env_types, + mandatory=True), + "api_port": self.require(int, True, mandatory=True), + "rabbitmq_pass": self.require(str, mandatory=True), + "rabbitmq_user": self.require(str, mandatory=True), + "rabbitmq_port": self.require(int, + True, + validate=DataValidate.REGEX, + requirement=regex.PORT, + mandatory=True), + "ssh_port": self.require(int, + True, + validate=DataValidate.REGEX, + requirement=regex.PORT), + "ssh_user": self.require(str), + "ssh_password": self.require(str), + "server_ip": self.require(str, + validate=DataValidate.REGEX, + requirement=[regex.IP, regex.HOSTNAME], + mandatory=True), + "server_name": self.require(str, mandatory=True), + "type": self.require(str, + validate=DataValidate.LIST, + requirement=self.monitoring_types, + mandatory=True) + }, + "NFV_provider": { + "name": self.require(str, mandatory=True), + "host": self.require(str, + validate=DataValidate.REGEX, + requirement=[regex.IP, regex.HOSTNAME], + mandatory=True), + "nfv_token": self.require(str, mandatory=True), + "port": self.require(int, + True, + DataValidate.REGEX, + regex.PORT, + True), + "user": self.require(str, mandatory=True), + "pwd": self.require(str, mandatory=True) + }, + "ACI": { + "name": self.require(str, mandatory=True), + "host": self.require(str, + validate=DataValidate.REGEX, + requirement=[regex.IP, regex.HOSTNAME], + mandatory=True), + "user": self.require(str, mandatory=True), + "pwd": self.require(str, mandatory=True) + } + } + self.AUTH_REQUIREMENTS = { + "view-env": self.require(list, mandatory=True), + "edit-env": self.require(list, mandatory=True) + } + + def on_get(self, req, resp): + self.log.debug("Getting environment config") + filters = self.parse_query_params(req) + + filters_requirements = { + "name": self.require(str), + "distribution": self.require(str, False, + DataValidate.LIST, + self.distributions), + "mechanism_drivers": self.require([str, list], + False, + DataValidate.LIST, + self.mechanism_drivers), + "type_drivers": self.require(str, False, + DataValidate.LIST, + self.type_drivers), + "user": self.require(str), + "listen": self.require(bool, True), + "scanned": self.require(bool, True), + "monitoring_setup_done": self.require(bool, True), + "operational": self.require(str, False, + DataValidate.LIST, + self.operational_values), + "page": self.require(int, True), + "page_size": self.require(int, True) + } + + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + + query = self.build_query(filters) + + if self.ID in query: + environment_config = self.get_object_by_id(self.COLLECTION, query, + [ObjectId, datetime], self.ID) + self.set_successful_response(resp, environment_config) + else: + objects_ids = self.get_objects_list(self.COLLECTION, query, + page, page_size, self.PROJECTION) + self.set_successful_response(resp, {'environment_configs': objects_ids}) + + def build_query(self, filters): + query = {} + filters_keys = ["name", "distribution", "type_drivers", "user", + "listen", "monitoring_setup_done", "scanned", + "operational"] + self.update_query_with_filters(filters, filters_keys, query) + mechanism_drivers = filters.get("mechanism_drivers") + if mechanism_drivers: + if type(mechanism_drivers) != list: + mechanism_drivers = [mechanism_drivers] + query['mechanism_drivers'] = {'$all': mechanism_drivers} + + return query + + def on_post(self, req, resp): + self.log.debug("Creating a new environment config") + + error, env_config = self.get_content_from_request(req) + if error: + self.bad_request(error) + + environment_config_requirement = { + "app_path": self.require(str, mandatory=True), + "configuration": self.require(list, mandatory=True), + "distribution": self.require(str, False, DataValidate.LIST, + self.distributions, True), + "listen": self.require(bool, True, mandatory=True), + "user": self.require(str), + "mechanism_drivers": self.require(list, False, DataValidate.LIST, + self.mechanism_drivers, True), + "name": self.require(str, mandatory=True), + "operational": self.require(str, True, DataValidate.LIST, + self.operational_values, mandatory=True), + "scanned": self.require(bool, True), + "last_scanned": self.require(str), + "type": self.require(str, mandatory=True), + "type_drivers": self.require(str, False, DataValidate.LIST, + self.type_drivers, True), + "enable_monitoring": self.require(bool, True), + "monitoring_setup_done": self.require(bool, True), + "auth": self.require(dict) + } + self.validate_query_data(env_config, + environment_config_requirement, + can_be_empty_keys=["last_scanned"] + ) + self.check_and_convert_datetime("last_scanned", env_config) + # validate the configurations + configurations = env_config['configuration'] + config_validation = self.validate_environment_config(configurations) + + if not config_validation['passed']: + self.bad_request(config_validation['error_message']) + + err_msg = self.validate_env_config_with_supported_envs(env_config) + if err_msg: + self.bad_request(err_msg) + + err_msg = self.validate_env_config_with_constraints(env_config) + if err_msg: + self.bad_request(err_msg) + + if "auth" in env_config: + err_msg = self.validate_data(env_config.get("auth"), + self.AUTH_REQUIREMENTS) + if err_msg: + self.bad_request("auth error: " + err_msg) + + if "scanned" not in env_config: + env_config["scanned"] = False + + self.write(env_config, self.COLLECTION) + self.set_successful_response(resp, + {"message": "created environment_config " + "for {0}" + .format(env_config["name"])}, + "201") + + def validate_environment_config(self, configurations): + configurations_of_names = {} + validation = {"passed": True} + if [config for config in configurations + if 'name' not in config]: + validation['passed'] = False + validation['error_message'] = "configuration must have name" + return validation + + unknown_configs = [config['name'] for config in configurations + if config['name'] not in self.CONFIGURATIONS_NAMES] + if unknown_configs: + validation['passed'] = False + validation['error_message'] = 'Unknown configurations: {0}'. \ + format(' and '.join(unknown_configs)) + return validation + + for name in self.CONFIGURATIONS_NAMES: + configs = self.get_configuration_by_name(name, configurations) + if configs: + if len(configs) > 1: + validation["passed"] = False + validation["error_message"] = "environment configurations can " \ + "only contain one " \ + "configuration for {0}".format(name) + return validation + configurations_of_names[name] = configs[0] + else: + if name not in self.OPTIONAL_CONFIGURATIONS_NAMES: + validation["passed"] = False + validation['error_message'] = "configuration for {0} " \ + "is mandatory".format(name) + return validation + + for name, config in configurations_of_names.items(): + error_message = self.validate_configuration(name, config) + if error_message: + validation['passed'] = False + validation['error_message'] = "{0} error: {1}".\ + format(name, error_message) + break + if name is 'CLI': + if 'key' not in config and 'pwd' not in config: + validation['passed'] = False + validation['error_message'] = 'CLI error: either key ' \ + 'or pwd must be provided' + return validation + + def validate_env_config_with_supported_envs(self, env_config): + # validate the environment config with supported environments + matches = { + 'environment.distribution': env_config['distribution'], + 'environment.type_drivers': env_config['type_drivers'], + 'environment.mechanism_drivers': {'$in': env_config['mechanism_drivers']} + } + + err_prefix = 'configuration not accepted: ' + if not self.inv.is_feature_supported_in_env(matches, + EnvironmentFeatures.SCANNING): + return err_prefix + 'scanning is not supported in this environment' + + configs = env_config['configuration'] + if not self.inv.is_feature_supported_in_env(matches, + EnvironmentFeatures.MONITORING) \ + and self.get_configuration_by_name('Monitoring', configs): + return err_prefix + 'monitoring is not supported in this environment, ' \ + 'please remove the Monitoring configuration' + + if not self.inv.is_feature_supported_in_env(matches, + EnvironmentFeatures.LISTENING) \ + and self.get_configuration_by_name('AMQP', configs): + return err_prefix + 'listening is not supported in this environment, ' \ + 'please remove the AMQP configuration' + + return None + + def validate_env_config_with_constraints(self, env_config): + if env_config['listen'] and \ + not self.get_configuration_by_name('AMQP', env_config['configuration']): + return 'configuration not accepted: ' \ + 'must provide AMQP configuration to listen the environment' + + def get_configuration_by_name(self, name, configurations): + return [config for config in configurations if config['name'] == name] + + def validate_configuration(self, name, configuration): + return self.validate_data(configuration, + self.CONFIGURATIONS_REQUIREMENTS[name]) diff --git a/app/api/responders/resource/inventory.py b/app/api/responders/resource/inventory.py new file mode 100644 index 0000000..02bc486 --- /dev/null +++ b/app/api/responders/resource/inventory.py @@ -0,0 +1,65 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.responders.responder_base import ResponderBase +from bson.objectid import ObjectId +from datetime import datetime + + +class Inventory(ResponderBase): + def __init__(self): + super().__init__() + self.COLLECTION = 'inventory' + self.ID = 'id' + self.PROJECTION = { + self.ID: True, + "name": True, + "name_path": True + } + + def on_get(self, req, resp): + self.log.debug("Getting objects from inventory") + + filters = self.parse_query_params(req) + filters_requirements = { + 'env_name': self.require(str, mandatory=True), + 'id': self.require(str), + 'id_path': self.require(str), + 'parent_id': self.require(str), + 'parent_path': self.require(str), + 'sub_tree': self.require(bool, True), + 'page': self.require(int, True), + 'page_size': self.require(int, True) + } + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + query = self.build_query(filters) + if self.ID in query: + obj = self.get_object_by_id(self.COLLECTION, query, + [ObjectId, datetime], self.ID) + self.set_successful_response(resp, obj) + else: + objects_ids = self.get_objects_list(self.COLLECTION, query, + page, page_size, self.PROJECTION) + self.set_successful_response(resp, {"objects": objects_ids}) + + def build_query(self, filters): + query = {} + filters_keys = ['parent_id', 'id_path', 'id'] + self.update_query_with_filters(filters, filters_keys, query) + parent_path = filters.get('parent_path') + if parent_path: + regular_expression = parent_path + if filters.get('sub_tree', False): + regular_expression += "[/]?" + else: + regular_expression += "/[^/]+$" + query['id_path'] = {"$regex": regular_expression} + query['environment'] = filters['env_name'] + return query diff --git a/app/api/responders/resource/links.py b/app/api/responders/resource/links.py new file mode 100644 index 0000000..33fd432 --- /dev/null +++ b/app/api/responders/resource/links.py @@ -0,0 +1,76 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.responders.responder_base import ResponderBase +from api.validation.data_validate import DataValidate +from bson.objectid import ObjectId + + +class Links(ResponderBase): + def __init__(self): + super().__init__() + self.COLLECTION = 'links' + self.ID = '_id' + self.PROJECTION = { + self.ID: True, + "link_name": True, + "link_type": True, + "environment": True, + "host": True + } + + def on_get(self, req, resp): + self.log.debug("Getting links from links") + + filters = self.parse_query_params(req) + + link_types = self.get_constants_by_name("link_types") + link_states = self.get_constants_by_name("link_states") + filters_requirements = { + 'env_name': self.require(str, mandatory=True), + 'id': self.require(ObjectId, True), + 'host': self.require(str), + 'link_type': self.require(str, validate=DataValidate.LIST, + requirement=link_types), + 'link_name': self.require(str), + 'source_id': self.require(str), + 'target_id': self.require(str), + 'state': self.require(str, validate=DataValidate.LIST, + requirement=link_states), + 'page': self.require(int, True), + 'page_size': self.require(int, True) + } + + self.validate_query_data(filters, filters_requirements, r'^attributes\:\w+$') + filters = self.change_dict_naming_convention(filters, self.replace_colon_with_dot) + page, page_size = self.get_pagination(filters) + query = self.build_query(filters) + if self.ID in query: + link = self.get_object_by_id(self.COLLECTION, query, + [ObjectId], self.ID) + self.set_successful_response(resp, link) + else: + links_ids = self.get_objects_list(self.COLLECTION, query, + page, page_size, self.PROJECTION) + self.set_successful_response(resp, {"links": links_ids}) + + def build_query(self, filters): + query = {} + filters_keys = ['host', 'link_type', 'link_name', + 'source_id', 'target_id', 'state'] + self.update_query_with_filters(filters, filters_keys, query) + # add attributes to the query + for key in filters.keys(): + if key.startswith("attributes."): + query[key] = filters[key] + _id = filters.get('id') + if _id: + query[self.ID] = _id + query['environment'] = filters['env_name'] + return query diff --git a/app/api/responders/resource/messages.py b/app/api/responders/resource/messages.py new file mode 100644 index 0000000..0dda31b --- /dev/null +++ b/app/api/responders/resource/messages.py @@ -0,0 +1,78 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from datetime import datetime + +from api.responders.responder_base import ResponderBase +from api.validation.data_validate import DataValidate +from bson.objectid import ObjectId + + +class Messages(ResponderBase): + def __init__(self): + super().__init__() + self.ID = "id" + self.COLLECTION = 'messages' + self.PROJECTION = { + self.ID: True, + "environment": True, + "source_system": True, + "level": True + } + + def on_get(self, req, resp): + self.log.debug("Getting messages from messages") + filters = self.parse_query_params(req) + messages_severity = self.get_constants_by_name("messages_severity") + object_types = self.get_constants_by_name("object_types") + filters_requirements = { + 'env_name': self.require(str, mandatory=True), + 'source_system': self.require(str), + 'id': self.require(str), + 'level': self.require(str, validate=DataValidate.LIST, + requirement=messages_severity), + 'related_object': self.require(str), + 'related_object_type': self.require(str, validate=DataValidate.LIST, + requirement=object_types), + 'start_time': self.require(str), + 'end_time': self.require(str), + 'page': self.require(int, True), + 'page_size': self.require(int, True) + } + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + self.check_and_convert_datetime('start_time', filters) + self.check_and_convert_datetime('end_time', filters) + + query = self.build_query(filters) + if self.ID in query: + message = self.get_object_by_id(self.COLLECTION, query, + [ObjectId, datetime], self.ID) + self.set_successful_response(resp, message) + else: + objects_ids = self.get_objects_list(self.COLLECTION, query, + page, page_size, self.PROJECTION) + self.set_successful_response(resp, {'messages': objects_ids}) + + def build_query(self, filters): + query = {} + filters_keys = ['source_system', 'id', 'level', 'related_object', + 'related_object_type'] + self.update_query_with_filters(filters, filters_keys, query) + start_time = filters.get('start_time') + if start_time: + query['timestamp'] = {"$gte": start_time} + end_time = filters.get('end_time') + if end_time: + if 'timestamp' in query: + query['timestamp'].update({"$lte": end_time}) + else: + query['timestamp'] = {"$lte": end_time} + query['environment'] = filters['env_name'] + return query diff --git a/app/api/responders/resource/monitoring_config_templates.py b/app/api/responders/resource/monitoring_config_templates.py new file mode 100644 index 0000000..42d3973 --- /dev/null +++ b/app/api/responders/resource/monitoring_config_templates.py @@ -0,0 +1,65 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.validation.data_validate import DataValidate +from api.responders.responder_base import ResponderBase +from bson.objectid import ObjectId + + +class MonitoringConfigTemplates(ResponderBase): + def __init__(self): + super().__init__() + self.ID = "_id" + self.COLLECTION = "monitoring_config_templates" + self.PROJECTION = { + self.ID: True, + "side": True, + "type": True + } + + def on_get(self, req, resp): + self.log.debug("Getting monitoring config template") + + filters = self.parse_query_params(req) + + sides = self.get_constants_by_name("monitoring_sides") + filters_requirements = { + "id": self.require(ObjectId, True), + "order": self.require(int, True), + "side": self.require(str, validate=DataValidate.LIST, + requirement=sides), + "type": self.require(str), + "page": self.require(int, True), + "page_size": self.require(int, True) + } + + self.validate_query_data(filters, filters_requirements) + + page, page_size = self.get_pagination(filters) + query = self.build_query(filters) + if self.ID in query: + template = self.get_object_by_id(self.COLLECTION, query, + [ObjectId], self.ID) + self.set_successful_response(resp, template) + else: + templates = self.get_objects_list(self.COLLECTION, query, + page, page_size, self.PROJECTION) + self.set_successful_response( + resp, + {"monitoring_config_templates": templates} + ) + + def build_query(self, filters): + query = {} + filters_keys = ["order", "side", "type"] + self.update_query_with_filters(filters, filters_keys, query) + _id = filters.get('id') + if _id: + query[self.ID] = _id + return query diff --git a/app/api/responders/resource/scans.py b/app/api/responders/resource/scans.py new file mode 100644 index 0000000..c9ad2e2 --- /dev/null +++ b/app/api/responders/resource/scans.py @@ -0,0 +1,111 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.validation.data_validate import DataValidate +from api.responders.responder_base import ResponderBase +from bson.objectid import ObjectId +from datetime import datetime + + +class Scans(ResponderBase): + def __init__(self): + super().__init__() + self.COLLECTION = "scans" + self.ID = "_id" + self.PROJECTION = { + self.ID: True, + "environment": True, + "status": True, + "scan_completed": True + } + + def on_get(self, req, resp): + self.log.debug("Getting scans") + filters = self.parse_query_params(req) + + scan_statuses = self.get_constants_by_name("scan_statuses") + filters_requirements = { + "env_name": self.require(str, mandatory=True), + "id": self.require(ObjectId, True), + "base_object": self.require(str), + "status": self.require(str, False, DataValidate.LIST, scan_statuses), + "page": self.require(int, True), + "page_size": self.require(int, True) + } + + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + + query = self.build_query(filters) + if "_id" in query: + scan = self.get_object_by_id(self.COLLECTION, query, + [ObjectId, datetime], self.ID) + self.set_successful_response(resp, scan) + else: + scans_ids = self.get_objects_list(self.COLLECTION, query, + page, page_size, self.PROJECTION) + self.set_successful_response(resp, {"scans": scans_ids}) + + def on_post(self, req, resp): + self.log.debug("Posting new scan") + error, scan = self.get_content_from_request(req) + if error: + self.bad_request(error) + + scan_statuses = self.get_constants_by_name("scan_statuses") + log_levels = self.get_constants_by_name("log_levels") + + scan_requirements = { + "status": self.require(str, + validate=DataValidate.LIST, + requirement=scan_statuses, + mandatory=True), + "log_level": self.require(str, + validate=DataValidate.LIST, + requirement=log_levels), + "clear": self.require(bool, True), + "scan_only_inventory": self.require(bool, True), + "scan_only_links": self.require(bool, True), + "scan_only_cliques": self.require(bool, True), + "environment": self.require(str, mandatory=True), + "inventory": self.require(str), + "object_id": self.require(str) + } + self.validate_query_data(scan, scan_requirements) + scan_only_keys = [k for k in scan if k.startswith("scan_only_")] + if len(scan_only_keys) > 1: + self.bad_request("multiple scan_only_* flags found: {0}. " + "only one of them can be set." + .format(", ".join(scan_only_keys))) + + env_name = scan["environment"] + if not self.check_environment_name(env_name): + self.bad_request("unkown environment: " + env_name) + + scan["scan_completed"] = False + scan["submit_timestamp"] = datetime.now() + self.write(scan, self.COLLECTION) + self.set_successful_response(resp, + {"message": "created a new scan for " + "environment {0}" + .format(env_name)}, + "201") + + def build_query(self, filters): + query = {} + filters_keys = ["status"] + self.update_query_with_filters(filters, filters_keys, query) + base_object = filters.get("base_object") + if base_object: + query['object_id'] = base_object + _id = filters.get("id") + if _id: + query['_id'] = _id + query['environment'] = filters['env_name'] + return query diff --git a/app/api/responders/resource/scheduled_scans.py b/app/api/responders/resource/scheduled_scans.py new file mode 100644 index 0000000..0588cd0 --- /dev/null +++ b/app/api/responders/resource/scheduled_scans.py @@ -0,0 +1,113 @@ +############################################################################### +# Copyright (c) 2017 Koren Lev (Cisco Systems), Yaron Yogev (Cisco Systems) # +# and others # +# # +# All rights reserved. This program and the accompanying materials # +# are made available under the terms of the Apache License, Version 2.0 # +# which accompanies this distribution, and is available at # +# http://www.apache.org/licenses/LICENSE-2.0 # +############################################################################### +from api.validation.data_validate import DataValidate +from api.responders.responder_base import ResponderBase +from bson.objectid import ObjectId +from datetime import datetime + + +class ScheduledScans(ResponderBase): + def __init__(self): + super().__init__() + self.COLLECTION = "scheduled_scans" + self.ID = "_id" + self.PROJECTION = { + self.ID: True, + "environment": True, + "scheduled_timestamp": True, + "freq": True + } + self.SCAN_FREQ = [ + "YEARLY", + "MONTHLY", + "WEEKLY", + "DAILY", + "HOURLY" + ] + + def on_get(self, req, resp): + self.log.debug("Getting scheduled scans") + filters = self.parse_query_params(req) + + filters_requirements = { + "environment": self.require(str, mandatory=True), + "id": self.require(ObjectId, True), + "freq": self.require(str, False, + DataValidate.LIST, self.SCAN_FREQ), + "page": self.require(int, True), + "page_size": self.require(int, True) + } + + self.validate_query_data(filters, filters_requirements) + page, page_size = self.get_pagination(filters) + + query = self.build_query(filters) + if self.ID in query: + scheduled_scan = self.get_object_by_id(self.COLLECTION, query, + [ObjectId, datetime], + self.ID) + self.set_successful_response(resp, scheduled_scan) + else: + scheduled_scan_ids = self.get_objects_list(self.COLLECTION, query, + page, page_size, + self.PROJECTION, + [datetime]) + self.set_successful_response(resp, + {"scheduled_scans": scheduled_scan_ids}) + + def on_post(self, req, resp): + self.log.debug("Posting new scheduled scan") + error, scheduled_scan = self.get_content_from_request(req) + if error: + self.bad_request(error) + + log_levels = self.get_constants_by_name("log_levels") + scheduled_scan_requirements = { + "environment": self.require(str, mandatory=True), + "scan_only_links": self.require(bool, True), + "scan_only_cliques": self.require(bool, True), + "scan_only_inventory": self.require(bool, True), + "freq": self.require(str, validate=DataValidate.LIST, + requirement=self.SCAN_FREQ, + mandatory=True), + "log_level": self.require(str, + validate=DataValidate.LIST, + requirement=log_levels), + "clear": self.require(bool, True), + "submit_timestamp": self.require(str, mandatory=True) + } + self.validate_query_data(scheduled_scan, scheduled_scan_requirements) + self.check_and_convert_datetime("submit_timestamp", scheduled_scan) + scan_only_keys = [k for k in scheduled_scan if k.startswith("scan_only_")] + if len(scan_only_keys) > 1: + self.bad_request("multiple scan_only_* flags found: {0}. " + "only one of them can be set." + .format(", ".join(scan_only_keys))) + + env_name = scheduled_scan["environment"] + if not self.check_environment_name(env_name): + self.bad_request("unkown environment: " + env_name) + + self.write(scheduled_scan, self.COLLECTION) + self.set_successful_response(resp, + {"message": "created a new scheduled scan for " + "environment {0}" + .format(env_name)}, + "201") + + def build_query(self, filters): + query = {} + filters_keys = ["freq", "environment"] + self.update_query_with_filters(filters, filters_keys, query) + + _id = filters.get("id") + if _id: + query["_id"] = _id + return query |