Use casablanca latest image
[integration/csit.git] / tests / dcaegen2-collectors-hv-ves / testcases / libraries / XnfSimulatorLibrary.py
1 import HttpRequests
2 import os
3 import docker
4 from robot.api import logger
5 from time import sleep
6
7 XNF_SIMULATOR_NAME = "xNF Simulator"
8 SIMULATOR_IMAGE_NAME = "onap/org.onap.dcaegen2.collectors.hv-ves.hv-collector-xnf-simulator"
9 SIMULATOR_IMAGE_FULL_NAME = os.getenv("DOCKER_REGISTRY_PREFIX") + SIMULATOR_IMAGE_NAME + ":1.0-SNAPSHOT"
10 WORKSPACE_ENV = os.getenv("WORKSPACE")
11 certificates_dir_path = WORKSPACE_ENV + "/plans/dcaegen2-collectors-hv-ves/testsuites/ssl/"
12 collector_certs_lookup_dir = "/etc/ves-hv/"
13 ONE_SECOND_IN_NANOS = 10 ** 9
14
15
16 class XnfSimulatorLibrary:
17
18     def start_xnf_simulators(self, list_of_ports,
19                              should_use_valid_certs=True,
20                              should_disable_ssl=False,
21                              should_connect_to_unencrypted_hv_ves=False):
22         logger.info("Creating " + str(len(list_of_ports)) + " xNF Simulator containers")
23         dockerClient = docker.from_env()
24
25         self.pullImageIfAbsent(dockerClient)
26         logger.info("Using image: " + SIMULATOR_IMAGE_FULL_NAME)
27
28         simulators_addresses = self.create_containers(dockerClient,
29                                                       list_of_ports,
30                                                       should_use_valid_certs,
31                                                       should_disable_ssl,
32                                                       should_connect_to_unencrypted_hv_ves)
33
34         self.assert_containers_startup_was_successful(dockerClient)
35         dockerClient.close()
36         return simulators_addresses
37
38     def pullImageIfAbsent(self, dockerClient):
39         try:
40             dockerClient.images.get(SIMULATOR_IMAGE_FULL_NAME)
41         except:
42             logger.console("Image " + SIMULATOR_IMAGE_FULL_NAME + " will be pulled from repository. "
43                                                                   "This can take a while.")
44             dockerClient.images.pull(SIMULATOR_IMAGE_FULL_NAME)
45
46     def create_containers(self,
47                           dockerClient,
48                           list_of_ports,
49                           should_use_valid_certs,
50                           should_disable_ssl,
51                           should_connect_to_unencrypted_hv_ves):
52         simulators_addresses = []
53         for port in list_of_ports:
54             xnf = XnfSimulator(port, should_use_valid_certs, should_disable_ssl, should_connect_to_unencrypted_hv_ves)
55             container = self.run_simulator(dockerClient, xnf)
56             logger.info("Started container: " + container.name + "  " + container.id)
57             simulators_addresses.append(container.name + ":" + xnf.port)
58         return simulators_addresses
59
60     def run_simulator(self, dockerClient, xnf):
61         xNF_startup_command = xnf.get_startup_command()
62         xNF_healthcheck_command = xnf.get_healthcheck_command()
63         port = xnf.port
64         logger.info("Startup command: " + str(xNF_startup_command))
65         logger.info("Healthcheck command: " + str(xNF_healthcheck_command))
66         return dockerClient.containers.run(SIMULATOR_IMAGE_FULL_NAME,
67                                            command=xNF_startup_command,
68                                            healthcheck=xNF_healthcheck_command,
69                                            detach=True,
70                                            network="ves-hv-default",
71                                            ports={port + "/tcp": port},
72                                            volumes=self.container_volumes(),
73                                            name=xnf.container_name_prefix + port)
74
75     def container_volumes(self):
76         return {certificates_dir_path: {"bind": collector_certs_lookup_dir, "mode": 'rw'}}
77
78     def assert_containers_startup_was_successful(self, dockerClient):
79         checks_amount = 6
80         check_interval_in_seconds = 5
81         for _ in range(checks_amount):
82             sleep(check_interval_in_seconds)
83             all_containers_healthy = True
84             for container in self.get_simulators_list(dockerClient):
85                 all_containers_healthy = all_containers_healthy and self.is_container_healthy(container)
86             if (all_containers_healthy):
87                 return
88         raise ContainerException("One of xNF simulators containers did not pass the healthcheck.")
89
90     def is_container_healthy(self, container):
91         container_health = container.attrs['State']['Health']['Status']
92         return container_health == 'healthy' and container.status == 'running'
93
94     def stop_and_remove_all_xnf_simulators(self, suite_name):
95         dockerClient = docker.from_env()
96         for container in self.get_simulators_list(dockerClient):
97             logger.info("Stopping and removing container: " + container.id)
98             log_filename = WORKSPACE_ENV + "/archives/containers_logs/" + \
99                            suite_name.split(".")[-1] + "_" + container.name + ".log"
100             file = open(log_filename, "w+")
101             file.write(container.logs())
102             file.close()
103             container.stop()
104             container.remove()
105         dockerClient.close()
106
107     def get_simulators_list(self, dockerClient):
108         return dockerClient.containers.list(filters={"ancestor": SIMULATOR_IMAGE_FULL_NAME}, all=True)
109
110     def send_messages(self, simulator_url, message_filepath):
111         logger.info("Reading message to simulator from: " + message_filepath)
112
113         file = open(message_filepath, "rb")
114         data = file.read()
115         file.close()
116
117         logger.info("POST at: " + simulator_url)
118         resp = HttpRequests.session_without_env().post(simulator_url, data=data, timeout=5)
119         HttpRequests.checkStatusCode(resp.status_code, XNF_SIMULATOR_NAME)
120
121
122 class XnfSimulator:
123     container_name_prefix = "ves-hv-collector-xnf-simulator"
124
125     def __init__(self,
126                  port,
127                  should_use_valid_certs,
128                  should_disable_ssl,
129                  should_connect_to_unencrypted_hv_ves):
130         self.port = port
131         cert_name_prefix = "" if should_use_valid_certs else "untrusted"
132         certificates_path_with_file_prefix = collector_certs_lookup_dir + cert_name_prefix
133         self.key_store_path = certificates_path_with_file_prefix + "client.p12"
134         self.trust_store_path = certificates_path_with_file_prefix + "trust.p12"
135         self.sec_store_passwd = "onaponap"
136         self.disable_ssl = should_disable_ssl
137         self.hv_collector_host = "unencrypted-ves-hv-collector" \
138             if should_connect_to_unencrypted_hv_ves else "ves-hv-collector"
139
140     def get_startup_command(self):
141         startup_command = ["--listen-port", self.port,
142                            "--ves-host", self.hv_collector_host,
143                            "--ves-port", "6061",
144                            "--key-store", self.key_store_path,
145                            "--trust-store", self.trust_store_path,
146                            "--key-store-password", self.sec_store_passwd,
147                            "--trust-store-password", self.sec_store_passwd
148                            ]
149         if self.disable_ssl:
150             startup_command.append("--ssl-disable")
151         return startup_command
152
153     def get_healthcheck_command(self):
154         return {
155             "interval": 5 * ONE_SECOND_IN_NANOS,
156             "timeout": 3 * ONE_SECOND_IN_NANOS,
157             "retries": 1,
158             "test": ["CMD", "curl", "--request", "GET",
159                      "--fail", "--silent", "--show-error",
160                      "localhost:" + self.port + "/healthcheck"]
161         }
162
163
164 class ContainerException(Exception):
165     def __init__(self, message):
166         super(ContainerException, self).__init__(message)