3 # ============LICENSE_START=======================================================
5 # ================================================================================
6 # Copyright (C) 2018 AT&T Intellectual Property. All rights
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
13 # http://www.apache.org/licenses/LICENSE-2.0
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.
29 import SimpleHTTPServer
37 parser = argparse.ArgumentParser(description="3rd party Cache & Replay")
38 parser.add_argument("--username", "-u", type=str, help="Set the username for contacting 3rd party - only used for GET")
39 parser.add_argument("--password", "-p", type=str, help="Set the password for contacting 3rd party - only used for GET")
40 parser.add_argument("--root", "-r", default=tempfile.mkdtemp, type=str, help="Root folder for the proxy cache")
41 parser.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")
42 parser.add_argument("--port", "-P", type=int, default="8081", help="Port on which the proxy should listen to")
43 parser.add_argument("--verbose", "-v", type=bool, help="Print more information in case of error")
44 options = parser.parse_args()
49 AUTH = (options.username, options.password)
50 HEADERS = {'X-ECOMP-InstanceID':'CLAMP'}
51 CACHE_ROOT = options.root
53 def signal_handler(signal_sent, frame):
55 if signal_sent == signal.SIGINT:
56 print('Got Ctrl-C (SIGINT)')
61 class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
63 def print_headers(self):
64 for header,value in self.headers.items():
65 print("header: %s : %s" % (header, value))
67 def check_credentials(self):
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',):
77 self.send_header(key, value)
79 with open(content_file,'rb') as f:
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
91 print("\n\n\nGot a GET request for %s " % self.path)
94 self.check_credentials()
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('<','<').replace('>','>').replace('?','?').replace('*','*').replace('\\','*').replace(':',':').replace('|','|')
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,)
103 _file_available = os.path.exists(cached_file_content)
105 if not _file_available:
106 print("Request for data currently not present in cache: %s" % (cached_file,))
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
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)
124 self.send_response(404)
125 return "404 Not found"
127 url = '%s%s' % (HOST, self.path)
128 response = requests.get(url, auth=AUTH, headers=HEADERS, stream=True)
130 if response.status_code == 200:
131 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
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
140 print("Request for data currently present in cache: %s" % (cached_file,))
142 self._send_content(cached_file_header, cached_file_content)
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)
148 print "NOT in DCAE case deleting folder created " + cached_file
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)
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('<','<').replace('>','>').replace('?','?').replace('*','*').replace('\\','*').replace(':',':').replace('|','|')
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,)
164 _file_available = os.path.exists(cached_file_content)
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
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)
180 self.send_response(404)
181 return "404 Not found"
183 print("Request for data currently not present in cache: %s" % (cached_file,))
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)
189 if response.status_code == 200:
190 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
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
199 print("Request for data present in cache: %s" % (cached_file,))
201 self._send_content(cached_file_header, cached_file_content)
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)
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('<','<').replace('>','>').replace('?','?').replace('*','*').replace('\\','*').replace(':',':').replace('|','|')
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,)
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"
223 if not _file_available:
224 print("Request for data currently not present in cache: %s" % (cached_file,))
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)
230 if response.status_code == 200:
231 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
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
240 print("Request for data present in cache: %s" % (cached_file,))
242 self._send_content(cached_file_header, cached_file_content)
246 # Main code that start the HTTP server
247 httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
248 httpd.allow_reuse_address = True
249 print "Listening on port "+ str(PORT) + " and caching in " + CACHE_ROOT + "(Press Ctrl+C to stop HTTPD Caching script)"
250 signal.signal(signal.SIGINT, signal_handler)
251 httpd.serve_forever()