blob: 70f430c5772303d1b2abc0c04662d32dc344f913 [file] [log] [blame]
ac2550ead10512018-10-05 13:50:23 +02001#!/usr/bin/env python
2###
3# ============LICENSE_START=======================================================
4# ONAP CLAMP
5# ================================================================================
6# Copyright (C) 2018 AT&T Intellectual Property. All rights
7# reserved.
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
12#
13# http://www.apache.org/licenses/LICENSE-2.0
14#
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# ===================================================================
22#
23###
24import json
25import logging
26import os
27import sys
28
29import requests
30
31if sys.version_info < (3,):
32 # for HTTPStatus.OK only
33 import httplib as HTTPStatus
34else:
35 from http import HTTPStatus
36
37
38
39OBJECT_TYPES = ['index-pattern', 'config', 'search', 'visualization', 'dashboard']
40
41def parse_args(args):
42 """ Parse arguments given to this script"""
43 import argparse
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',
50 default='./default',
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])
54 )
55 )
56 parser.add_argument('-H', '--kibana-host', default='http://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.')
61
62 return parser.parse_args(args)
63
64def get_logger(args):
65 """Creates the logger based on the provided arguments"""
66 logging.basicConfig()
67 logger = logging.getLogger(__name__)
68 logger.setLevel(args.log_level)
69 return logger
70
71def main():
72 ''' Main script function'''
73 args = parse_args(sys.argv[1:])
74 logger = get_logger(args)
75 base_config_path = args.configuration_path
76
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))
80
81 if not os.path.exists(obj_dir):
82 logger.info('No %s to restore, skipping.', obj_type)
83 continue
84
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()
88
89 obj = json.loads(payload)
90
91 obj_id = obj['id']
92 for key in ('id', 'version', 'type', 'updated_at'):
ac255097705c82018-10-09 16:43:55 +020093 try:
94 del obj[key]
95 except KeyError:
96 logger.info("Could not find key %s in %s[%s]", key, obj_type, obj_id)
ac2550ead10512018-10-05 13:50:23 +020097
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,
102 headers={'content-type': 'application/json',
103 'kbn-xsrf': 'True'},
104 params=params,
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)
108 else:
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)
113
114if __name__ == "__main__":
115 main()