blob: 301e7af9df7dd69ed7b6620dcf48a453b8805ee7 [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,)
94 cached_file_content = "%s/.file" % (cached_file,)
95 cached_file_header = "%s/.header" % (cached_file,)
96
97 _file_available = os.path.exists(cached_file_content)
98 if not _file_available and not SDC_HOST:
99 self.send_response(404)
100 return "404 Not found"
101
102 if not _file_available:
103 print("Request for not cached file : %s" % (cached_file,))
104 url = '%s%s' % (SDC_HOST, self.path)
105 response = requests.get(url, auth=SDC_AUTH, headers=SDC_HEADERS, stream=True)
106
107 if response.status_code == 200:
108 self._write_cache(cached_file, cached_file_header, cached_file_content, response)
109 else:
110 print('Error when requesting file :')
111 print('Requested url : %s' % (url,))
112 print('Status code : %s' % (response.status_code,))
113 print('Content : %s' % (response.content,))
114 self.send_response(response.status_code)
115 return response.content
116
117 self._send_content(cached_file_header, cached_file_content)
118
119# Main code that start the HTTP server
120httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
121httpd.allow_reuse_address = True
122print "Listening on port "+ str(PORT) + " and caching in " + CACHE_ROOT + "(Press Ctrl+C to stop HTTPD Caching script)"
123signal.signal(signal.SIGINT, signal_handler)
124httpd.serve_forever()