SDNC-766: Refactoring of installCerts.py
[sdnc/oam.git] / installation / sdnc / src / main / scripts / installCerts.py
1 # ============LICENSE_START=======================================================
2 #  Copyright (C) 2019 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
20
21 # coding=utf-8
22 import os
23 import httplib
24 import base64
25 import time
26 import zipfile
27 import shutil
28
29 Path = "/tmp"
30
31 zipFileList = []
32
33 username = os.environ['ODL_ADMIN_USERNAME']
34 password = os.environ['ODL_ADMIN_PASSWORD']
35 TIMEOUT=1000
36 INTERVAL=30
37 timePassed=0
38
39 postKeystore= "/restconf/operations/netconf-keystore:add-keystore-entry"
40 postPrivateKey= "/restconf/operations/netconf-keystore:add-private-key"
41 postTrustedCertificate= "/restconf/operations/netconf-keystore:add-trusted-certificate"
42
43
44 headers = {'Authorization':'Basic %s' % base64.b64encode(username + ":" + password),
45            'X-FromAppId': 'csit-sdnc',
46            'X-TransactionId': 'csit-sdnc',
47            'Accept':"application/json",
48            'Content-type':"application/json"}
49
50 def readFile(folder, file):
51     key = open(Path + "/" + folder + "/" + file, "r")
52     fileRead = key.read()
53     key.close()
54     fileRead = "\n".join(fileRead.splitlines()[1:-1])
55     return fileRead
56
57 def readTrustedCertificate(folder, file):
58     listCert = list()
59     caPem = ""
60     startCa = False
61     key = open(Path + "/" + folder + "/" + file, "r")
62     lines = key.readlines()
63     for line in lines:
64         if not "BEGIN CERTIFICATE" in line and not "END CERTIFICATE" in line and startCa:
65             caPem += line
66         elif "BEGIN CERTIFICATE" in line:
67             startCa = True
68         elif "END CERTIFICATE" in line:
69             startCa = False
70             listCert.append(caPem)
71             caPem = ""
72     return listCert
73
74 def makeKeystoreKey(clientKey, count):
75     odl_private_key="ODL_private_key_%d" %count
76
77     json_keystore_key='{{\"input\": {{ \"key-credential\": {{\"key-id\": \"{odl_private_key}\", \"private-key\" : ' \
78                       '\"{clientKey}\",\"passphrase\" : \"\"}}}}}}'.format(
79         odl_private_key=odl_private_key,
80         clientKey=clientKey)
81
82     return json_keystore_key
83
84
85
86 def makePrivateKey(clientKey, clientCrt, certList, count):
87     caPem = ""
88     for cert in certList:
89         caPem += '\"%s\",' % cert
90
91     caPem = caPem.rsplit(',', 1)[0]
92     odl_private_key="ODL_private_key_%d" %count
93
94     json_private_key='{{\"input\": {{ \"private-key\":{{\"name\": \"{odl_private_key}\", \"data\" : ' \
95                      '\"{clientKey}\",\"certificate-chain\":[\"{clientCrt}\",{caPem}]}}}}}}'.format(
96         odl_private_key=odl_private_key,
97         clientKey=clientKey,
98         clientCrt=clientCrt,
99         caPem=caPem)
100
101     return json_private_key
102
103 def makeTrustedCertificate(certList, count):
104     number = 0
105     json_cert_format = ""
106     for cert in certList:
107         cert_name = "xNF_CA_certificate_%d_%d" %(count, number)
108         json_cert_format += '{{\"name\": \"{trusted_name}\",\"certificate\":\"{cert}\"}},\n'.format(
109             trusted_name=cert_name,
110             cert=cert.strip())
111         number += 1
112
113     json_cert_format = json_cert_format.rsplit(',', 1)[0]
114     json_trusted_cert='{{\"input\": {{ \"trusted-certificate\": [{certificates}]}}}}'.format(
115         certificates=json_cert_format)
116     return json_trusted_cert
117
118
119 def makeRestconfPost(conn, json_file, apiCall):
120     req = conn.request("POST", apiCall, json_file, headers=headers)
121     res = conn.getresponse()
122     res.read()
123     if res.status != 200:
124         print "Error here, response back wasnt 200: Response was : %d , %s" % (res.status, res.reason)
125     else:
126         print res.status, res.reason
127
128 def extractZipFiles(zipFileList, count):
129     for zipFolder in zipFileList:
130         with zipfile.ZipFile(Path + "/" + zipFolder.strip(),"r") as zip_ref:
131             zip_ref.extractall(Path)
132         folder = zipFolder.rsplit(".")[0]
133         processFiles(folder, count)
134
135 def processFiles(folder, count):
136     conn = httplib.HTTPConnection("localhost",8181)
137     for file in os.listdir(Path + "/" + folder):
138         if os.path.isfile(Path + "/" + folder + "/" + file.strip()):
139             if ".key" in file:
140                 clientKey = readFile(folder, file.strip())
141             elif "trustedCertificate" in file:
142                 certList = readTrustedCertificate(folder, file.strip())
143             elif ".crt" in file:
144                 clientCrt = readFile(folder, file.strip())
145         else:
146             print "Could not find file %s" % file.strip()
147     shutil.rmtree(Path + "/" + folder)
148     json_keystore_key = makeKeystoreKey(clientKey, count)
149     json_private_key = makePrivateKey(clientKey, clientCrt, certList, count)
150     json_trusted_cert = makeTrustedCertificate(certList, count)
151
152     makeRestconfPost(conn, json_keystore_key, postKeystore)
153     makeRestconfPost(conn, json_private_key, postPrivateKey)
154     makeRestconfPost(conn, json_trusted_cert, postTrustedCertificate)
155
156 def makeHealthcheckCall(headers, timePassed):
157     connected = False
158     # WAIT 10 minutes maximum and test every 30 seconds if HealthCheck API is returning 200
159     while timePassed < TIMEOUT:
160         try:
161             conn = httplib.HTTPConnection("localhost",8181)
162             req = conn.request("POST", "/restconf/operations/SLI-API:healthcheck",headers=headers)
163             res = conn.getresponse()
164             res.read()
165             if res.status == 200:
166                 print ("Healthcheck Passed in %d seconds." %timePassed)
167                 connected = True
168                 break
169             else:
170                 print ("Sleep: %d seconds before testing if Healthcheck worked. Total wait time up now is: %d seconds. Timeout is: %d seconds" %(INTERVAL, timePassed, TIMEOUT))
171         except:
172             print ("Cannot execute REST call. Sleep: %d seconds before testing if Healthcheck worked. Total wait time up now is: %d seconds. Timeout is: %d seconds" %(INTERVAL, timePassed, TIMEOUT))
173         timePassed = timeIncrement(timePassed)
174
175     if timePassed > TIMEOUT:
176         print ("TIME OUT: Healthcheck not passed in  %d seconds... Could cause problems for testing activities..." %TIMEOUT)
177     return connected
178
179
180 def timeIncrement(timePassed):
181     time.sleep(INTERVAL)
182     timePassed = timePassed + INTERVAL
183     return timePassed
184
185 def readCertProperties():
186     connected = makeHealthcheckCall(headers, timePassed)
187
188     if connected:
189         count = 0
190         if os.path.isfile(Path + "/certs.properties"):
191             with open(Path + "/certs.properties", "r") as f:
192                 for line in f:
193                     if not "*****" in line:
194                         zipFileList.append(line)
195                     else:
196                         extractZipFiles(zipFileList, count)
197                         count += 1
198                         del zipFileList[:]
199         else:
200             print "Error: File not found in path entered"
201
202 readCertProperties()