3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
10 Resources to handle environment related requests
14 from flask import jsonify
16 from functest.api.base import ApiResource
17 from functest.api.common import api_utils
18 from functest.cli.commands.cli_env import Env
19 import functest.utils.functest_utils as ft_utils
22 class V1Envs(ApiResource):
23 """ V1Envs Resource class"""
25 def get(self): # pylint: disable=no-self-use
26 """ Get environment """
27 environment_show = Env().show()
28 return jsonify(environment_show)
31 """ Used to handle post request """
32 return self._dispatch_post()
34 def prepare(self, args): # pylint: disable=no-self-use, unused-argument
35 """ Prepare environment """
37 ft_utils.execute_command("prepare_env start")
38 except Exception as err: # pylint: disable=broad-except
39 return api_utils.result_handler(status=1, data=str(err))
40 return api_utils.result_handler(
41 status=0, data="Prepare env successfully")
43 def update_hosts(self, hosts_info): # pylint: disable=no-self-use
44 """ Update hosts info """
46 if not isinstance(hosts_info, dict):
47 return api_utils.result_handler(
48 status=1, data='Error, args should be a dict')
50 for key, value in hosts_info.items():
54 except Exception: # pylint: disable=broad-except
55 return api_utils.result_handler(
56 status=1, data='The IP %s is invalid' % value)
58 return api_utils.result_handler(
59 status=1, data='Domain name is absent')
62 functest_flag = "# SUT hosts info for Functest"
63 hosts_list = ('\n{} {} {}'.format(ip, host_name, functest_flag)
64 for host_name, ip in hosts_info.items())
66 with open("/etc/hosts", 'r') as file_hosts:
67 origin_lines = [line for line in file_hosts
68 if functest_flag not in line]
70 with open("/etc/hosts", 'w') as file_hosts:
71 file_hosts.writelines(origin_lines)
72 file_hosts.write(functest_flag)
73 file_hosts.writelines(hosts_list)
74 except Exception: # pylint: disable=broad-except
75 return api_utils.result_handler(
76 status=1, data='Error when updating hosts info')
78 return api_utils.result_handler(
79 status=0, data='Update hosts info successfully')