3 # ============LICENSE_START=======================================================
5 # ================================================================================
6 # Copyright (C) 2018 AT&T Intellectual Property. All rights
8 # ================================================================================
9 # Licensed under the Apache License, Version 2.0 (the "License");
10 # you may not use this file except in compliance with the License.
11 # You may obtain a copy of the License at
13 # http://www.apache.org/licenses/LICENSE-2.0
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
20 # ============LICENSE_END============================================
21 # ===================================================================
31 if sys.version_info < (3,):
32 # for HTTPStatus.OK only
33 import httplib as HTTPStatus
35 from http import HTTPStatus
39 OBJECT_TYPES = ['index-pattern', 'config', 'search', 'visualization', 'dashboard']
42 """ Parse arguments given to this script"""
44 parser = argparse.ArgumentParser(
45 description=('Restores the kibana configuration.'))
46 parser.add_argument('-v', '--verbose', dest='log_level', action='store_const',
47 const=logging.DEBUG, default=logging.INFO,
48 help='Use verbose logging')
49 parser.add_argument('-C', '--configuration_path',
51 help=('Path of the configuration to be restored.'
52 'Should contain at least one folder named %s or %s' %
53 (','.join(OBJECT_TYPES[:-1]), OBJECT_TYPES[-1])
56 parser.add_argument('-H', '--kibana-host', default='https://localhost:5601',
57 help='Kibana endpoint.')
58 parser.add_argument('-f', '--force', action='store_const',
59 const=True, default=False,
60 help='Overwrite configuration if needed.')
62 return parser.parse_args(args)
65 """Creates the logger based on the provided arguments"""
67 logger = logging.getLogger(__name__)
68 logger.setLevel(args.log_level)
72 ''' Main script function'''
73 args = parse_args(sys.argv[1:])
74 logger = get_logger(args)
75 base_config_path = args.configuration_path
77 # order to ensure dependency order is ok
78 for obj_type in OBJECT_TYPES:
79 obj_dir = os.path.sep.join((base_config_path, obj_type))
81 if not os.path.exists(obj_dir):
82 logger.info('No %s to restore, skipping.', obj_type)
85 for obj_filename in os.listdir(obj_dir):
86 with open(os.path.sep.join((obj_dir, obj_filename))) as obj_file:
87 payload = obj_file.read()
89 obj = json.loads(payload)
92 for key in ('id', 'version', 'type', 'updated_at'):
96 logger.info("Could not find key %s in %s[%s]", key, obj_type, obj_id)
98 logger.info('Restoring %s id:%s (overwrite:%s)', obj_type, obj_id, args.force)
99 url = "%s/api/saved_objects/%s/%s" % (args.kibana_host.rstrip("/"), obj_type, obj_id)
100 params = {'overwrite': True} if args.force else {}
101 post_object_req = requests.post(url, auth=('admin', 'admin'), verify=False,
102 headers={'content-type': 'application/json',
105 data=json.dumps(obj))
106 if post_object_req.status_code == HTTPStatus.OK:
107 logger.info('%s id:%s restored.', obj_type, obj_id)
109 logger.warning(('Something bad happend while restoring %s id:%s. '
110 ' Received status code: %s'),
111 obj_type, obj_id, post_object_req.status_code)
112 logger.warning('Body: %s', post_object_req.content)
114 if __name__ == "__main__":