def get_param_env(self): env = nutils.get_entries(self, self._MEMBER_ENV_RE, str) #Tasklet.MEMBER_ENV_RE env['PARAMETERS'] = '' # overwrite kludge if (self.INPUT_PARAMETERS): env.update(self.INPUT_PARAMETERS) if (self.PARAMETERS): env.update(self.PARAMETERS) # overrides INPUT_PARAMETERS if (self.TIMESTAMP): parse_timestamp2(self.TIMESTAMP, env) env['PRODUCT'] = self.PRODUCT_ID # temporary (rack-tile) return env
def run_http(product_server): """A convenience function for starting and stopping the HTTP server. """ NutHandler.directory = product_server.HTTP_ROOT # has no effect as such... http.server.SimpleHTTPRequestHandler.directory = product_server.HTTP_ROOT # has no effect... #http.server.SimpleHTTPRequestHandler. # server_class = http.server.HTTPServer # httpd = server_class((product_server.HTTP_NAME, int(product_server.HTTP_PORT)), NutHandler) httpd = http.server.HTTPServer((product_server.HTTP_NAME, int(product_server.HTTP_PORT)), NutHandler) #if (options.VERBOSE > 1): print('Starting server (port={0}, root={1})'.format(product_server.HTTP_PORT, NutHandler.directory)) nutils.print_dict(nutils.get_entries(httpd)) cache = Path(product_server.HTTP_ROOT, 'cache') if (not cache.exists()): print('Warning: cache dir does not exist: {0}'.format(cache)) # elif not writable: os.chdir(product_server.HTTP_ROOT) print('Starting: http://{0}:{1}/nutshell/'.format( httpd.server_name, httpd.server_port)) try: httpd.serve_forever() # httpd.handle_request() # single except KeyboardInterrupt: print() print( "Keyboard interrupt (CTRL-C)" ) #pass except SystemExit: print() print( "System Exit" ) except: print("Unexpected error:") # , sys.exc_info()[0]) finally: httpd.server_close()
def get_status(self): return nutils.get_entries(self)
def get_param_env(self): return nutils.get_entries(self, product.Info._MEMBER_ENV_RE, str)
def do_GET(s): """Main function. Receives the http request and sends a response. """ # Consider renaming NutShell "request" to "instructions" s.log = logging.getLogger("NutHandler" + str(++product_server.counter)) s.log.setLevel(product_server.logger.level) #++NutHandler.counter s.log.debug("started") # Declare request and directives as lists querydata = {'request': [], 'directives': []} # 'product': '', basepath,querydata = NutHandler.parse_url(s.path, querydata) # basepath.replace(HTTP_PATH_PREFIX, '') s.log.info(querydata) if (basepath == '/test'): s.log.info('Testing (info)!') s.log.warning('Testing (warn)!') NutHandler._send_status_html(s, HTTPStatus.OK, "Test", basepath) """ s.send_response(HTTPStatus.OK.value) s.end_headers() s.wfile.write("<html><body>Test</body></html>\n".encode()) s.log.warning("test {0}".format(basepath)) """ return nutshell_path = '' # Strip HTTP_PREFIX if (basepath.startswith(product_server.HTTP_PREFIX)): nutshell_path = basepath[len(product_server.HTTP_PREFIX):] else: s.send_response(HTTPStatus.OK.value) s.end_headers() html = '<html><body>Error: path {0} does not start with <a href="{1}">{1}</a></body></html>\n' html = html.format(nutshell_path, product_server.HTTP_PREFIX) s.wfile.write(html.encode()) s.log.warning("test {0}".format(nutshell_path)) return if (nutshell_path == '/NutShell'): # Imitate Tomcat Servlet (Nutlet) url = product_server.HTTP_PREFIX + "/menu.html"; # .format(system_path.name) NutHandler._redirect(s, url) return #NutHandler._include_html(main, 'template/form.html') #NutHandler._send_status_html(s, HTTPStatus.OK, "Test", nutshell_path) """ s.send_response(HTTPStatus.OK.value) s.end_headers() s.wfile.write("<html><body>Test</body></html>\n".encode()) s.log.warning("test {0}".format(nutshell_path)) """ # Directory and file requests are directed to default HTTP handler # NOTE: use plus, otherways collapses to root #system_path = nutshell.Path(s.directory + nutshell_path) system_path = Path(s.directory + nutshell_path) s.log.info("system_path: {0}".format(system_path)) if (system_path.exists()): # TODO: if empty product, allow generation # 503 Service Unavailable x Busy, come back later os.chdir(s.directory) # !! s.log.info("File found, forwarding to standard handler") # -> {0} ".format(system_path)) http.server.SimpleHTTPRequestHandler.do_GET(s) return # If the path # - starts with "/cache/" # - is a file, that has not been found (checked above) # - has a filename extension (system_path.suffix, like ".png") # - has no special parameters (like "?redirect=None") if (nutshell_path.find('/cache/') == 0) and system_path.suffix and (s.path.find('?') == -1): s.log.error("PRODUCT? {0}".format(system_path.suffix)) url = '/' + product_server.HTTP_PREFIX + "/nutshell/server/?request=MAKE&product={0}".format(system_path.name) NutHandler._redirect(s, url) return if (system_path.name == 'stop'): s.send_response(HTTPStatus.OK.value) s.end_headers() s.wfile.write(b"<html>Stopped server</html>") #httpd.server_close() s.log.info('Goodbye, world!') raise SystemExit #KeyboardInterrupt #s.log.warning('Suffix?') #s.log.warning(system_path.suffix) # TODO: fix - this does not recognize query param. /nutshell/NutShell?menu.html if (system_path.suffix == '.html'): #s.log.warn('Goodbye, HTML') html = NutHandler._get_html_file(system_path.name) s.send_response(HTTPStatus.OK.value) s.end_headers() s.wfile.write(ET.tostring(html)) return instructions = None directives = [] product_name = querydata.get('product', None) product_info = None if (product_name): product_info = product.Info(filename = product_name) instructions = querydata.get('request', ["MAKE"]) directives = querydata['directives'] else: instructions = querydata['request'] directives = querydata.get('directives', ["STATUS"]) s.log.info("Service-request: {0} ".format(instructions)) s.log.info("Product-name: {0} ".format(product_name)) s.log.info("Directives: {0} ".format(directives)) #product_info = nutproduct.ProductInfo() product_request = None if (product_info): product_info.set_product(filename = product_name) #parse_filename(product_name) s.log.info("Product info: {0} ".format(product_info)) # "MAIN" product_request = product_server.make_request(product_info, instructions, directives, s.log.getChild("Make_Request")) # print("Phase 3", instructions) # TODO: 'PATH' if ('MAKE' in instructions) and ('STATUS' not in directives): if (product_request.status == HTTPStatus.OK) and (product_request.path != ''): # Redirect # server_name mpeura10kl # server_port 8088 context = '{0}:{1}'.format(s.server.server_name, s.server.server_port) path = Path(context, product_server.HTTP_PREFIX, 'cache', str(product_request.path_relative)) url = str(path) + '?no_redirect' #url = '/' + product_server.HTTP_PREFIX + '/cache/' + str(product_request.path_relative) + '?no_redirect' #url = '/'+product_server.get_relative_path(product_info)+'?no_redirect' #print('CONSIDER', url) NutHandler._redirect(s, url) return else: s.log.error("MAKE failed for: {0}".format(product_info.get_filename())) #product_request.log else: product_request.status = HTTPStatus.OK #print("Nokemake", instructions) if product_request: s.send_response(product_request.status.value) s.end_headers() else: s.send_response(HTTPStatus.OK.value) s.end_headers() # Proceed to HTML page response html = NutHandler._get_html_template() #head = nutxml.get_head(html) body = nutxml.get_body(html) main = nutxml.get_by_id(body, 'main', 'span') NutHandler._include_html(main, 'template/form.html') # Consider single table for all # table = ET.Element('table') # append_table(table, data, attributes) if instructions: elem = nutxml.get_by_id(body, 'request') elem.set("value", ','.join(instructions)) if product_request: elem = nutxml.get_by_id(body, 'product') elem.set("value", product_request.product_info.get_filename()) if directives: elem = nutxml.get_by_id(body, 'directives') elem.set("value", ','.join(directives)) if product_request and (product_request.returncode != 0): responses = http.server.SimpleHTTPRequestHandler.responses msg, desc = responses.get(product_request.status, ('Unknown', 'Not a valid HTTP return code')) elem = nutxml.get_by_id(main, 'notif_head_elem', 'pre') elem.text = 'HTTP {0}: {1} -- {2}'.format(product_request.status.value, msg, desc) #elem = nutxml.get_by_id(body, 'error_info', 'pre') # No log stored, it's flushed: elem.text = str(product_request.log) # last status? main.append(nutxml.get_table(product_server.get_status(), {"title": "NutServer status"})) main.append(nutxml.get_table(nutils.get_entries(s), {"title": "HttpRequest"})) main.append(nutxml.get_table(nutils.get_entries(s.server), {"title": "HttpServer"})) #elem = nutxml.get_by_id(body, 'status_elem') #elem = nutxml.get_by_id(body, 'misc', 'pre') #elem.text = "Cwd: " + os.cwd + '\n' if (product_info): if ('INPUTS' in instructions): if (not product_request.inputs): # what if None? product_request.inputs = product_server.get_input_list(product_info).inputs #layout = '<tr><td>{0}</td><td><a href="/nutshell/server?request=INPUTS&product={1}">{1}</a></td></tr>\n' #elem = nutxml.get_by_id(body, 'inputs_elem') main.append(nutxml.get_table(product_request.inputs, {"title": "Product inputs", "border": "1"})) env = product_info.get_param_env() #elem = nutxml.get_by_id(body, 'product_elem') main.append(nutxml.get_table(env, {"title": "Product ({0}) parameters".format(product_info.PRODUCT_ID)})) #elem = nutxml.get_by_tag(body, 'pre', {'id': 'dump'}) elem = nutxml.get_by_id(main, 'dump_elem', 'pre') elem.text = str(dir(product_server)) + '\n' elem.text += str(dir(s)) + '\n' elem.text += "Load: " + str(os.getloadavg()) + '\n' elem.text += "Cwd (s.directory): " + s.directory + '\n' elem.text += "System side path (system_path): " + str(system_path) + '\n' elem.text += "HttpRequest: " + str(s) + '\n' elem = nutxml.get_by_id(body, 'version', 'span') elem.text = product_server.__class__.__name__ + ' : ' + product_server.__doc__ + " (Python version)" s.wfile.write(ET.tostring(html)) #s.wfile.write(minidom.parseString(ET.tostring(html)).toprettyxml(indent = " ")) #minidom.parseString(etree.toString(root)).toprettyxml(indent = " ") return