Merge "Add reporting results for Danube 3.0"
[functest.git] / functest / api / resources / v1 / creds.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """
11 Resources to handle openstack related requests
12 """
13
14 import collections
15 import logging
16
17 from flask import jsonify
18
19 from functest.api.base import ApiResource
20 from functest.api.common import api_utils
21 from functest.cli.commands.cli_os import OpenStack
22 from functest.utils import openstack_utils as os_utils
23 from functest.utils.constants import CONST
24
25 LOGGER = logging.getLogger(__name__)
26
27
28 class V1Creds(ApiResource):
29     """ V1Creds Resource class"""
30
31     def get(self):  # pylint: disable=no-self-use
32         """ Get credentials """
33         os_utils.source_credentials(CONST.__getattribute__('openstack_creds'))
34         credentials_show = OpenStack.show_credentials()
35         return jsonify(credentials_show)
36
37     def post(self):
38         """ Used to handle post request """
39         return self._dispatch_post()
40
41     def update_openrc(self, args):  # pylint: disable=no-self-use
42         """ Used to update the OpenStack RC file """
43         try:
44             openrc_vars = args['openrc']
45         except KeyError:
46             return api_utils.result_handler(
47                 status=0, data='openrc must be provided')
48         else:
49             if not isinstance(openrc_vars, collections.Mapping):
50                 return api_utils.result_handler(
51                     status=0, data='args should be a dict')
52
53         lines = ['export {}={}\n'.format(k, v) for k, v in openrc_vars.items()]
54
55         rc_file = CONST.__getattribute__('openstack_creds')
56         with open(rc_file, 'w') as creds_file:
57             creds_file.writelines(lines)
58
59         LOGGER.info("Sourcing the OpenStack RC file...")
60         try:
61             os_utils.source_credentials(rc_file)
62         except Exception as err:  # pylint: disable=broad-except
63             LOGGER.exception('Failed to source the OpenStack RC file')
64             return api_utils.result_handler(status=0, data=str(err))
65
66         return api_utils.result_handler(
67             status=0, data='Update openrc successfully')