47e28c0bef0ac13d3786cafd9d44c72127aeb948
[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 username = "admin"
33 password = "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U"
34
35 TIME_OUT=1000
36 INTERVAL=30
37 TIME=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     caPem = ""
59     serverCrt = ""
60     startCa = False
61     startCrt = False
62     key = open(Path + "/" + folder + "/" + file, "r")
63     lines = key.readlines()
64     for line in lines:
65         if not "BEGIN CERTIFICATE CA.pem" in line and not "END CERTIFICATE CA.pem" in line and startCa:
66             caPem += line
67         elif "BEGIN CERTIFICATE CA.pem" in line:
68             startCa = True
69         elif "END CERTIFICATE CA.pem" in line:
70             startCa = False
71
72         if not "BEGIN CERTIFICATE Server.crt" in line and not "END CERTIFICATE Server.crt" in line and startCrt:
73             serverCrt += line
74         elif "BEGIN CERTIFICATE Server.crt" in line:
75             startCrt = True
76         elif "END CERTIFICATE Server.crt" in line:
77             startCrt = False
78     return caPem, serverCrt
79
80 def makeKeystoreKey(clientKey, count):
81     odl_private_key="ODL_private_key_%d" %count
82
83     json_keystore_key='{{\"input\": {{ \"key-credential\": {{\"key-id\": \"{odl_private_key}\", \"private-key\" : ' \
84                       '\"{clientKey}\",\"passphrase\" : \"\"}}}}}}'.format(
85         odl_private_key=odl_private_key,
86         clientKey=clientKey)
87
88     return json_keystore_key
89
90
91
92 def makePrivateKey(clientKey, clientCrt, caPem, count):
93     odl_private_key="ODL_private_key_%d" %count
94
95     json_private_key='{{\"input\": {{ \"private-key\":{{\"name\": \"{odl_private_key}\", \"data\" : ' \
96                      '\"{clientKey}\",\"certificate-chain\":[\"{clientCrt}\",\"{caPem}\"]}}}}}}'.format(
97         odl_private_key=odl_private_key,
98         clientKey=clientKey,
99         clientCrt=clientCrt,
100         caPem=caPem)
101
102     return json_private_key
103
104 def makeTrustedCertificate(serverCrt, caPem, count):
105     trusted_cert_name = "xNF_Server_certificate_%d" %count
106     trusted_name = "xNF_CA_certificate_%d" %count
107
108     json_trusted_cert='{{\"input\": {{ \"trusted-certificate\": [{{\"name\":\"{trusted_cert_name}\",\"certificate\" : ' \
109                       '\"{serverCrt}\"}},{{\"name\": \"{trusted_name}\",\"certificate\":\"{caPem}\"}}]}}}}'.format(
110         trusted_cert_name=trusted_cert_name,
111         serverCrt=serverCrt,
112         trusted_name=trusted_name,
113         caPem=caPem)
114
115     return json_trusted_cert
116
117
118 def makeRestconfPost(conn, json_file, apiCall):
119     req = conn.request("POST", apiCall, json_file, headers=headers)
120     res = conn.getresponse()
121     res.read()
122     if res.status != 200:
123         print "Error here, response back wasnt 200: Response was : %d , %s" % (res.status, res.reason)
124     else:
125         print res.status, res.reason
126
127 def extractZipFiles(zipFileList, count):
128     for zipFolder in zipFileList:
129         with zipfile.ZipFile(Path + "/" + zipFolder.strip(),"r") as zip_ref:
130             zip_ref.extractall(Path)
131         folder = zipFolder.rsplit(".")[0]
132         processFiles(folder, count)
133
134 def processFiles(folder, count):
135     conn = httplib.HTTPConnection("localhost",8181)
136     for file in os.listdir(Path + "/" + folder):
137         if os.path.isfile(Path + "/" + folder + "/" + file.strip()):
138             if ".key" in file:
139                 clientKey = readFile(folder, file.strip())
140             elif "trustedCertificate" in file:
141                 caPem, serverCrt = readTrustedCertificate(folder, file.strip())
142             elif ".crt" in file:
143                 clientCrt = readFile(folder, file.strip())
144         else:
145             print "Could not find file %s" % file.strip()
146     shutil.rmtree(Path + "/" + folder)
147     json_keystore_key = makeKeystoreKey(clientKey, count)
148     json_private_key = makePrivateKey(clientKey, clientCrt, caPem, count)
149     json_trusted_cert = makeTrustedCertificate(serverCrt, caPem, count)
150
151     makeRestconfPost(conn, json_keystore_key, postKeystore)
152     makeRestconfPost(conn, json_private_key, postPrivateKey)
153     makeRestconfPost(conn, json_trusted_cert, postTrustedCertificate)
154
155 def makeHealthcheckCall(headers):
156     conn = httplib.HTTPConnection("localhost",8181)
157     req = conn.request("POST", "/restconf/operations/SLI-API:healthcheck",headers=headers)
158     res = conn.getresponse()
159     res.read()
160     if res.status == 200:
161         print ("Healthcheck Passed in %d seconds." %TIME)
162     else:
163         print ("Sleep: %d seconds before testing if Healtcheck worked. Total wait time up now is: %d seconds. Timeout is: %d seconds" %(INTERVAL, TIME, TIME_OUT))
164     return res.status
165
166
167 def timeIncrement(TIME):
168     time.sleep(INTERVAL)
169     TIME = TIME + INTERVAL
170     return TIME
171
172 def healthcheck(TIME):
173     # WAIT 10 minutes maximum and test every 30 seconds if HealthCheck API is returning 200
174     while TIME < TIME_OUT:
175         try:
176             status = makeHealthcheckCall(headers)
177             if status == 200:
178                 connected = True
179                 break
180         except:
181             print ("Sleep: %d seconds before testing if Healthcheck worked. Total wait time up now is: %d seconds. Timeout is: %d seconds" %(INTERVAL, TIME, TIME_OUT))
182
183         TIME = timeIncrement(TIME)
184
185     if TIME > TIME_OUT:
186         print ("TIME OUT: Healthcheck not passed in  %d seconds... Could cause problems for testing activities..." %TIME_OUT)
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     else:
202         print "This was a problem here, Healthcheck never passed, please check is your instance up and running."
203
204
205 healthcheck(TIME)