blob: 989a796ce5f9d545bddc74fca2a38d2b8adbcb3d [file] [log] [blame]
Gary Wu9abb61c2018-09-27 10:38:50 -07001from time import time
2
3from robot.api import logger
4import os.path
5import docker
6from io import BytesIO
7from os.path import basename
8from tarfile import TarFile, TarInfo
9
10LOCALHOST = "localhost"
11
12
13class VesHvContainersUtilsLibrary:
14
15 def get_consul_api_access_url(self, method, image_name, port):
16 return self.create_url(
17 method,
18 self.get_instance_address(image_name, port)
19 )
20
21 def get_xnf_sim_api_access_url(self, method, host):
22 if is_running_inside_docker():
23 return self.create_url(method, host)
24 else:
25 logger.info("File `/.dockerenv` not found. Assuming local environment and using localhost.")
26 port_from_container_name = str(host)[-4:]
27 return self.create_url(method, LOCALHOST + ":" + port_from_container_name)
28
29 def get_dcae_app_api_access_url(self, method, image_name, port):
30 return self.create_url(
31 method,
32 self.get_instance_address(image_name, port)
33 )
34
35 def get_instance_address(self, image_name, port):
36 if is_running_inside_docker():
37 return image_name + ":" + port
38 else:
39 logger.info("File `/.dockerenv` not found. Assuming local environment and using localhost.")
40 return LOCALHOST + ":" + port
41
42 def create_url(self, method, host_address):
43 return method + host_address
44
45def is_running_inside_docker():
46 return os.path.isfile("/.dockerenv")
47
48def copy_to_container(container_id, filepaths, path='/etc/ves-hv'):
49 with create_archive(filepaths) as archive:
50 docker.APIClient('unix:///var/run/docker.sock') \
51 .put_archive(container=container_id, path=(path), data=archive)
52
53
54def create_archive(filepaths):
55 tarstream = BytesIO()
56 tarfile = TarFile(fileobj=tarstream, mode='w')
57 for filepath in filepaths:
58 file = open(filepath, 'r')
59 file_data = file.read()
60
61 tarinfo = TarInfo(name=basename(file.name))
62 tarinfo.size = len(file_data)
63 tarinfo.mtime = time()
64
65 tarfile.addfile(tarinfo, BytesIO(file_data))
66
67 tarfile.close()
68 tarstream.seek(0)
69 return tarstream