diff options
Diffstat (limited to 'src/main')
18 files changed, 582 insertions, 151 deletions
diff --git a/src/main/docker/kibana/Dockerfile.kibana b/src/main/docker/kibana/Dockerfile.kibana new file mode 100644 index 000000000..993edd4a2 --- /dev/null +++ b/src/main/docker/kibana/Dockerfile.kibana @@ -0,0 +1,58 @@ +### +# ============LICENSE_START======================================================= +# ONAP CLAMP +# ================================================================================ +# Copyright (C) 2018 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END============================================ +# =================================================================== +# +### + +FROM docker.elastic.co/kibana/kibana-oss:6.1.3 + +MAINTAINER "The Onap Team" +LABEL Description="Kibana image with saved objects loading" +USER root +RUN yum install -y python-requests && yum clean all + +# You can share volume on this folder to restore +# a default kibana configuration. Each subfolder will +# be considered as a saved-object folder generated by, +# the backup.py script bundled with the image. +# Structure example : +# saved-objects/ +# └── default +# ├── config +# │ └── config-6.1.3.json +# ├── dashboard +# │ └── dashboard-e6a82230-c190-11e8-a550-27f2e3138fee.json +# ├── index-pattern +# │ └── index-pattern-3ecb1c70-c190-11e8-a550-27f2e3138fee.json +# ├── search +# │ └── search-abdd0440-c190-11e8-a550-27f2e3138fee.json +# └── visualization +# ├── visualization-cb896270-c190-11e8-a550-27f2e3138fee.json +# └── visualization-d837b120-c190-11e8-a550-27f2e3138fee.json + +RUN mkdir /saved-objects/ + +USER kibana + +ADD saved-objects /saved-objects +ADD startup.sh /usr/local/bin/startup.sh +ADD restore.py /usr/local/bin/restore.py +ADD backup.py /usr/local/bin/backup.py +CMD /usr/local/bin/startup.sh diff --git a/src/main/docker/kibana/README.md b/src/main/docker/kibana/README.md new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/src/main/docker/kibana/README.md diff --git a/src/main/docker/kibana/backup.py b/src/main/docker/kibana/backup.py new file mode 100755 index 000000000..4127eb23c --- /dev/null +++ b/src/main/docker/kibana/backup.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python +### +# ============LICENSE_START======================================================= +# ONAP CLAMP +# ================================================================================ +# Copyright (C) 2018 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END============================================ +# =================================================================== +# +### + +import json +import logging +import os +import sys + +import requests + +PER_PAGE = 1000 + +def parse_args(args): + """ Parse arguments given to this script""" + import argparse + parser = argparse.ArgumentParser( + description=('Description of the script')) + parser.add_argument('-v', '--verbose', dest='log_level', action='store_const', + const=logging.DEBUG, default=logging.INFO, + help='Use verbose logging') + parser.add_argument('-C', '--configuration_path', + default='./default', + help='Path of the configuration to be backed up.') + parser.add_argument('-f', '--force', action='store_const', + const=True, default=False, + help=('If the save folder already exists, overwrite files' + ' matching a configuration item that should be written.' + ' Files already in the folder that do not match are' + ' left as-is.')) + parser.add_argument('-H', '--kibana-host', default='http://localhost:5601', + help='Kibana endpoint.') + + return parser.parse_args(args) + +def get_logger(args): + """Creates the logger based on the provided arguments""" + logging.basicConfig() + logger = logging.getLogger(__name__) + logger.setLevel(args.log_level) + return logger + +def main(): + """ This script dumps the kibana configuration from Kibana""" + args = parse_args(sys.argv[1:]) + + base_config_path = args.configuration_path + + # get list of all objects available + url = "%s/api/saved_objects/" % (args.kibana_host.rstrip("/"),) + saved_objects_req = requests.get(url, + params={'per_page': PER_PAGE}) + + saved_objects = saved_objects_req.json()['saved_objects'] + + for obj in saved_objects: + + obj_folder = os.path.sep.join((base_config_path, obj['type'])) + + if not os.path.exists(obj_folder): + os.makedirs(obj_folder) + + filename = "%s/%s-%s.json" % (obj_folder, obj['type'], obj['id']) + with open(filename, 'w') as file: + json.dump(obj, fp=file) + + +if __name__ == "__main__": + main() diff --git a/src/main/docker/kibana/restore.py b/src/main/docker/kibana/restore.py new file mode 100755 index 000000000..f58701bba --- /dev/null +++ b/src/main/docker/kibana/restore.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +### +# ============LICENSE_START======================================================= +# ONAP CLAMP +# ================================================================================ +# Copyright (C) 2018 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END============================================ +# =================================================================== +# +### +import json +import logging +import os +import sys + +import requests + +if sys.version_info < (3,): + # for HTTPStatus.OK only + import httplib as HTTPStatus +else: + from http import HTTPStatus + + + +OBJECT_TYPES = ['index-pattern', 'config', 'search', 'visualization', 'dashboard'] + +def parse_args(args): + """ Parse arguments given to this script""" + import argparse + parser = argparse.ArgumentParser( + description=('Restores the kibana configuration.')) + parser.add_argument('-v', '--verbose', dest='log_level', action='store_const', + const=logging.DEBUG, default=logging.INFO, + help='Use verbose logging') + parser.add_argument('-C', '--configuration_path', + default='./default', + help=('Path of the configuration to be restored.' + 'Should contain at least one folder named %s or %s' % + (','.join(OBJECT_TYPES[:-1]), OBJECT_TYPES[-1]) + ) + ) + parser.add_argument('-H', '--kibana-host', default='http://localhost:5601', + help='Kibana endpoint.') + parser.add_argument('-f', '--force', action='store_const', + const=True, default=False, + help='Overwrite configuration if needed.') + + return parser.parse_args(args) + +def get_logger(args): + """Creates the logger based on the provided arguments""" + logging.basicConfig() + logger = logging.getLogger(__name__) + logger.setLevel(args.log_level) + return logger + +def main(): + ''' Main script function''' + args = parse_args(sys.argv[1:]) + logger = get_logger(args) + base_config_path = args.configuration_path + + # order to ensure dependency order is ok + for obj_type in OBJECT_TYPES: + obj_dir = os.path.sep.join((base_config_path, obj_type)) + + if not os.path.exists(obj_dir): + logger.info('No %s to restore, skipping.', obj_type) + continue + + for obj_filename in os.listdir(obj_dir): + with open(os.path.sep.join((obj_dir, obj_filename))) as obj_file: + payload = obj_file.read() + + obj = json.loads(payload) + + obj_id = obj['id'] + for key in ('id', 'version', 'type', 'updated_at'): + del obj[key] + + logger.info('Restoring %s id:%s (overwrite:%s)', obj_type, obj_id, args.force) + url = "%s/api/saved_objects/%s/%s" % (args.kibana_host.rstrip("/"), obj_type, obj_id) + params = {'overwrite': True} if args.force else {} + post_object_req = requests.post(url, + headers={'content-type': 'application/json', + 'kbn-xsrf': 'True'}, + params=params, + data=json.dumps(obj)) + if post_object_req.status_code == HTTPStatus.OK: + logger.info('%s id:%s restored.', obj_type, obj_id) + else: + logger.warning(('Something bad happend while restoring %s id:%s. ' + ' Received status code: %s'), + obj_type, obj_id, post_object_req.status_code) + logger.warning('Body: %s', post_object_req.content) + +if __name__ == "__main__": + main() diff --git a/src/main/docker/kibana/saved-objects/default/config/config-6.1.3.json b/src/main/docker/kibana/saved-objects/default/config/config-6.1.3.json new file mode 100644 index 000000000..196e147bc --- /dev/null +++ b/src/main/docker/kibana/saved-objects/default/config/config-6.1.3.json @@ -0,0 +1 @@ +{"attributes": {"buildNum": 16371, "defaultIndex": "3ecb1c70-c190-11e8-a550-27f2e3138fee"}, "type": "config", "id": "6.1.3", "version": 2, "updated_at": "2018-09-26T13:29:53.056Z"}
\ No newline at end of file diff --git a/src/main/docker/kibana/saved-objects/default/dashboard/dashboard-e6a82230-c190-11e8-a550-27f2e3138fee.json b/src/main/docker/kibana/saved-objects/default/dashboard/dashboard-e6a82230-c190-11e8-a550-27f2e3138fee.json new file mode 100644 index 000000000..65afdf789 --- /dev/null +++ b/src/main/docker/kibana/saved-objects/default/dashboard/dashboard-e6a82230-c190-11e8-a550-27f2e3138fee.json @@ -0,0 +1 @@ +{"attributes": {"panelsJSON": "[{\"gridData\":{\"w\":6,\"h\":3,\"x\":0,\"y\":0,\"i\":\"1\"},\"version\":\"6.1.3\",\"panelIndex\":\"1\",\"type\":\"visualization\",\"id\":\"d837b120-c190-11e8-a550-27f2e3138fee\"},{\"gridData\":{\"w\":6,\"h\":3,\"x\":6,\"y\":0,\"i\":\"2\"},\"version\":\"6.1.3\",\"panelIndex\":\"2\",\"type\":\"visualization\",\"id\":\"cb896270-c190-11e8-a550-27f2e3138fee\"}]", "uiStateJSON": "{}", "version": 1, "optionsJSON": "{\"darkTheme\":false,\"useMargins\":true,\"hidePanelTitles\":false}", "title": "Counts", "hits": 0, "description": "", "kibanaSavedObjectMeta": {"searchSourceJSON": "{\"query\":{\"query\":\"\",\"language\":\"lucene\"},\"filter\":[],\"highlightAll\":true,\"version\":true}"}, "timeRestore": false}, "type": "dashboard", "id": "e6a82230-c190-11e8-a550-27f2e3138fee", "version": 1, "updated_at": "2018-09-26T13:34:32.403Z"}
\ No newline at end of file diff --git a/src/main/docker/kibana/saved-objects/default/index-pattern/index-pattern-3ecb1c70-c190-11e8-a550-27f2e3138fee.json b/src/main/docker/kibana/saved-objects/default/index-pattern/index-pattern-3ecb1c70-c190-11e8-a550-27f2e3138fee.json new file mode 100644 index 000000000..19041ec1a --- /dev/null +++ b/src/main/docker/kibana/saved-objects/default/index-pattern/index-pattern-3ecb1c70-c190-11e8-a550-27f2e3138fee.json @@ -0,0 +1 @@ +{"attributes": {"title": "events-*", "fields": "[{\"name\":\"@timestamp\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"@version\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"@version.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.cloud-region.identity-url\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.cloud-region.identity-url.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.complex.city\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.complex.city.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.complex.physical-location-id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.complex.physical-location-id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.complex.state\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.complex.state.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.generic-vnf.service-id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.generic-vnf.service-id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.generic-vnf.vnf-id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.generic-vnf.vnf-id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.generic-vnf.vnf-name\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.generic-vnf.vnf-name.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.generic-vnf.vnf-type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.generic-vnf.vnf-type.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.tenant.tenant-id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.tenant.tenant-id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.in-maint\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.in-maint.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.is-closed-loop-disabled\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.is-closed-loop-disabled.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.l-interface.interface-name\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.l-interface.interface-name.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.l-interface.l3-interface-ipv4-address-list.l3-inteface-ipv4-address\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.l-interface.l3-interface-ipv4-address-list.l3-inteface-ipv4-address.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.l-interface.network-name\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.l-interface.network-name.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.prov-status\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.prov-status.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.selflink\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.selflink.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.vserver-id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.vserver-id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"AAI.vserver.vserver-name\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"AAI.vserver.vserver-name.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"_id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_index\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"_score\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_source\",\"type\":\"_source\",\"count\":0,\"scripted\":false,\"searchable\":false,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"_type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false},{\"name\":\"action\",\"type\":\"string\",\"count\":1,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"action.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"closedLoopAlarmEnd\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"closedLoopAlarmStart\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"closedLoopControlName\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"closedLoopControlName.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"closedLoopEventClient\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"closedLoopEventClient.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"closedLoopEventStatus\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"closedLoopEventStatus.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eNodeB.cell_id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eNodeB.cell_id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eNodeB.common_id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eNodeB.common_id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eNodeB.datetime\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eNodeB.datetime.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eNodeB.ems_id\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eNodeB.ems_id.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eNodeB.oam_ip\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eNodeB.oam_ip.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eNodeB.software_version\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eNodeB.software_version.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eNodeB.vendor\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eNodeB.vendor.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"eventDetails\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"eventDetails.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"from\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"from.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.actor\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"history.actor.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.end\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.message\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"history.message.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.operation\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"history.operation.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.outcome\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"history.outcome.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.start\",\"type\":\"number\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.subRequestId\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"history.subRequestId.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"history.target\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"history.target.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"host\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"host.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"message\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"message.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"notification\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"notification.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"notificationTime\",\"type\":\"date\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"path\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"path.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"policyName\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"policyName.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"policyScope\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"policyScope.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"policyVersion\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"policyVersion.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"requestID\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"requestID.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"resourceInstance.resourceInstanceName\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"resourceInstance.resourceInstanceName.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"resourceInstance.resourceName\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"resourceInstance.resourceName.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"serviceInstance.serviceInstanceName\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"serviceInstance.serviceInstanceName.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"serviceInstance.serviceName\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"serviceInstance.serviceName.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"status.code\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"status.code.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"status.description\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"status.description.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"subRequestID\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"subRequestID.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"target\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"target.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"target_type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"target_type.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"triggerID\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"triggerID.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"triggerSourceName\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"triggerSourceName.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"type\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"type.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"version\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":false,\"readFromDocValues\":false},{\"name\":\"version.keyword\",\"type\":\"string\",\"count\":0,\"scripted\":false,\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":true},{\"name\":\"isReset\",\"type\":\"boolean\",\"count\":0,\"scripted\":true,\"script\":\"doc['action.keyword'].value == 'Reset'\",\"lang\":\"painless\",\"searchable\":true,\"aggregatable\":true,\"readFromDocValues\":false}]", "fieldFormatMap": "{\"isReset\":{\"id\":\"boolean\"}}", "timeFieldName": "@timestamp"}, "type": "index-pattern", "id": "3ecb1c70-c190-11e8-a550-27f2e3138fee", "version": 14, "updated_at": "2018-09-26T13:46:43.472Z"}
\ No newline at end of file diff --git a/src/main/docker/kibana/saved-objects/default/search/search-abdd0440-c190-11e8-a550-27f2e3138fee.json b/src/main/docker/kibana/saved-objects/default/search/search-abdd0440-c190-11e8-a550-27f2e3138fee.json new file mode 100644 index 000000000..1ebc06c63 --- /dev/null +++ b/src/main/docker/kibana/saved-objects/default/search/search-abdd0440-c190-11e8-a550-27f2e3138fee.json @@ -0,0 +1 @@ +{"attributes": {"sort": ["@timestamp", "desc"], "kibanaSavedObjectMeta": {"searchSourceJSON": "{\"index\":\"3ecb1c70-c190-11e8-a550-27f2e3138fee\",\"highlightAll\":true,\"version\":true,\"query\":{\"language\":\"lucene\",\"query\":\"\"},\"filter\":[{\"$state\":{\"store\":\"appState\"},\"meta\":{\"alias\":null,\"disabled\":false,\"index\":\"3ecb1c70-c190-11e8-a550-27f2e3138fee\",\"key\":\"action.keyword\",\"negate\":false,\"params\":{\"query\":\"Reset\",\"type\":\"phrase\"},\"type\":\"phrase\",\"value\":\"Reset\"},\"query\":{\"match\":{\"action.keyword\":{\"query\":\"Reset\",\"type\":\"phrase\"}}}}]}"}, "version": 1, "title": "Resets", "hits": 0, "description": "", "columns": ["action"]}, "type": "search", "id": "abdd0440-c190-11e8-a550-27f2e3138fee", "version": 2, "updated_at": "2018-09-26T13:33:28.694Z"}
\ No newline at end of file diff --git a/src/main/docker/kibana/saved-objects/default/visualization/visualization-cb896270-c190-11e8-a550-27f2e3138fee.json b/src/main/docker/kibana/saved-objects/default/visualization/visualization-cb896270-c190-11e8-a550-27f2e3138fee.json new file mode 100644 index 000000000..de2c037d1 --- /dev/null +++ b/src/main/docker/kibana/saved-objects/default/visualization/visualization-cb896270-c190-11e8-a550-27f2e3138fee.json @@ -0,0 +1 @@ +{"attributes": {"uiStateJSON": "{}", "kibanaSavedObjectMeta": {"searchSourceJSON": "{\"index\":\"3ecb1c70-c190-11e8-a550-27f2e3138fee\",\"filter\":[],\"query\":{\"query\":\"\",\"language\":\"lucene\"}}"}, "visState": "{\"title\":\"Counts\",\"type\":\"metric\",\"params\":{\"addTooltip\":true,\"addLegend\":false,\"type\":\"metric\",\"metric\":{\"percentageMode\":false,\"useRanges\":false,\"colorSchema\":\"Green to Red\",\"metricColorMode\":\"None\",\"colorsRange\":[{\"from\":0,\"to\":10000}],\"labels\":{\"show\":true},\"invertColors\":false,\"style\":{\"bgFill\":\"#000\",\"bgColor\":false,\"labelColor\":false,\"subText\":\"\",\"fontSize\":60}}},\"aggs\":[{\"id\":\"1\",\"enabled\":true,\"type\":\"count\",\"schema\":\"metric\",\"params\":{}}]}", "title": "Counts", "version": 1, "description": ""}, "type": "visualization", "id": "cb896270-c190-11e8-a550-27f2e3138fee", "version": 1, "updated_at": "2018-09-26T13:33:46.903Z"}
\ No newline at end of file diff --git a/src/main/docker/kibana/saved-objects/default/visualization/visualization-d837b120-c190-11e8-a550-27f2e3138fee.json b/src/main/docker/kibana/saved-objects/default/visualization/visualization-d837b120-c190-11e8-a550-27f2e3138fee.json new file mode 100644 index 000000000..65a355763 --- /dev/null +++ b/src/main/docker/kibana/saved-objects/default/visualization/visualization-d837b120-c190-11e8-a550-27f2e3138fee.json @@ -0,0 +1 @@ +{"attributes": {"savedSearchId": "abdd0440-c190-11e8-a550-27f2e3138fee", "uiStateJSON": "{}", "kibanaSavedObjectMeta": {"searchSourceJSON": "{\"filter\":[],\"query\":{\"query\":\"\",\"language\":\"lucene\"}}"}, "visState": "{\"title\":\"ResetsCount\",\"type\":\"metric\",\"params\":{\"addTooltip\":true,\"addLegend\":false,\"type\":\"metric\",\"metric\":{\"percentageMode\":false,\"useRanges\":false,\"colorSchema\":\"Green to Red\",\"metricColorMode\":\"None\",\"colorsRange\":[{\"from\":0,\"to\":10000}],\"labels\":{\"show\":true},\"invertColors\":false,\"style\":{\"bgFill\":\"#000\",\"bgColor\":false,\"labelColor\":false,\"subText\":\"\",\"fontSize\":60}}},\"aggs\":[{\"id\":\"1\",\"enabled\":true,\"type\":\"count\",\"schema\":\"metric\",\"params\":{}}]}", "title": "ResetsCount", "version": 1, "description": ""}, "type": "visualization", "id": "d837b120-c190-11e8-a550-27f2e3138fee", "version": 1, "updated_at": "2018-09-26T13:34:08.178Z"}
\ No newline at end of file diff --git a/src/main/docker/kibana/startup.sh b/src/main/docker/kibana/startup.sh new file mode 100755 index 000000000..bbd9d45d9 --- /dev/null +++ b/src/main/docker/kibana/startup.sh @@ -0,0 +1,81 @@ +#!/bin/bash -x +### +# ============LICENSE_START======================================================= +# ONAP CLAMP +# ================================================================================ +# Copyright (C) 2018 AT&T Intellectual Property. All rights +# reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END============================================ +# =================================================================== +# +### +KIBANA_CONF_FILE="/usr/share/kibana/config/kibana.yml" +SAVED_OBJECTS_ROOT="/saved-objects/" +RESTORE_CMD="/usr/local/bin/restore.py -H http://127.0.0.1:5601/ -f" +BACKUP_BIN="/usr/local/bin/backup.py" +KIBANA_START_CMD="/usr/local/bin/kibana-docker" +LOG_FILE="/tmp/load.kibana.log" +KIBANA_LOAD_CMD="/usr/local/bin/kibana-docker -H 127.0.0.1 -l $LOG_FILE" +TIMEOUT=60 +WAIT_TIME=2 + +if [ -n "$(ls -A ${SAVED_OBJECTS_PATH})" ]; +then + echo "---- Saved objects found, restoring files." + + $KIBANA_LOAD_CMD & + KIB_PID=$! + + # Wait for log file to be avaiable + LOG_TIMEOUT=60 + while [ ! -f $LOG_FILE ] && [ "$LOG_TIMEOUT" -gt "0" ]; + do + echo "Waiting for $LOG_FILE to be available..." + sleep $WAIT_TIME + let LOG_TIMEOUT=$LOG_TIMEOUT-$WAIT_TIME + done + + tail -f $LOG_FILE & + LOG_PID=$! + + # Wait for kibana to be listening + while [ -z "$(grep "Server running at" $LOG_FILE)" ] && [ "$TIMEOUT" -gt "0" ]; + do + echo "Waiting for kibana to start..." + sleep $WAIT_TIME + let TIMEOUT=$TIMEOUT-$WAIT_TIME + done + sleep 1 + + # restore files + for saved_objects_path in $SAVED_OBJECTS_ROOT/* + do + echo "Restoring content of $saved_objects_path" + $RESTORE_CMD -C $saved_objects_path + sleep 1 + done + + # cleanup + kill $KIB_PID + kill $LOG_PID +else + echo "---- No saved object found" + ls -A ${SAVED_OBJECTS_PATH} +fi + +echo "---- Starting kibana" + +$KIBANA_START_CMD + diff --git a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java index 9287abbce..fb91d9c57 100644 --- a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java @@ -27,7 +27,6 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import java.io.UnsupportedEncodingException; -import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Handler; @@ -39,14 +38,13 @@ import org.onap.clamp.clds.model.properties.Policy; import org.onap.clamp.clds.model.properties.PolicyChain; import org.onap.clamp.clds.model.properties.PolicyItem; import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.policy.api.AttributeType; import org.onap.policy.controlloop.policy.builder.BuilderException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Send Guard Policy info to policy API. It uses the policy code to define - * the model and communicate with it. See also the PolicyClient class. + * Send Guard Policy info to policy API. It uses the policy code to define the + * model and communicate with it. See also the PolicyClient class. */ @Component public class GuardPolicyDelegate { @@ -74,25 +72,20 @@ public class GuardPolicyDelegate { */ @Handler public void execute(Exchange camelExchange) throws BuilderException, UnsupportedEncodingException { - String responseMessageGuard = null; ModelProperties prop = ModelProperties.create(camelExchange); Policy policy = prop.getType(Policy.class); if (policy.isFound()) { for (PolicyChain policyChain : prop.getType(Policy.class).getPolicyChains()) { - for(PolicyItem policyItem:policyChain.getPolicyItems()) { - if ("on".equals(policyItem.getEnableGuardPolicy())) - responseMessageGuard = createGuardPolicy(prop, policyItem); + for(PolicyItem policyItem:GuardPolicyAttributesConstructor.getAllPolicyGuardsFromPolicyChain(policyChain)) { + prop.setCurrentModelElementId(policy.getId()); + prop.setPolicyUniqueId(policyChain.getPolicyId()); + prop.setGuardUniqueId(policyItem.getId()); + policyClient.sendGuardPolicy(GuardPolicyAttributesConstructor + .formatAttributes(prop, policyItem), prop, LoggingUtils.getRequestId(), policyItem); } } - if (responseMessageGuard != null) { - camelExchange.setProperty("guardPolicyResponseMessage", responseMessageGuard.getBytes()); - } } } - private String createGuardPolicy(ModelProperties prop, PolicyItem policyItem) { - Map<AttributeType, Map<String, String>> attributes = GuardPolicyAttributesConstructor - .formatAttributes(refProp, prop, prop.getType(Policy.class).getId(), policyItem); - return policyClient.sendGuardPolicy(attributes, prop, LoggingUtils.getRequestId()); - } + } diff --git a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java index 9e8e1b8c5..36eb147de 100644 --- a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java @@ -28,11 +28,14 @@ import com.att.eelf.configuration.EELFManager; import org.apache.camel.Exchange; import org.apache.camel.Handler; +import org.onap.clamp.clds.client.req.policy.GuardPolicyAttributesConstructor; import org.onap.clamp.clds.client.req.policy.PolicyClient; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.properties.Policy; import org.onap.clamp.clds.model.properties.PolicyChain; +import org.onap.clamp.clds.model.properties.PolicyItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -45,9 +48,14 @@ public class GuardPolicyDeleteDelegate { protected static final EELFLogger logger = EELFManager.getInstance() .getLogger(GuardPolicyDeleteDelegate.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - @Autowired - private PolicyClient policyClient; + private final PolicyClient policyClient; + private final ClampProperties refProp; + @Autowired + public GuardPolicyDeleteDelegate(PolicyClient policyClient, ClampProperties refProp) { + this.policyClient = policyClient; + this.refProp = refProp; + } /** * Perform activity. Delete Operational Policy via policy api. * @@ -58,17 +66,18 @@ public class GuardPolicyDeleteDelegate { public void execute(Exchange camelExchange) { ModelProperties prop = ModelProperties.create(camelExchange); Policy policy = prop.getType(Policy.class); - prop.setCurrentModelElementId(policy.getId()); + String eventAction = (String) camelExchange.getProperty("eventAction"); - String responseMessage = ""; if (!eventAction.equalsIgnoreCase(CldsEvent.ACTION_CREATE) && policy.isFound()) { - for (PolicyChain policyChain : policy.getPolicyChains()) { - prop.setPolicyUniqueId(policyChain.getPolicyId()); - responseMessage = policyClient.deleteBrms(prop); - } - if (responseMessage != null) { - camelExchange.setProperty("operationalPolicyDeleteResponseMessage", responseMessage.getBytes()); + for (PolicyChain policyChain : prop.getType(Policy.class).getPolicyChains()) { + for(PolicyItem policyItem:GuardPolicyAttributesConstructor.getAllPolicyGuardsFromPolicyChain(policyChain)) { + prop.setCurrentModelElementId(policy.getId()); + prop.setPolicyUniqueId(policyChain.getPolicyId()); + prop.setGuardUniqueId(policyItem.getId()); + policyClient.deleteGuard(prop); + } } } } + } diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java b/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java index f11b492c0..de86faa21 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java @@ -26,13 +26,16 @@ package org.onap.clamp.clds.client.req.policy; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; -import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.model.properties.ModelProperties; +import org.onap.clamp.clds.model.properties.PolicyChain; import org.onap.clamp.clds.model.properties.PolicyItem; import org.onap.policy.api.AttributeType; +import org.onap.policy.api.RuleProvider; public class GuardPolicyAttributesConstructor { private static final EELFLogger logger = EELFManager.getInstance() @@ -41,24 +44,32 @@ public class GuardPolicyAttributesConstructor { private GuardPolicyAttributesConstructor() { } - public static Map<AttributeType, Map<String, String>> formatAttributes(ClampProperties refProp, - ModelProperties modelProperties, String modelElementId, PolicyItem policyItem) { - Map<String, String> matchingAttributes = prepareMatchingAttributes(refProp, policyItem, modelProperties); + public static Map<AttributeType, Map<String, String>> formatAttributes(ModelProperties modelProperties, PolicyItem policyItem) { + Map<String, String> matchingAttributes = prepareMatchingAttributes(policyItem, modelProperties); return createAttributesMap(matchingAttributes); } - private static Map<String, String> prepareMatchingAttributes(ClampProperties refProp, - PolicyItem policyItem, ModelProperties modelProp) { + public static List<PolicyItem> getAllPolicyGuardsFromPolicyChain(PolicyChain policyChain) { + List<PolicyItem> listItem = new ArrayList<>(); + for (PolicyItem policyItem : policyChain.getPolicyItems()) { + if ("on".equals(policyItem.getEnableGuardPolicy())) { + listItem.add(policyItem); + } + } + return listItem; + } + + private static Map<String, String> prepareMatchingAttributes(PolicyItem policyItem, ModelProperties modelProp) { logger.info("Preparing matching attributes for guard..."); Map<String, String> matchingAttributes = new HashMap<>(); matchingAttributes.put("actor",policyItem.getActor()); matchingAttributes.put("recipe",policyItem.getRecipe()); matchingAttributes.put("targets",policyItem.getGuardTargets()); matchingAttributes.put("clname",modelProp.getControlNameAndPolicyUniqueId()); - if ("MinMax".equals(policyItem.getGuardPolicyType())) { + if (RuleProvider.GUARD_MIN_MAX.equals(RuleProvider.valueOf(policyItem.getGuardPolicyType()))) { matchingAttributes.put("min",policyItem.getMinGuard()); matchingAttributes.put("max",policyItem.getMaxGuard()); - } else if ("FrequencyLimiter".equals(policyItem.getGuardPolicyType())) { + } else if (RuleProvider.GUARD_YAML.equals(RuleProvider.valueOf(policyItem.getGuardPolicyType()))) { matchingAttributes.put("limit",policyItem.getLimitGuard()); matchingAttributes.put("timeWindow",policyItem.getTimeWindowGuard()); matchingAttributes.put("timeUnits",policyItem.getTimeUnitsGuard()); diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java index 58366d954..c26b15ce7 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java @@ -37,11 +37,13 @@ import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.config.PolicyConfiguration; import org.onap.clamp.clds.exception.policy.PolicyClientException; import org.onap.clamp.clds.model.properties.ModelProperties; +import org.onap.clamp.clds.model.properties.PolicyItem; import org.onap.clamp.clds.util.LoggingUtils; import org.onap.policy.api.AttributeType; import org.onap.policy.api.ConfigRequestParameters; import org.onap.policy.api.DeletePolicyCondition; import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.DictionaryType; import org.onap.policy.api.PolicyChangeResponse; import org.onap.policy.api.PolicyClass; import org.onap.policy.api.PolicyConfigException; @@ -74,6 +76,8 @@ public class PolicyClient { public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix"; public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix"; public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type"; + public static final String POLICY_GUARD_SUFFIX = "_Guard"; + @Autowired protected ApplicationContext appContext; @Autowired @@ -85,33 +89,32 @@ public class PolicyClient { * Perform Guard policy type. * * @param attributes - * A map of attributes + * A map of attributes * @param prop - * The ModelProperties + * The ModelProperties * @param policyRequestUuid - * PolicyRequest UUID + * PolicyRequest UUID * @return The response message of policy */ public String sendGuardPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop, - String policyRequestUuid) { + String policyRequestUuid, PolicyItem policyItem) { PolicyParameters policyParameters = new PolicyParameters(); // Set Policy Type(Mandatory) policyParameters.setPolicyClass(PolicyClass.Decision); // Set Policy Name(Mandatory) - policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId()+"Guard"); + policyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId()); // documentation says this is options, but when tested, got the // following failure: java.lang.Exception: Policy send failed: PE300 - // Data Issue: No policyDescription given. policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription")); policyParameters.setOnapName("PDPD"); - policyParameters.setRuleProvider(RuleProvider.GUARD_YAML); + policyParameters.setRuleProvider(RuleProvider.valueOf(policyItem.getGuardPolicyType())); policyParameters.setAttributes(attributes); // Set a random UUID(Mandatory) policyParameters.setRequestID(UUID.fromString(policyRequestUuid)); - String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME); - String rtnMsg = send(policyParameters, prop, policyNamePrefix); - String policyType = "Decision"; - push(policyType, prop); + + String rtnMsg = send(policyParameters, prop, null); + push(DictionaryType.Decision.toString(), prop); return rtnMsg; } @@ -119,11 +122,11 @@ public class PolicyClient { * Perform BRMS policy type. * * @param attributes - * A map of attributes + * A map of attributes * @param prop - * The ModelProperties + * The ModelProperties * @param policyRequestUuid - * PolicyRequest UUID + * PolicyRequest UUID * @return The response message of policy */ public String sendBrmsPolicy(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop, @@ -151,11 +154,11 @@ public class PolicyClient { * Perform send of microservice policy in JSON. * * @param policyJson - * The policy JSON + * The policy JSON * @param prop - * The ModelProperties + * The ModelProperties * @param policyRequestUuid - * The policy Request UUID + * The policy Request UUID * @return The response message of policy */ public String sendMicroServiceInJson(String policyJson, ModelProperties prop, String policyRequestUuid) { @@ -181,14 +184,14 @@ public class PolicyClient { * Perform send of base policy in OTHER type. * * @param configBody - * The config policy string body + * The config policy string body * @param configPolicyName - * The config policy name of the component that has been - * pre-deployed in DCAE + * The config policy name of the component that has been pre-deployed in + * DCAE * @param prop - * The ModelProperties + * The ModelProperties * @param policyRequestUuid - * The policy request UUID + * The policy request UUID * @return The answer from policy call */ public String sendBasePolicyInOther(String configBody, String configPolicyName, ModelProperties prop, @@ -215,9 +218,9 @@ public class PolicyClient { * Perform send of Microservice policy in OTHER type. * * @param configBody - * The config policy string body + * The config policy string body * @param prop - * The ModelProperties + * The ModelProperties * @return The answer from policy call */ public String sendMicroServiceInOther(String configBody, ModelProperties prop) { @@ -238,12 +241,12 @@ public class PolicyClient { } /** - * Perform send of policy. + * Perform send of Configuration or Decision policies. * * @param policyParameters - * The PolicyParameters + * The PolicyParameters * @param prop - * The ModelProperties + * The ModelProperties * @return The response message of Policy */ protected String send(PolicyParameters policyParameters, ModelProperties prop, String policyNamePrefix) { @@ -256,7 +259,9 @@ public class PolicyClient { String responseMessage = ""; Date startTime = new Date(); try { - if (!checkPolicyExists(policyNamePrefix, prop)) { + if ((PolicyClass.Decision.equals(policyParameters.getPolicyClass()) && !checkDecisionPolicyExists(prop)) + || (PolicyClass.Config.equals(policyParameters.getPolicyClass()) + && !checkPolicyExists(policyNamePrefix, prop))) { LoggingUtils.setTargetContext("Policy", "createPolicy"); logger.info("Attempting to create policy for action=" + prop.getActionCd()); response = getPolicyEngine().createPolicy(policyParameters); @@ -292,9 +297,9 @@ public class PolicyClient { * Format and send push of policy. * * @param policyType - * The policy Type + * The policy Type * @param prop - * The ModelProperties + * The ModelProperties * @return The response message of policy */ protected String push(String policyType, ModelProperties prop) { @@ -305,7 +310,11 @@ public class PolicyClient { PushPolicyParameters pushPolicyParameters = new PushPolicyParameters(); // Parameter arguments if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) { - pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId()); + if (DictionaryType.Decision.toString().equals(policyType)) { + pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId()); + } else { + pushPolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId()); + } } else { pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName()); } @@ -344,36 +353,63 @@ public class PolicyClient { } /** + * Use list Decision policy to know if the decision policy exists. + * + * @param prop + * The model properties + * @return true if it exists, false otherwise + */ + protected boolean checkDecisionPolicyExists(ModelProperties prop) { + boolean policyexists = false; + + logger.info("Search in Policy Engine for DecisionpolicyName=" + prop.getPolicyScopeAndNameWithUniqueGuardId()); + try { + // No other choice than pushing to see if it exists or not + String response = push(DictionaryType.Decision.toString(), prop); + if (response != null) { + policyexists = true; + } + } catch (BadRequestException e) { + // just print warning - if no policy version found + logger.warn("Policy not found...policy name - " + prop.getPolicyScopeAndNameWithUniqueGuardId(), e); + } + return policyexists; + } + + /** * Use list Policy API to retrieve the policy. Return true if policy exists * otherwise return false. * * @param policyNamePrefix - * The Policy Name Prefix + * The Policy Name Prefix * @param prop - * The ModelProperties + * The ModelProperties * @return The response message from policy * @throws PolicyConfigException - * In case of issues with policy engine + * In case of issues with policy engine */ - protected boolean checkPolicyExists(String policyNamePrefix, ModelProperties prop) throws PolicyConfigException { + protected boolean checkPolicyExists(String policyNamePrefix, ModelProperties prop) { boolean policyexists = false; - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); String policyName = ""; - if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) { - policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + prop.getPolicyUniqueId(); - } else { - policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix); - } - logger.info("Search in Policy Engine for policyName=" + policyName); - configRequestParameters.setPolicyName(policyName); try { + + if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) { + policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix) + "_" + + prop.getPolicyUniqueId(); + } else { + policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix); + } + logger.info("Search in Policy Engine for policyName=" + policyName); + + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + configRequestParameters.setPolicyName(policyName); Collection<String> response = getPolicyEngine().listConfig(configRequestParameters); if (response != null && !response.isEmpty() && !response.contains("Policy Name: null")) { policyexists = true; } - } catch (PolicyConfigException e) { + } catch (PolicyConfigException e1) { // just print warning - if no policy version found - logger.warn("policy not found...policy name - " + policyName, e); + logger.warn("Policy not found...policy name - " + policyName, e1); } return policyexists; } @@ -398,7 +434,7 @@ public class PolicyClient { * Format and send delete Micro Service requests to Policy. * * @param prop - * The ModelProperties + * The ModelProperties * @return The response message from Policy */ public String deleteMicrosService(ModelProperties prop) { @@ -420,7 +456,7 @@ public class PolicyClient { * This method delete the Base policy. * * @param prop - * The model Properties + * The model Properties * @return A string with the answer from policy */ public String deleteBasePolicy(ModelProperties prop) { @@ -431,15 +467,15 @@ public class PolicyClient { * Format and send delete Guard requests to Policy. * * @param prop - * The ModelProperties + * The ModelProperties * @return The response message from policy */ public String deleteGuard(ModelProperties prop) { String deletePolicyResponse = ""; try { - String policyNamePrefix = refProp.getStringValue(POLICY_OP_NAME_PREFIX_PROPERTY_NAME); - if (checkPolicyExists(policyNamePrefix, prop)) { - deletePolicyResponse = deletePolicy(prop, "Decision"); + + if (checkDecisionPolicyExists(prop)) { + deletePolicyResponse = deletePolicy(prop, DictionaryType.Decision.toString()); } } catch (Exception e) { logger.error("Exception occurred during policy communication", e); @@ -452,7 +488,7 @@ public class PolicyClient { * Format and send delete BRMS requests to Policy. * * @param prop - * The ModelProperties + * The ModelProperties * @return The response message from policy */ public String deleteBrms(ModelProperties prop) { @@ -474,13 +510,17 @@ public class PolicyClient { * Format and send delete PAP and PDP requests to Policy. * * @param prop - * The ModelProperties + * The ModelProperties * @return The response message from policy */ protected String deletePolicy(ModelProperties prop, String policyType) { DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters(); if (prop.getPolicyUniqueId() != null && !prop.getPolicyUniqueId().isEmpty()) { - deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId()); + if (DictionaryType.Decision.toString().equals(policyType)) { + deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueGuardId()); + } else { + deletePolicyParameters.setPolicyName(prop.getPolicyScopeAndNameWithUniqueId()); + } } else { deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName()); } @@ -503,9 +543,9 @@ public class PolicyClient { * Send delete request to Policy. * * @param deletePolicyParameters - * The DeletePolicyParameters + * The DeletePolicyParameters * @param prop - * The ModelProperties + * The ModelProperties * @return The response message from policy */ protected String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) { diff --git a/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java b/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java index d5f3ae228..f38e8c1c4 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/ModelProperties.java @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.model.properties; @@ -62,6 +62,8 @@ public class ModelProperties { private final Map<String, AbstractModelElement> modelElements = new ConcurrentHashMap<>(); private String currentModelElementId; private String policyUniqueId; + private String guardUniqueId; + public static final String POLICY_GUARD_SUFFIX = "_Guard_"; private static final Object lock = new Object(); private static Map<Class<? extends AbstractModelElement>, String> modelElementClasses = new ConcurrentHashMap<>(); static { @@ -91,7 +93,7 @@ public class ModelProperties { * The BPMN parameters for all boxes defined in modelBpmnTest */ public ModelProperties(String modelName, String controlName, String actionCd, boolean isATest, String modelBpmnText, - String modelPropText) { + String modelPropText) { try { this.modelName = modelName; this.controlName = controlName; @@ -118,19 +120,19 @@ public class ModelProperties { // Parse the list of base Model Elements and build up the // ModelElements modelElementClasses.entrySet().stream().parallel() - .filter(entry -> (AbstractModelElement.class.isAssignableFrom(entry.getKey()) - && missingTypes.contains(entry.getValue()))) - .forEach(entry -> { - try { - modelElements.put(entry.getValue(), - (entry.getKey() - .getConstructor(ModelProperties.class, ModelBpmn.class, JsonNode.class) - .newInstance(this, modelBpmn, modelJson))); - } catch (InstantiationException | NoSuchMethodException | IllegalAccessException - | InvocationTargetException e) { - logger.warn("Unable to instantiate a ModelElement, exception follows: ", e); - } - }); + .filter(entry -> (AbstractModelElement.class.isAssignableFrom(entry.getKey()) + && missingTypes.contains(entry.getValue()))) + .forEach(entry -> { + try { + modelElements.put(entry.getValue(), + (entry.getKey() + .getConstructor(ModelProperties.class, ModelBpmn.class, JsonNode.class) + .newInstance(this, modelBpmn, modelJson))); + } catch (InstantiationException | NoSuchMethodException | IllegalAccessException + | InvocationTargetException e) { + logger.warn("Unable to instantiate a ModelElement, exception follows: ", e); + } + }); } } @@ -234,7 +236,7 @@ public class ModelProperties { */ public String getPolicyNameForDcaeDeploy(ClampProperties refProp) { return normalizePolicyScopeName(modelName + createScopeSeparator(modelName) - + refProp.getStringValue(PolicyClient.POLICY_MS_NAME_PREFIX_PROPERTY_NAME) + getCurrentPolicyName()); + + refProp.getStringValue(PolicyClient.POLICY_MS_NAME_PREFIX_PROPERTY_NAME) + getCurrentPolicyName()); } /** @@ -242,7 +244,15 @@ public class ModelProperties { */ public String getPolicyScopeAndNameWithUniqueId() { return normalizePolicyScopeName( - modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_" + policyUniqueId); + modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_" + policyUniqueId); + } + + /** + * @return the policyScopeAndNameWithUniqueId + */ + public String getPolicyScopeAndNameWithUniqueGuardId() { + return normalizePolicyScopeName( + modelName + createScopeSeparator(modelName) + getCurrentPolicyName() + "_" + policyUniqueId+POLICY_GUARD_SUFFIX+guardUniqueId); } /** @@ -250,7 +260,7 @@ public class ModelProperties { */ public String getCurrentPolicyScopeAndFullPolicyName(String policyNamePrefix) { return normalizePolicyScopeName( - modelName + createScopeSeparator(modelName) + policyNamePrefix + getCurrentPolicyName()); + modelName + createScopeSeparator(modelName) + policyNamePrefix + getCurrentPolicyName()); } /** @@ -288,6 +298,14 @@ public class ModelProperties { return policyUniqueId; } + public String getGuardUniqueId() { + return guardUniqueId; + } + + public void setGuardUniqueId(String guardUniqueId) { + this.guardUniqueId = guardUniqueId; + } + /** * When generating a policy request for a model element, must set the unique * id of that policy using this method. Used to generate the policy name. @@ -318,17 +336,17 @@ public class ModelProperties { */ public boolean isCreateRequest() { switch (actionCd) { - case CldsEvent.ACTION_SUBMIT: - case CldsEvent.ACTION_RESTART: - return true; + case CldsEvent.ACTION_SUBMIT: + case CldsEvent.ACTION_RESTART: + return true; } return false; } public boolean isStopRequest() { switch (actionCd) { - case CldsEvent.ACTION_STOP: - return true; + case CldsEvent.ACTION_STOP: + return true; } return false; } @@ -344,7 +362,7 @@ public class ModelProperties { } public static final synchronized void registerModelElement(Class<? extends AbstractModelElement> modelElementClass, - String type) { + String type) { if (!modelElementClasses.containsKey(modelElementClass.getClass())) { modelElementClasses.put(modelElementClass, type); } diff --git a/src/main/resources/META-INF/resources/designer/partials/portfolios/PolicyWindow_properties.html b/src/main/resources/META-INF/resources/designer/partials/portfolios/PolicyWindow_properties.html index 25cc9a028..5a4600304 100644 --- a/src/main/resources/META-INF/resources/designer/partials/portfolios/PolicyWindow_properties.html +++ b/src/main/resources/META-INF/resources/designer/partials/portfolios/PolicyWindow_properties.html @@ -289,12 +289,11 @@ label { </div> <div class="col-sm-8"> <label for="guardPolicyType" class="col-sm-4 control-label"> - Guard Policy Type</label> - <select class="form-control" + Guard Policy Type</label> <select class="form-control" name="guardPolicyType" id="guardPolicyType" onchange="changeGuardPolicyType();"> - <option value="MinMax">MinMax</option> - <option value="FrequencyLimiter">FrequencyLimiter</option> + <option value="GUARD_MIN_MAX">MinMax</option> + <option value="GUARD_YAML">FrequencyLimiter</option> </select> </div> <label for="guardTargets" class="col-sm-4 control-label">Guard @@ -362,36 +361,51 @@ label { </div> <script> - - function initTargetResourceId() { - // Set all the Resource Invariant UUID in the target resource ID list (+Empty and other) - Object.keys(vf_Services["shared"]["byVf"]).forEach(function(key){ - $('#targetResourceId').append($('<option></option>').val(key).html(key)); - }); - } - - function changeTargetResourceIdOther() { - if ($("#targetResourceId").val()==="Other:") { - $("#targetResourceIdOther").show(); - } else { - $("#targetResourceIdOther").hide(); - $("#targetResourceIdOther").val(""); + function getAllFormId() { + return Array.from(document.getElementsByClassName("formId")); } - } - - function changeGuardPolicyType() { - console.log("executing GuardPolicyType") - console.log("GuardPolicyType value:"+$("#guardPolicyType").val()) - if ($("#guardPolicyType").val()==="MinMax") { - console.log("executing GuardPolicyType") - $("#minMaxGuardPolicyDiv").show(); - $("#frequencyLimiterGuardPolicyDiv").hide(); - } else if ($("#guardPolicyType").val()==="FrequencyLimiter") { - console.log("executing GuardPolicyType") - $("#minMaxGuardPolicyDiv").hide(); - $("#frequencyLimiterGuardPolicyDiv").show(); + + function searchActiveFormId() { + var formArray = getAllFormId(); + for (var i=0, max=formArray.length; i < max; i++) { + + console.log("Search active FormId, current element "+formArray[i].id); + if (formArray[i].style.display !== "none") { + console.log("Active form is:"+formArray[i].id); + return formArray[i]; + } + } + console.log("No active formId found !"); + } + + function initTargetResourceId() { + // Set all the Resource Invariant UUID in the target resource ID list (+Empty and other) + Object.keys(vf_Services["shared"]["byVf"]).forEach(function(key) { + $("#targetResourceId").append($('<option></option>').val(key).html(key)); + }); + + } + + function changeTargetResourceIdOther() { + var formItemActive = searchActiveFormId(); + if ($("#"+formItemActive.id+" #targetResourceId").val()==="Other:") { + $("#"+formItemActive.id+" #targetResourceIdOther").show(); + } else { + $("#"+formItemActive.id+" #targetResourceIdOther").hide(); + $("#"+formItemActive.id+" #targetResourceIdOther").val(""); + } + } + + function changeGuardPolicyType() { + var formItemActive = searchActiveFormId(); + if ($("#"+formItemActive.id+" #guardPolicyType").val()==="GUARD_MIN_MAX") { + $("#"+formItemActive.id+" #minMaxGuardPolicyDiv").show(); + $("#"+formItemActive.id+" #frequencyLimiterGuardPolicyDiv").hide(); + } else if ($("#"+formItemActive.id+" #guardPolicyType").val()==="GUARD_YAML") { + $("#"+formItemActive.id+" #minMaxGuardPolicyDiv").hide(); + $("#"+formItemActive.id+" #frequencyLimiterGuardPolicyDiv").show(); + } } - } //Basically this method will add a new form. All forms share the same class. When you want one form to show(active form) the other forms get the // css attribute display:none $("#add_one_more").click(function(event) { @@ -451,10 +465,10 @@ label { } if(el[i][j].name==="targetResourceIdOther" && el[i][j].value.toString()!=='') { // Add the entry and set it - $('#targetResourceId').append($('<option></option>').val($('#targetResourceIdOther').val()).html($('#targetResourceIdOther').val())); - $('#targetResourceId').val($('#targetResourceIdOther').val()); + $("#formId" + num + " #targetResourceId").append($('<option></option>').val($("#formId" + num + " #targetResourceIdOther").val()).html($("#formId" + num + " #targetResourceIdOther").val())); + $("#formId" + num + " #targetResourceId").val($("#formId" + num + " #targetResourceIdOther").val()); } - + changeGuardPolicyType(); } } } @@ -497,7 +511,7 @@ label { }); $('input[value="multiselect-all"]').prop('disabled', true).parent('li').addClass('disabled'); } - changeGuardPolicyType(); + } function addSelectListen(count) { @@ -904,7 +918,7 @@ label { initTargetResourceId(); //load metrics dropdown - if (elementMap["global"]){ + if (elementMap["global"]) { for (var i = 0; i < (elementMap["global"].length); i++){ if ((elementMap["global"][i]["name"]) == "actionSet"){ var asSel = elementMap["global"][i]["value"]; diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 0ecf01998..263c09d35 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -237,7 +237,7 @@ clamp.config.cadi.keyFile=classpath:/clds/aaf/org.onap.clamp.keyfile clamp.config.cadi.cadiLoglevel=DEBUG clamp.config.cadi.cadiLatitude=37.78187 clamp.config.cadi.cadiLongitude=-122.26147 -clamp.config.cadi.aafLocateUrl=https://onap-aaf:8095 +clamp.config.cadi.aafLocateUrl=https://aaf.api.simpledemo.onap.org:8095 clamp.config.cadi.cadiKeystorePassword=enc:V_kq_EwDNb4itWp_lYfDGXIWJzemHGkhkZOxAQI9IHs clamp.config.cadi.cadiTruststorePassword=enc:Mj0YQqNCUKbKq2lPp1kTFQWeqLxaBXKNwd5F1yB1ukf #clamp.config.cadi.oauthTokenUrl=https://AAF_LOCATE_URL/AAF_NS.token:2.0/token |