blob: 45dac4133fae99f6d7659c6e913beb9ce64636c8 [file] [log] [blame]
Determe, Sebastien (sd378r)9d6523c2018-02-14 14:39:29 +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
34
35parser = argparse.ArgumentParser(description="SDC Cache & Replay")
36parser.add_argument("--username", "-u", type=str, help="Set the username for contacting SDC")
37parser.add_argument("--password", "-p", type=str, help="Set the password for contacting SDC")
38parser.add_argument("--root", "-r", default=tempfile.mkdtemp, type=str, help="Root folder for the proxy cache")
39parser.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")
40parser.add_argument("--port", "-P", type=int, default="8081", help="Port on which the proxy should listen to")
41parser.add_argument("--verbose", "-v", type=bool, help="Print more information in case of error")
42options = parser.parse_args()
43
44
45PORT = options.port
46SDC_HOST = options.proxy
47SDC_AUTH = (options.username, options.password)
48SDC_HEADERS = {'X-ECOMP-InstanceID':'CLAMP'}
49CACHE_ROOT = options.root
50
51def 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
59class 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,)
Determe, Sebastien (sd378r)3ba34032018-02-15 11:20:25 +010094 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)
Determe, Sebastien (sd378r)9d6523c2018-02-14 14:39:29 +010097 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:
Determe, Sebastien (sd378r)3ba34032018-02-15 11:20:25 +0100106 print("SDC Request for data currently not present in cache: %s" % (cached_file,))
Determe, Sebastien (sd378r)9d6523c2018-02-14 14:39:29 +0100107 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
123httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
124httpd.allow_reuse_address = True
125print "Listening on port "+ str(PORT) + " and caching in " + CACHE_ROOT + "(Press Ctrl+C to stop HTTPD Caching script)"
126signal.signal(signal.SIGINT, signal_handler)
127httpd.serve_forever()