E2E Integration Test for NETCONF/TLS Configuration in SDNC.
[integration/csit.git] / tests / sdnc / sdnc_netconf_tls_post_deploy / libraries / ClientManager.py
1 # ============LICENSE_START=======================================================
2 #  Copyright (C) 2020 Nordix Foundation.
3 # ================================================================================
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 # SPDX-License-Identifier: Apache-2.0
17 # ============LICENSE_END=========================================================
18
19 __author__ = "Ajay Deep Singh (ajay.deep.singh@est.tech)"
20 __copyright__ = "Copyright (C) 2020 Nordix Foundation"
21 __license__ = "Apache 2.0"
22
23 import os
24 import shutil
25 import subprocess
26
27 import docker
28 from OpenSSL import crypto
29 from docker.types import Mount
30
31 DEV_NULL = open(os.devnull, 'wb')
32 NETCONF_PNP_SIM_CONTAINER_NAME = 'netconf-simulator'
33 ARCHIVES_PATH = os.getenv("WORKSPACE") + "/archives/"
34
35
36 class ClientManager:
37
38     def __init__(self, mount_path, truststore_path):
39         self.mount_path = mount_path
40         self.truststore_path = truststore_path
41         self.caCertPem = mount_path + '/ca.pem'
42         self.serverKeyPem = mount_path + '/server_key.pem'
43         self.serverCertPem = mount_path + '/server_cert.pem'
44         self.keystoreJksPath = mount_path + '/keystore.jks'
45         self.keystorePassPath = mount_path + '/keystore.pass'
46         self.truststoreJksPath = mount_path + '/truststore.jks'
47         self.truststorePassPath = mount_path + '/truststore.pass'
48
49     # Function Create docker container.
50     def run_client_container(self, client_image, container_name, path_to_env, request_url, network):
51         self.create_mount_dir()
52         client = docker.from_env()
53         environment = self.read_env_list_from_file(path_to_env)
54         environment.append("REQUEST_URL=" + request_url)
55         container = client.containers.run(
56             image=client_image,
57             name=container_name,
58             environment=environment,
59             network=network,
60             user='root',
61             mounts=[Mount(target='/var/certs', source=self.mount_path, type='bind'),
62                     Mount(target='/etc/onap/aaf/certservice/certs/', source=self.truststore_path, type='bind')],
63             detach=True
64         )
65         exitcode = container.wait()
66         return exitcode
67
68     # Function to validate keystore.jks/truststore.jks can be opened with generated pass-phrase.
69     def can_open_keystore_and_truststore_with_pass(self):
70         can_open_keystore = self.can_open_jks_file_with_pass_file(self.keystorePassPath, self.keystoreJksPath)
71         can_open_truststore = self.can_open_jks_file_with_pass_file(self.truststorePassPath, self.truststoreJksPath)
72         return can_open_keystore & can_open_truststore
73
74     # Method for Uploading Certificate in SDNC-Container.
75     # Creating/Uploading Server-key, Server-cert, Ca-cert PEM files in Netconf-Pnp-Simulator.
76     def can_install_keystore_and_truststore_certs(self, cmd, container_name):
77         continue_exec = True
78         if container_name == NETCONF_PNP_SIM_CONTAINER_NAME:
79             print("Generating PEM files for {0} from JKS files".format(container_name))
80             continue_exec = self.create_pem(self.keystorePassPath, self.keystoreJksPath, self.truststorePassPath,
81                                             self.truststoreJksPath)
82         if continue_exec:
83             print("Initiate Configuration Push for : {0}".format(container_name))
84             resp_code = self.execute_bash_config(cmd, container_name)
85             if resp_code == 0:
86                 print("Execution Successful for: {0}".format(container_name))
87                 return True
88             else:
89                 print("Execution Failed for: {0}".format(container_name))
90                 return False
91
92     def create_pem(self, keystore_pass_file_path, keystore_jks_file_path, truststore_pass_file_path,
93                    truststore_jks_file_path):
94         # Create [server_key.pem, server_cert.pem, ca.pem] files for Netconf-Pnp-Simulation/TLS Configuration.
95         try:
96             keystore_p12 = self.get_pkcs12(keystore_pass_file_path, keystore_jks_file_path)
97             truststore_p12 = self.get_pkcs12(truststore_pass_file_path, truststore_jks_file_path)
98             with open(self.serverKeyPem, "wb+") as key_file:
99                 key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, keystore_p12.get_privatekey()))
100             with open(self.serverCertPem, "wb+") as server_cert_file:
101                 server_cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, keystore_p12.get_certificate()))
102             with open(self.caCertPem, "wb+") as ca_cert_file:
103                 ca_cert_file.write(
104                     crypto.dump_certificate(crypto.FILETYPE_PEM, truststore_p12.get_ca_certificates()[0]))
105             return True
106         except IOError as err:
107             print("I/O Error: {0}".format(err))
108             return False
109         except Exception as e:
110             print("UnExpected Error: {0}".format(e))
111             return False
112
113     def can_open_jks_file_with_pass_file(self, pass_file_path, jks_file_path):
114         try:
115             if jks_file_path.split('/')[-1] == 'truststore.jks':
116                 pkcs12 = self.get_pkcs12(pass_file_path, jks_file_path).get_ca_certificates()[0]
117             else:
118                 pkcs12 = self.get_pkcs12(pass_file_path, jks_file_path).get_certificate()
119             if pkcs12 is None:
120                 return False
121             return True
122         except IOError as err:
123             print("I/O Error PKCS12 Creation failed: {0}".format(err))
124             return False
125         except Exception as e:
126             print("UnExpected Error PKCS12 Creation failed: {0}".format(e))
127             return False
128
129     def remove_client_container_and_save_logs(self, container_name, log_file_name):
130         client = docker.from_env()
131         container = client.containers.get(container_name)
132         text_file = open(ARCHIVES_PATH + container_name + '_' + log_file_name + ".log", "w")
133         text_file.write(container.logs())
134         text_file.close()
135         container.remove()
136         self.remove_mount_dir()
137
138     def create_mount_dir(self):
139         if not os.path.exists(self.mount_path):
140             os.makedirs(self.mount_path)
141
142     def remove_mount_dir(self):
143         shutil.rmtree(self.mount_path)
144
145     @staticmethod
146     def get_pkcs12(pass_file_path, jks_file_path):
147         # Load PKCS12 Object
148         password = open(pass_file_path, 'rb').read()
149         p12 = crypto.load_pkcs12(open(jks_file_path, 'rb').read(), password)
150         return p12
151
152     @staticmethod
153     def execute_bash_config(cmd, container_name):
154         # Run command with arguments. Wait for command to complete or timeout, return code attribute.
155         try:
156             resp_code = subprocess.call(["%s %s" % (cmd, container_name)], shell=True, stdout=DEV_NULL,
157                                         stderr=subprocess.STDOUT)
158             print("Response Code from Config.sh execution: {0}".format(resp_code))
159             return resp_code
160         except subprocess.CalledProcessError as e:
161             print("CalledProcessError Certificate installation failed in SDNC-ODL Container: {0}".format(e))
162             return 1  # Return Error Code
163
164     @staticmethod
165     def get_container_logs(container_name):
166         client = docker.from_env()
167         container = client.containers.get(container_name)
168         logs = container.logs()
169         return logs
170
171     @staticmethod
172     def read_env_list_from_file(path):
173         f = open(path, "r")
174         r_list = []
175         for line in f:
176             line = line.strip()
177             if line[0] != "#":
178                 r_list.append(line)
179         return r_list