Merge "false positive license issue on nexus IQ + unused"
[clamp.git] / src / test / resources / http-cache / sdc_proxy.py
1 #!/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
25 import json
26 import requests
27 import os
28 import sys
29 import SimpleHTTPServer
30 import SocketServer
31 import argparse
32 import tempfile
33 import signal
34
35 parser = argparse.ArgumentParser(description="SDC Cache & Replay")
36 parser.add_argument("--username", "-u", type=str, help="Set the username for contacting SDC")
37 parser.add_argument("--password", "-p", type=str, help="Set the password for contacting SDC")
38 parser.add_argument("--root",     "-r", default=tempfile.mkdtemp, type=str, help="Root folder for the proxy cache")
39 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")
40 parser.add_argument("--port",     "-P", type=int, default="8081", help="Port on which the proxy should listen to")
41 parser.add_argument("--verbose",  "-v", type=bool, help="Print more information in case of error")
42 options = parser.parse_args()
43
44
45 PORT = options.port
46 SDC_HOST = options.proxy
47 SDC_AUTH = (options.username, options.password)
48 SDC_HEADERS = {'X-ECOMP-InstanceID':'CLAMP'}
49 CACHE_ROOT = options.root
50
51 def signal_handler(signal_sent, frame):
52     global httpd
53     if signal_sent == signal.SIGINT:
54         print('Got Ctrl-C (SIGINT)')
55         httpd.socket.close()
56         httpd.shutdown()
57         httpd.server_close()
58
59 class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
60
61     def print_headers(self):
62         for header,value in self.headers.items():
63             print("%s : %s" % (header, value))
64
65     def check_credentials(self):
66         pass
67
68     def _send_content(self, header_file, content_file):
69         self.send_response(200)
70         with open(header_file, 'rb') as f:
71             headers = json.load(f)
72             for key,value in headers.items():
73                 if key in ('Transfer-Encoding',):
74                     continue
75                 self.send_header(key, value)
76             self.end_headers()
77         with open(content_file,'rb') as f:
78             fc = f.read()
79             self.wfile.write(fc)
80
81     def _write_cache(self,cached_file, header_file, content_file, response):
82         os.makedirs(cached_file, True)
83         with open(content_file, 'w') as f:
84             f.write(response.raw.read())
85         with open(header_file, 'w') as f:
86             json.dump(dict(response.raw.headers), f)
87     # Entry point of the code
88     def do_GET(self):
89
90         self.print_headers()
91         self.check_credentials()
92
93         cached_file = '%s/%s' % (CACHE_ROOT, self.path,)
94         print("Cached file name before escaping : %s" % cached_file)
95         cached_file = cached_file.replace('<','&#60;').replace('>','&#62;').replace('?','&#63;').replace('*','&#42;').replace('\\','&#42;').replace(':','&#58;').replace('|','&#124;')
96         print("Cached file name after escaping (used for cache storage) : %s" % cached_file)
97         cached_file_content = "%s/.file" % (cached_file,)
98         cached_file_header = "%s/.header" % (cached_file,)
99
100         _file_available = os.path.exists(cached_file_content)
101         if not _file_available and not SDC_HOST:
102             self.send_response(404)
103             return "404 Not found"
104
105         if not _file_available:
106             print("SDC Request for data currently not present in cache: %s" % (cached_file,))
107             url = '%s%s' % (SDC_HOST, self.path)
108             response = requests.get(url, auth=SDC_AUTH, headers=SDC_HEADERS, stream=True)
109
110             if response.status_code == 200:
111                 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
112             else:
113                 print('Error when requesting file :')
114                 print('Requested url : %s' % (url,))
115                 print('Status code : %s' % (response.status_code,))
116                 print('Content : %s' % (response.content,))
117                 self.send_response(response.status_code)
118                 return response.content
119
120         self._send_content(cached_file_header, cached_file_content)
121
122 # Main code that start the HTTP server
123 httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
124 httpd.allow_reuse_address = True
125 print "Listening on port "+ str(PORT) + " and caching in " + CACHE_ROOT + "(Press Ctrl+C to stop HTTPD Caching script)"
126 signal.signal(signal.SIGINT, signal_handler)
127 httpd.serve_forever()