blob: 72ea4958703bf658c2c7ecbb26fc6bf682feee07 [file] [log] [blame]
ehautot153c8292018-03-15 17:49:50 +01001#!/usr/bin/env python2
2###
3# ============LICENSE_START=======================================================
4# ONAP CLAMP
5# ================================================================================
6# Copyright (C) 2018 AT&T Intellectual Property. All rights
7# reserved.
8# ================================================================================
9# Licensed under the Apache License, Version 2.0 (the "License");
10# you may not use this file except in compliance with the License.
11# You may obtain a copy of the License at
12#
13# http://www.apache.org/licenses/LICENSE-2.0
14#
15# Unless required by applicable law or agreed to in writing, software
16# distributed under the License is distributed on an "AS IS" BASIS,
17# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18# See the License for the specific language governing permissions and
19# limitations under the License.
20# ============LICENSE_END============================================
21# ===================================================================
22# ECOMP is a trademark and service mark of AT&T Intellectual Property.
23###
24
25import json
26import requests
27import os
28import sys
29import SimpleHTTPServer
30import SocketServer
31import argparse
32import tempfile
33import signal
34import uuid
35import shutil
36
37parser = argparse.ArgumentParser(description="3rd party Cache & Replay")
38parser.add_argument("--username", "-u", type=str, help="Set the username for contacting 3rd party - only used for GET")
39parser.add_argument("--password", "-p", type=str, help="Set the password for contacting 3rd party - only used for GET")
40parser.add_argument("--root", "-r", default=tempfile.mkdtemp, type=str, help="Root folder for the proxy cache")
41parser.add_argument("--proxy" , type=str, help="Url of the Act as a proxy. If not set, this script only uses the cache and will return a 404 if files aren't found")
42parser.add_argument("--port", "-P", type=int, default="8081", help="Port on which the proxy should listen to")
43parser.add_argument("--verbose", "-v", type=bool, help="Print more information in case of error")
44options = parser.parse_args()
45
46
47PORT = options.port
48HOST = options.proxy
49AUTH = (options.username, options.password)
50HEADERS = {'X-ECOMP-InstanceID':'CLAMP'}
51CACHE_ROOT = options.root
52
53def signal_handler(signal_sent, frame):
54 global httpd
55 if signal_sent == signal.SIGINT:
56 print('Got Ctrl-C (SIGINT)')
57 httpd.socket.close()
58 httpd.shutdown()
59 httpd.server_close()
60
61class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
62
63 def print_headers(self):
64 for header,value in self.headers.items():
65 print("header: %s : %s" % (header, value))
66
67 def check_credentials(self):
68 pass
69
70 def _send_content(self, header_file, content_file):
71 self.send_response(200)
72 with open(header_file, 'rb') as f:
73 headers = json.load(f)
74 for key,value in headers.items():
75 if key in ('Transfer-Encoding',):
76 continue
77 self.send_header(key, value)
78 self.end_headers()
79 with open(content_file,'rb') as f:
80 fc = f.read()
81 self.wfile.write(fc)
82
83 def _write_cache(self,cached_file, header_file, content_file, response):
84 os.makedirs(cached_file, True)
85 with open(content_file, 'w') as f:
86 f.write(response.raw.read())
87 with open(header_file, 'w') as f:
88 json.dump(dict(response.raw.headers), f)
89 # Entry point of the code
90 def do_GET(self):
91 print("\n\n\nGot a GET request for %s " % self.path)
92
93 self.print_headers()
94 self.check_credentials()
95
96 cached_file = '%s/%s' % (CACHE_ROOT, self.path,)
97 print("Cached file name before escaping : %s" % cached_file)
98 cached_file = cached_file.replace('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
99 print("Cached file name after escaping (used for cache storage) : %s" % cached_file)
100 cached_file_content = "%s/.file" % (cached_file,)
101 cached_file_header = "%s/.header" % (cached_file,)
102
103 _file_available = os.path.exists(cached_file_content)
104
105 if not _file_available:
106 print("Request for data currently not present in cache: %s" % (cached_file,))
107
108 if self.path.startswith("/dcae-service-types?asdcResourceId="):
109 print "self.path start with /dcae-service-types?asdcResourceId=, generating response json..."
110 uuidGenerated = str(uuid.uuid4())
111 typeId = "typeId-" + uuidGenerated
112 typeName = "typeName-" + uuidGenerated
113 print "typeId generated: " + typeName + " and typeName: "+ typeId
114 jsonGenerated = "{\"totalCount\":1, \"items\":[{\"typeId\":\"" + typeId + "\", \"typeName\":\"" + typeName +"\"}]}"
115 print "jsonGenerated: " + jsonGenerated
116
117 os.makedirs(cached_file, True)
118 with open(cached_file_header, 'w') as f:
119 f.write("{\"Content-Length\": \"144\", \"Content-Type\": \"application/json\"}")
120 with open(cached_file_content, 'w') as f:
121 f.write(jsonGenerated)
122 else:
123 if not HOST:
124 self.send_response(404)
125 return "404 Not found"
126
127 url = '%s%s' % (HOST, self.path)
128 response = requests.get(url, auth=AUTH, headers=HEADERS, stream=True)
129
130 if response.status_code == 200:
131 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
132 else:
133 print('Error when requesting file :')
134 print('Requested url : %s' % (url,))
135 print('Status code : %s' % (response.status_code,))
136 print('Content : %s' % (response.content,))
137 self.send_response(response.status_code)
138 return response.content
139 else:
140 print("Request for data currently present in cache: %s" % (cached_file,))
141
142 self._send_content(cached_file_header, cached_file_content)
143
144 if self.path.startswith("/dcae-service-types?asdcResourceId="):
145 print "DCAE case deleting folder created " + cached_file
146 shutil.rmtree(cached_file, ignore_errors=False, onerror=None)
147 else:
148 print "NOT in DCAE case deleting folder created " + cached_file
149
150 def do_POST(self):
151 print("\n\n\nGot a POST for %s" % self.path)
152 self.check_credentials()
153 self.data_string = self.rfile.read(int(self.headers['Content-Length']))
154 print("data-string:\n %s" % self.data_string)
155 print("self.headers:\n %s" % self.headers)
156
157 cached_file = '%s/%s' % (CACHE_ROOT, self.path,)
158 print("Cached file name before escaping : %s" % cached_file)
159 cached_file = cached_file.replace('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
160 print("Cached file name after escaping (used for cache storage) : %s" % cached_file)
161 cached_file_content = "%s/.file" % (cached_file,)
162 cached_file_header = "%s/.header" % (cached_file,)
163
164 _file_available = os.path.exists(cached_file_content)
165
166 if not _file_available:
167 if self.path.startswith("/sdc/v1/catalog/services/"):
168 print "self.path start with /sdc/v1/catalog/services/, generating response json..."
169 jsondata = json.loads(self.data_string)
170 jsonGenerated = "{\"artifactName\":\"" + jsondata['artifactName'] + "\",\"artifactType\":\"" + jsondata['artifactType'] + "\",\"artifactURL\":\"" + self.path + "\",\"artifactDescription\":\"" + jsondata['description'] + "\",\"artifactChecksum\":\"ZjJlMjVmMWE2M2M1OTM2MDZlODlmNTVmZmYzNjViYzM=\",\"artifactUUID\":\"" + str(uuid.uuid4()) + "\",\"artifactVersion\":\"1\"}"
171 print "jsonGenerated: " + jsonGenerated
172
173 os.makedirs(cached_file, True)
174 with open(cached_file_header, 'w') as f:
175 f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}")
176 with open(cached_file_content, 'w') as f:
177 f.write(jsonGenerated)
178 else:
179 if not HOST:
180 self.send_response(404)
181 return "404 Not found"
182
183 print("Request for data currently not present in cache: %s" % (cached_file,))
184
185 url = '%s%s' % (HOST, self.path)
186 print("url: %s" % (url,))
187 response = requests.post(url, data=self.data_string, headers=self.headers, stream=True)
188
189 if response.status_code == 200:
190 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
191 else:
192 print('Error when requesting file :')
193 print('Requested url : %s' % (url,))
194 print('Status code : %s' % (response.status_code,))
195 print('Content : %s' % (response.content,))
196 self.send_response(response.status_code)
197 return response.content
198 else:
199 print("Request for data present in cache: %s" % (cached_file,))
200
201 self._send_content(cached_file_header, cached_file_content)
202
203 def do_PUT(self):
204 print("\n\n\nGot a PUT for %s " % self.path)
205 self.check_credentials()
206 self.data_string = self.rfile.read(int(self.headers['Content-Length']))
207 print("data-string:\n %s" % self.data_string)
208 print("self.headers:\n %s" % self.headers)
209
210 cached_file = '%s/%s' % (CACHE_ROOT, self.path,)
211 print("Cached file name before escaping : %s" % cached_file)
212 cached_file = cached_file.replace('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
213 print("Cached file name after escaping (used for cache storage) : %s" % cached_file)
214 cached_file_content = "%s/.file" % (cached_file,)
215 cached_file_header = "%s/.header" % (cached_file,)
216
217 _file_available = os.path.exists(cached_file_content)
218 if not _file_available and not HOST:
219 print("No file corresponding in cache and no HOST specified: %s" % HOST)
220 self.send_response(404)
221 return "404 Not found"
222
223 if not _file_available:
224 print("Request for data currently not present in cache: %s" % (cached_file,))
225
226 url = '%s%s' % (HOST, self.path)
227 print("url: %s" % (url,))
228 response = requests.put(url, data=self.data_string, headers=self.headers, stream=True)
229
230 if response.status_code == 200:
231 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
232 else:
233 print('Error when requesting file :')
234 print('Requested url : %s' % (url,))
235 print('Status code : %s' % (response.status_code,))
236 print('Content : %s' % (response.content,))
237 self.send_response(response.status_code)
238 return response.content
239 else:
240 print("Request for data present in cache: %s" % (cached_file,))
241
242 self._send_content(cached_file_header, cached_file_content)
243
244
245
246# Main code that start the HTTP server
247httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
248httpd.allow_reuse_address = True
249print "Listening on port "+ str(PORT) + " and caching in " + CACHE_ROOT + "(Press Ctrl+C to stop HTTPD Caching script)"
250signal.signal(signal.SIGINT, signal_handler)
251httpd.serve_forever()