def main(prefix, cfgdir): """Server's main-function which parses the command line and starts up the server accordingly. """ global configdir global basedir true_port_val = 0 configdir = cfgdir basedir = prefix frontend = os.path.join(cfgdir, 'frontend') if not os.path.exists(os.path.join(frontend, 'dojo')): dojoz = zipfile.ZipFile(os.path.join(frontend, 'dojo.zip'), 'r') dojoz.extractall(path=frontend) dojoz.close() def_server_name = 'localhost' if hasattr(webbrowser, 'WindowsDefault') and isinstance( webbrowser.get(), webbrowser.WindowsDefault): # If on windows and using IE we do this to avoid IE9 bug (doesn't affect other versions of IE, there is no easy way to test def_server_name = socket.gethostname() cmdln_parser = optparse.OptionParser() cmdln_parser.add_option('-N', '--server_name', action='store', type='string', default=def_server_name, help='server name: [default: %default ]') cmdln_parser.add_option('-p', '--port', action='store', type='int', dest='port', default=8081, help='port for the webserver: [default: %default]') cmdln_parser.add_option( '-n', '--no-browser', action='store_true', help='do not open the server\'s start page in a browser.') cmdln_parser.add_option('-s', '--browser-start-page', action='store', type='string', dest='browser_start_page', default=mcc_config.MCC_BROWSER_START_PAGE, help='start page for browser: [default: %default]') cmdln_parser.add_option( '-d', '--debug-level', action='store', type='string', default='WARNING', help= 'Python logging module debug level (DEBUG, INFO, WARNING, ERROR or CRITICAL). [default: %default]' ) cmdln_parser.add_option( '-o', '--server-log-file', action='store', type='string', default=os.path.join(tempfile.gettempdir(), 'ndb_setup-' + str(os.getpid()) + '.log'), help= 'log requests to this file. The value - means log to stderr: [default: %default]' ) # option for level/logcfg file cmdln_parser.add_option( '-S', '--use-https', action='store_true', help='use https to secure communication with browser.') cmdln_parser.add_option( '-c', '--cert-file', action='store', type='string', default=os.path.join(cfgdir, 'cfg.pem'), help= 'file containing X509 certificate which identifies the server (possibly self-signed): [default: %default]' ) cmdln_parser.add_option( '-k', '--key-file', action='store', type='string', help= 'file containing private key when if not included in cert-file: [default: %default]' ) cmdln_parser.add_option( '-a', '--ca-certs-file', action='store', type='string', help= 'file containing list of client certificates allowed to connect to the server [default: %default (no client authentication)]' ) (options, arguments) = cmdln_parser.parse_args() dbglvl = getattr(logging, options.debug_level, logging.DEBUG) fmt = '%(asctime)s: %(levelname)s [%(funcName)s;%(filename)s:%(lineno)d]: %(message)s ' if options.server_log_file == '-': logging.basicConfig(level=dbglvl, format=fmt) else: logging.basicConfig(level=dbglvl, format=fmt, filename=options.server_log_file) for port_val in range(options.port, options.port + 20): if is_port_available(options.server_name, port_val): true_port_val = port_val break if true_port_val == 0: # no available port in range :-/ print("No available port in range[{},{}]!".format( options.port, options.port + 20)) sys.exit() options.port = true_port_val srvopts = { 'server': options.server_name, 'port': options.port, 'cdir': cfgdir, 'fdir': os.path.join(cfgdir, 'frontend') } if options.use_https: srvopts['ssl'] = True srvopts['certfile'] = options.cert_file srvopts['keyfile'] = options.key_file srvopts['ca_certs'] = options.ca_certs_file flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY try: file_handle = os.open('mcc.pid', flags) except OSError as e: if e.errno == errno.EEXIST: # Failed as the file already exists. file_handle = open('mcc.pid') # , os.O_RDONLY) print 'mcc.pid file found at ' + os.path.realpath( file_handle.name ) + '. Please remove before restarting process.' file_handle.close() sys.exit("Web server already running!") else: # Something unexpected went wrong so reraise the exception. raise else: # No exception, so the file must have been created successfully. with os.fdopen(file_handle, 'w') as file_obj: # Using `os.fdopen` converts the handle to an object that acts like a # regular Python file object, and the `with` context manager means the # file will be automatically closed when we're done with it. file_obj.write("MCC running.") file_obj.close() print 'Starting web server on port ' + repr(options.port) url_host = options.server_name if url_host == '': url_host = 'localhost' if options.use_https: url = 'https://{0}:{opt.port}/{opt.browser_start_page}'.format( url_host, opt=options) else: url = 'http://{0}:{opt.port}/{opt.browser_start_page}'.format( url_host, opt=options) httpsrv = None global deathkey deathkey = random.randint(100000, 1000000) print 'deathkey=' + str(deathkey) print 'Press CTRL+C to stop web server.' # dkf = open('deathkey.txt','w') # dkf.write(str(deathkey)) # dkf.close() # os.chmod('deathkey.txt', stat.S_IRUSR) try: httpsrv = ConfiguratorServer(srvopts) if not options.no_browser: try: webbrowser.open_new(url) except: logging.exception('Failed to control browser: ') print 'Could not control your browser. Try to opening ' + url + ' to launch the application.' else: print 'The application should now be running in your browser.\n(Alternatively you can navigate to ' + url + ' to start it)' else: print 'Navigate to ' + url + ' to launch the application.' httpsrv.serve_forever() except KeyboardInterrupt: print '^C received, shutting down web server' except: traceback.print_exc() finally: if httpsrv: httpsrv.socket.close() #os.remove('deathkey.txt') os.remove('mcc.pid')
def testPortAvailable(self): self.assertTrue(util.is_port_available(local_ipv4_ssh_addr(), 23))
def testPortNotAvailable(self): self.assertFalse(util.is_port_available(local_ipv4_ssh_addr(), 22))