blob: 7d5f1b8d80fa7a60568a2461cf708ef959153ada [file] [log] [blame]
Chengyu Fanb07788a2014-03-31 12:15:36 -06001#!/usr/bin/env python2.7
Alexander Afanasyev9bcbc7c2014-04-06 19:37:37 -07002# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
3
4"""
Junxiao Shie2733332016-11-24 14:11:40 +00005Copyright (c) 2014-2016, Regents of the University of California,
6 Arizona Board of Regents,
7 Colorado State University,
8 University Pierre & Marie Curie, Sorbonne University,
9 Washington University in St. Louis,
10 Beijing Institute of Technology,
11 The University of Memphis.
Alexander Afanasyev9bcbc7c2014-04-06 19:37:37 -070012
13This file is part of NFD (Named Data Networking Forwarding Daemon).
14See AUTHORS.md for complete list of NFD authors and contributors.
15
16NFD is free software: you can redistribute it and/or modify it under the terms
17of the GNU General Public License as published by the Free Software Foundation,
18either version 3 of the License, or (at your option) any later version.
19
20NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
21without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
22PURPOSE. See the GNU General Public License for more details.
23
24You should have received a copy of the GNU General Public License along with
25NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
26"""
Chengyu Fanb07788a2014-03-31 12:15:36 -060027
Chengyu Fan45d1a762014-07-08 14:21:32 -060028from BaseHTTPServer import HTTPServer
29from SimpleHTTPServer import SimpleHTTPRequestHandler
Chengyu Fanb07788a2014-03-31 12:15:36 -060030from SocketServer import ThreadingMixIn
31import sys
Chengyu Fan30aa2072014-07-20 13:52:32 -060032import subprocess
Chengyu Fanb07788a2014-03-31 12:15:36 -060033import urlparse
34import logging
Chengyu Fanb07788a2014-03-31 12:15:36 -060035import argparse
Chengyu Fane25b0f02014-04-05 21:42:40 -060036import socket
Chengyu Fan45d1a762014-07-08 14:21:32 -060037import os
Chengyu Fanb07788a2014-03-31 12:15:36 -060038
39
Chengyu Fan45d1a762014-07-08 14:21:32 -060040class StatusHandler(SimpleHTTPRequestHandler):
Chengyu Fanb07788a2014-03-31 12:15:36 -060041 """ The handler class to handle requests."""
42 def do_GET(self):
43 # get the url info to decide how to respond
44 parsedPath = urlparse.urlparse(self.path)
Chengyu Fan45d1a762014-07-08 14:21:32 -060045 if parsedPath.path == "/":
46 # get current nfd status, and use it as result message
Junxiao Shi9137e9e2016-12-15 21:31:50 +000047 (httpCode, contentType, body) = self.getNfdStatus()
48 self.send_response(httpCode)
49 self.send_header("Content-Type", contentType)
Chengyu Fan45d1a762014-07-08 14:21:32 -060050 self.end_headers()
Junxiao Shi9137e9e2016-12-15 21:31:50 +000051 self.wfile.write(body)
Chengyu Fan45d1a762014-07-08 14:21:32 -060052 elif parsedPath.path == "/robots.txt" and self.server.robots == True:
Chengyu Fanb07788a2014-03-31 12:15:36 -060053 self.send_response(200)
Junxiao Shi9137e9e2016-12-15 21:31:50 +000054 self.send_header("Content-Type", "text/plain")
Chengyu Fan45d1a762014-07-08 14:21:32 -060055 self.end_headers()
Chengyu Fanb07788a2014-03-31 12:15:36 -060056 else:
Chengyu Fan45d1a762014-07-08 14:21:32 -060057 SimpleHTTPRequestHandler.do_GET(self)
Chengyu Fanb07788a2014-03-31 12:15:36 -060058
Chengyu Fanb07788a2014-03-31 12:15:36 -060059 def log_message(self, format, *args):
60 if self.server.verbose:
Junxiao Shi9137e9e2016-12-15 21:31:50 +000061 logging.info("%s - %s\n" % (self.address_string(), format % args))
62
63 def makeErrorResponseHtml(self, text):
64 return '<!DOCTYPE html><title>NFD status</title><p>%s</p>' % text
Chengyu Fanb07788a2014-03-31 12:15:36 -060065
66 def getNfdStatus(self):
Junxiao Shie2733332016-11-24 14:11:40 +000067 """ Obtain XML-formatted NFD status report """
Junxiao Shi9137e9e2016-12-15 21:31:50 +000068 try:
69 sp = subprocess.Popen(['nfdc', 'status', 'report', 'xml'], stdout=subprocess.PIPE, close_fds=True)
70 output = sp.communicate()[0]
71 except OSError as e:
72 self.log_message('error invoking nfdc: %s', e)
73 html = self.makeErrorResponseHtml('Internal error')
74 return (500, "text/html; charset=UTF-8", html)
75
Alexander Afanasyevb4bac922014-11-03 13:56:01 -080076 if sp.returncode == 0:
Junxiao Shi9137e9e2016-12-15 21:31:50 +000077 # add stylesheet processing instruction after the XML document type declaration
78 pos = output.index('>') + 1
79 xml = output[:pos]\
80 + '<?xml-stylesheet type="text/xsl" href="nfd-status.xsl"?>'\
81 + output[pos:]
82 return (200, 'text/xml; charset=UTF-8', xml)
Chengyu Fanb07788a2014-03-31 12:15:36 -060083 else:
Junxiao Shi9137e9e2016-12-15 21:31:50 +000084 html = self.makeErrorResponseHtml('Cannot connect to NFD, Code = %d' % sp.returncode)
85 return (504, "text/html; charset=UTF-8", html)
Chengyu Fanb07788a2014-03-31 12:15:36 -060086
Chengyu Fane25b0f02014-04-05 21:42:40 -060087class ThreadHttpServer(ThreadingMixIn, HTTPServer):
88 """ Handle requests using threads """
Chengyu Fanb07788a2014-03-31 12:15:36 -060089 def __init__(self, server, handler, verbose=False, robots=False):
Chengyu Fane25b0f02014-04-05 21:42:40 -060090 serverAddr = server[0]
91 # socket.AF_UNSPEC is not supported, check whether it is v6 or v4
92 ipType = self.getIpType(serverAddr)
93 if ipType == socket.AF_INET6:
94 self.address_family = socket.AF_INET6
95 elif ipType == socket.AF_INET:
96 self.address_family == socket.AF_INET
97 else:
98 logging.error("The input IP address is neither IPv6 nor IPv4")
99 sys.exit(2)
100
Chengyu Fanb07788a2014-03-31 12:15:36 -0600101 try:
102 HTTPServer.__init__(self, server, handler)
103 except Exception as e:
104 logging.error(str(e))
105 sys.exit(2)
106 self.verbose = verbose
107 self.robots = robots
108
Chengyu Fane25b0f02014-04-05 21:42:40 -0600109 def getIpType(self, ipAddr):
110 """ Get ipAddr's address type """
111 # if ipAddr is an IPv6 addr, return AF_INET6
112 try:
113 socket.inet_pton(socket.AF_INET6, ipAddr)
114 return socket.AF_INET6
115 except socket.error:
116 pass
117 # if ipAddr is an IPv4 addr return AF_INET, if not, return None
118 try:
119 socket.inet_pton(socket.AF_INET, ipAddr)
120 return socket.AF_INET
121 except socket.error:
122 return None
123
Chengyu Fanb07788a2014-03-31 12:15:36 -0600124
125# main function to start
126def httpServer():
127 parser = argparse.ArgumentParser()
128 parser.add_argument("-p", type=int, metavar="port number",
129 help="Specify the HTTP server port number, default is 8080.",
130 dest="port", default=8080)
Chengyu Fane25b0f02014-04-05 21:42:40 -0600131 # if address is not specified, use 127.0.0.1
132 parser.add_argument("-a", default="127.0.0.1", metavar="IP address", dest="addr",
Chengyu Fanb07788a2014-03-31 12:15:36 -0600133 help="Specify the HTTP server IP address.")
134 parser.add_argument("-r", default=False, dest="robots", action="store_true",
135 help="Enable HTTP robots to crawl; disabled by default.")
Alexander Afanasyev8a093762014-07-16 18:43:09 -0700136 parser.add_argument("-f", default="@DATAROOTDIR@/ndn", metavar="Server Directory", dest="serverDir",
137 help="Specify the working directory of nfd-status-http-server, default is @DATAROOTDIR@/ndn.")
Chengyu Fanb07788a2014-03-31 12:15:36 -0600138 parser.add_argument("-v", default=False, dest="verbose", action="store_true",
139 help="Verbose mode.")
Alexander Afanasyevb47d5382014-05-05 14:35:03 -0700140 parser.add_argument("--version", default=False, dest="version", action="store_true",
141 help="Show version and exit")
Chengyu Fanb07788a2014-03-31 12:15:36 -0600142
143 args = vars(parser.parse_args())
Alexander Afanasyevb47d5382014-05-05 14:35:03 -0700144
145 if args['version']:
146 print "@VERSION@"
147 return
148
Chengyu Fanb07788a2014-03-31 12:15:36 -0600149 localPort = args["port"]
150 localAddr = args["addr"]
151 verbose = args["verbose"]
152 robots = args["robots"]
Chengyu Fan45d1a762014-07-08 14:21:32 -0600153 serverDirectory = args["serverDir"]
154
155 os.chdir(serverDirectory)
Chengyu Fanb07788a2014-03-31 12:15:36 -0600156
157 # setting log message format
158 logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s',
159 level=logging.INFO)
160
Chengyu Fane25b0f02014-04-05 21:42:40 -0600161 # if port is invalid, exit
Chengyu Fanb07788a2014-03-31 12:15:36 -0600162 if localPort <= 0 or localPort > 65535:
163 logging.error("Specified port number is invalid")
164 sys.exit(2)
165
Chengyu Fane25b0f02014-04-05 21:42:40 -0600166 httpd = ThreadHttpServer((localAddr, localPort), StatusHandler,
Chengyu Fanb07788a2014-03-31 12:15:36 -0600167 verbose, robots)
Chengyu Fane25b0f02014-04-05 21:42:40 -0600168 httpServerAddr = ""
169 if httpd.address_family == socket.AF_INET6:
170 httpServerAddr = "http://[%s]:%s" % (httpd.server_address[0],
171 httpd.server_address[1])
172 else:
173 httpServerAddr = "http://%s:%s" % (httpd.server_address[0],
174 httpd.server_address[1])
Chengyu Fanb07788a2014-03-31 12:15:36 -0600175
Chengyu Fane25b0f02014-04-05 21:42:40 -0600176 logging.info("Server started - at %s" % httpServerAddr)
Chengyu Fanb07788a2014-03-31 12:15:36 -0600177
178 try:
179 httpd.serve_forever()
180 except KeyboardInterrupt:
181 pass
182
Chengyu Fanb07788a2014-03-31 12:15:36 -0600183 httpd.server_close()
184
Chengyu Fane25b0f02014-04-05 21:42:40 -0600185 logging.info("Server stopped")
Chengyu Fanb07788a2014-03-31 12:15:36 -0600186
187
188if __name__ == '__main__':
189 httpServer()