Commits

desmaj  committed bad1766 Merge

merged TRAC-131 to default

  • Participants
  • Parent commits 4ba399d, 81e921f

Comments (0)

Files changed (21)

 ^include/
 ^lib/
 ^lib64
-daemon/.+egg
-daemon/orbited.egg-info/
+daemon/build
+daemon/dist
+daemon/orbited.egg-info

File daemon/.coverage

Binary file removed.

File daemon/orbited-debug.cfg

-[global]
-session.ping_interval = 10
-session.ping_timeout = 5
-user=orbited
-
-[listen]
-http://:8000
-http://:5000
-echo://:8001
-lineecho://:8002
-rude://:8003
-announce://:8004
-monitor://:8005
-stomp://:61613
-# uncomment to enable ssl on port 8043 using given .key and .crt files
-#https://:8043
-#
-#[ssl]
-#key=orbited.key
-#crt=orbited.crt
-
-[test]
-stompdispatcher.enabled = 1
-
-[static]
-
-[access]
-# freenode irc:
-* -> irc.freenode.net:6667
-# local stomp:
-* -> localhost:61613
-# local irc:
-* -> localhost:6667
-# local jabber/xmpp:
-* -> localhost:5222
-# local websocket:
-* -> localhost:81
-# local test port:
-* -> localhost:7777
-# built-in debugging servers
-* -> localhost:8001     # echo
-* -> localhost:8002     # lineecho
-* -> localhost:8003     # rude
-* -> localhost:8004     # announce
-* -> localhost:8005     # daemon monitoring feed
-
-[logging]
-debug=STDERR,debug.log
-info=STDERR,info.log
-access=STDERR,info.log
-warn=STDERR,error.log
-error=STDERR,error.log
-
-enabled.default=debug,info,access,warn,error
-
-[loggers]
-

File daemon/orbited.cfg

 session.ping_interval = 40
 session.ping_timeout = 30
 # once the sockets are open, orbited will drop its privileges to this user.
-user=orbited
+# user=orbited
 
 [listen]
 http://:8000
 handlers = console
 
 [logger_orbited]
-level = WARN
+level = DEBUG
 handlers = 
 qualname = orbited
 

File daemon/orbited/cometsession.py

         else:
             raise CannotListenError("Already listening...")
 
-    def stopListening():
+    def stopListening(self):
         self.logger.debug('stopListening')
         if self.wrapped_port:
             self.listening = False
         transportProtocol.parentTransport = transport
         protocol.makeConnection(transport)
         
-    def getHost():
+    def getHost(self):
         if self.wrapped_port:
             return self.wrapped_port.getHost()
         elif self.resource:
         return None
 
     def connectionLost(self):
-        self.logger.debug('connectionLost... already triggered?', self.lostTriggered)
+        self.logger.debug('connectionLost... already triggered? %r', self.lostTriggered)
         if not self.lostTriggered:
             self.logger.debug('do trigger');
             self.lostTriggered = True
         hostHeader = request.received_headers.get('host', '')
         self.connections[key] = TCPConnectionResource(self, key, request.client, request.host, hostHeader)
         self.listeningPort.connectionMade(self.connections[key])
-        self.logger.debug('created conn: ', repr(self.connections[key]))
+        self.logger.debug('created conn: %s', repr(self.connections[key]))
         request.setHeader('cache-control', 'no-cache, must-revalidate')
         return key
 

File daemon/orbited/proxy.py

         # NB: its cometsession.py:TCPConnectionResource that makes sure
         #     we receive whole frames here.
         self.logger.debug('dataReceived: data=%r' % data)
-        self.logger.debug('self.outgoingConn is', self.outgoingConn)
+        self.logger.debug('self.outgoingConn is %r', self.outgoingConn)
 
         if self.outgoingConn:
             # NB: outgoingConn is-a ProxyOutgoingProtocol
                 port = int(port)
                 self.completedHandshake = True
             except:
-                self.logger.error("failed to connect on handshake", tb=True)
+                self.logger.error("failed to connect on handshake")
                 self.transport.write("0" + str(ERRORS['InvalidHandshake']))
                 self.transport.loseConnection()
                 return
                 self.transport.write("0" + str(ERRORS['Unauthorized']))
                 self.transport.loseConnection()
                 return
-            self.logger.access('new connection from %s:%s to %s:%d' % (self.fromHost, self.fromPort, self.toHost, self.toPort))
+            self.logger.info('new connection from %s:%s to %s:%d' % (self.fromHost, self.fromPort, self.toHost, self.toPort))
             self.state = 'connecting'
             client = ClientCreator(reactor, ProxyOutgoingProtocol, self)
             client.connectTCP(host, port).addErrback(self.errorConnection) 
         if self.outgoingConn:
             self.outgoingConn.transport.loseConnection()
         if self.completedHandshake:
-            self.logger.access('connection closed from %s:%s to %s:%s'%(self.fromHost, self.fromPort, self.toHost, self.toPort))
+            self.logger.info('connection closed from %s:%s to %s:%s'%(self.fromHost, self.fromPort, self.toHost, self.toPort))
 
     def outgoingConnectionEstablished(self, outgoingConn):
         if self.state == 'closed':

File daemon/orbited/start.py

 from orbited import __version__ as version
 from orbited import config
 
-logger = logging.getLogger(__name__)
-
 def _import(name):
     module_import = name.rsplit('.', 1)[0]
     return reduce(getattr, name.split('.')[1:], __import__(module_import))
         config.setup(options=options)
 
     logging.config.fileConfig(options.config)
+    global logger
+    logger = logging.getLogger(__name__)
     
     # NB: we need to install the reactor before using twisted.
     reactor_name = config.map['[global]'].get('reactor')
     else:
         reactor.run()
 
+class URLParseResult(object):
+    """ An object that allows access to urlparse results by index or name.
+        
+        This provides compatibility with python < 2.5 since the record fields
+        were added then.
+        
+        The tuple structure is like:
+        (scheme, netloc, path, params, query, fragment)
+    """
+    parts = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')
+    
+    @staticmethod
+    def _make_field_getter(self, index):
+        return lambda self: self[index]
+    
+    def __init__(self, result_tuple):
+        self._tuple = result_tuple
+        for index, part in enumerate(self.parts):
+            setattr(self.__class__, part, 
+                    property(self._make_field_getter(self, index)))
+        
+    
+    def __getitem__(self, index):
+        return self._tuple[index]
+    
+    def _split_netloc(self):
+        if ':' in self.netloc:
+            host, port = self.netloc.split(':')
+            port = int(port)
+        else:
+            host = self.netloc
+            port = 80
+        return host, port
+    
+    @property
+    def hostname(self):
+        return self._split_netloc()[0]
+
+    @property
+    def port(self):
+        return self._split_netloc()[1]
+
+def _parse_url(url):
+    """ Parse `url' and return the result as a URLParseResult object.
+    """
+    result = urlparse.urlparse(url)
+    return URLParseResult(result)
+    
 def start_listening(site, config, logger):
     from twisted.internet import reactor
     from twisted.internet import protocol as protocol_module
         urlparse.uses_netloc.append(protocol)
 
     for addr in config['[listen]']:
+        logger.debug(addr)
         if addr.startswith("stomp"):
             stompConfig = ""
             if " " in addr:
                 addr, stompConfig = addr.split(" ",1)
-        url = urlparse.urlparse(addr)
+        url = _parse_url(addr)
+        logger.debug('hostname: %r', url.hostname)
+        logger.debug('port: %r', url.port)
         hostname = url.hostname or ''
         if url.scheme == 'stomp':
             logger.info('Listening stomp@%s' % url.port)

File daemon/orbited/test/coverage/.coverage

Binary file added.

File daemon/orbited/test/functional/__init__.py

+import os
+import re
+import signal
+import sys
+import time
+
+from orbited.test.resources.selenium import selenium
+
+class TestingResource(object):
+    
+    def __init__(self, name_pattern):
+        self.name_pattern = name_pattern
+        self._path = None
+    
+    def _get_resources_dir(self):
+        functional_test_dir = os.path.abspath(os.path.dirname(__file__))
+        orbited_test_dir = os.path.normpath(os.path.join(functional_test_dir,
+                                                          '..'))
+        resources_dir = os.path.join(orbited_test_dir, 'resources')
+        return resources_dir
+    
+    def _select_resource(self):
+        resources_dir = self._get_resources_dir()
+        resources = os.listdir(resources_dir)
+        candidates = [name for name in resources 
+                      if re.match(self.name_pattern, name)]
+        assert candidates, \
+            "could not find resource matching %s in %s; found:\n%s" % \
+            (self.name_pattern, resources_dir, '\n'.join(candidates))
+        return os.path.join(resources_dir, max(candidates))
+    
+    @property
+    def path(self):
+        if self._path is None:
+            self._path = self._select_resource()
+        return self._path
+
+class InProcessServer(object):
+    
+    def start(self):
+        command, args = self.command.split(' ', 1)
+        print "running command [%s] with args [%r]" % (command, args)
+        self.pid = os.spawnvp(os.P_NOWAIT, command, args)
+        time.sleep(2)
+    
+    def stop(self):
+        os.kill(self.pid, signal.SIGINT)
+
+class OrbitedServer(InProcessServer):
+    config_file = TestingResource(r'orbited-debug.cfg')
+    command = "orbited -c %s" % config_file.path
+
+class SeleniumRCServer(InProcessServer):
+    server_jar = TestingResource(r'selenium-server-standalone-\S+.jar')
+    command = "java -jar %s" % server_jar.path
+
+orbited = OrbitedServer()
+selenium_rc = SeleniumRCServer()
+
+# def setup():
+#     orbited.start()
+#     selenium_rc.start()
+    
+# def teardown():
+#     selenium_rc.stop()
+#     orbited.stop()
+
+class TCPSocketTestCase(object):
+    
+    def test_tcp_socket(self):
+        BROWSERS = ["*firefox",
+                    ]
+        
+        for browser in BROWSERS:
+            yield self._tcp_socket_test, browser
+    
+    def _tcp_socket_test(self, browser):
+        sel = selenium('localhost', 4444, browser, "http://%s:8000/" % self.domain)
+        sel.start()
+        
+        sel.open("/static/tests/")
+        sel.click("link=%s" % self.label)
+        sel.wait_for_page_to_load("30000")
+        time.sleep(0.5)
+        assert sel.is_text_present("TEST SUMMARY")
+        time.sleep(0.5)
+        assert sel.is_text_present("5 tests in 1 groups")
+        assert sel.is_text_present("0 errors")
+        assert sel.is_text_present("0 failures")
+        
+        sel.stop()

File daemon/orbited/test/functional/test_cross_port_tcp_socket.py

+from selenium import selenium
+import time, re
+
+from orbited.test.functional import TCPSocketTestCase
+
+class TestCrossPortTCPSocket(TCPSocketTestCase):
+    domain = "xp.orbited"
+    label = "Cross-Port"

File daemon/orbited/test/functional/test_cross_subdomain_tcp_socket.py

+from selenium import selenium
+import time, re
+
+from orbited.test.functional import TCPSocketTestCase
+
+class TestCrossSubdomainTCPSocket(TCPSocketTestCase):
+    domain = "www.orbited"
+    label = "Cross-Subdomain"
+

File daemon/orbited/test/functional/test_same_domain_tcp_socket.py

+from selenium import selenium
+import time, re
+
+from orbited.test.functional import TCPSocketTestCase
+
+class TestSameDomainTCPSocket(TCPSocketTestCase):
+    domain = "localhost"
+    label = "Same Domain"

File daemon/orbited/test/reports/coverage/index.html

-<html><head><title>Coverage Index</title></head><body><p>Covered: 0 lines<br/>
-Missed: 2 lines<br/>
-Skipped 2 lines<br/>
-Percent: 0 %<br/>
-<table><tr><td>File</td><td>Covered</td><td>Missed</td><td>Skipped</td><td>Percent</td></tr><tr><td><a href="orbited.html">orbited</a></td><td>0</td><td>1</td><td>1</td><td>0 %</td></tr><tr><td><a href="orbited._version.html">orbited._version</a></td><td>0</td><td>1</td><td>1</td><td>0 %</td></tr></table></p></html

File daemon/orbited/test/reports/coverage/orbited._version.html

-<html>
-<head>
-<title>orbited._version</title>
-</head>
-<body>
-orbited._version
-<style>
-.coverage pre {float: left; margin: 0px 1em; border: none;
-               padding: 0px; }
-.num pre { margin: 0px }
-.nocov, .nocov pre {background-color: #faa}
-.cov, .cov pre {background-color: #cfc}
-div.coverage div { clear: both; height: 1.1em}
-</style>
-<div class="stats">
-Covered: 0 lines<br/>
-Missed: 1 lines<br/>
-Skipped 1 lines<br/>
-Percent: 0 %<br/>
-
-</div>
-<div class="coverage">
-<div class="nocov"><span class="num"><pre>1</pre></span><pre>__version__ = &quot;0.7.11&quot;</pre></div>
-<div class="skip"><span class="num"><pre>2</pre></span><pre></pre></div>
-</div>
-</body>
-</html>

File daemon/orbited/test/reports/coverage/orbited.html

-<html>
-<head>
-<title>orbited</title>
-</head>
-<body>
-orbited
-<style>
-.coverage pre {float: left; margin: 0px 1em; border: none;
-               padding: 0px; }
-.num pre { margin: 0px }
-.nocov, .nocov pre {background-color: #faa}
-.cov, .cov pre {background-color: #cfc}
-div.coverage div { clear: both; height: 1.1em}
-</style>
-<div class="stats">
-Covered: 0 lines<br/>
-Missed: 1 lines<br/>
-Skipped 1 lines<br/>
-Percent: 0 %<br/>
-
-</div>
-<div class="coverage">
-<div class="nocov"><span class="num"><pre>1</pre></span><pre>from orbited._version import __version__</pre></div>
-<div class="skip"><span class="num"><pre>2</pre></span><pre></pre></div>
-</div>
-</body>
-</html>

File daemon/orbited/test/resources/orbited-debug.cfg

+[global]
+session.ping_interval = 10
+session.ping_timeout = 5
+user=orbited
+
+[listen]
+http://:8000
+http://:5000
+echo://:8001
+lineecho://:8002
+rude://:8003
+announce://:8004
+monitor://:8005
+stomp://:61613
+# uncomment to enable ssl on port 8043 using given .key and .crt files
+#https://:8043
+#
+#[ssl]
+#key=orbited.key
+#crt=orbited.crt
+
+[test]
+stompdispatcher.enabled = 1
+
+[static]
+
+[access]
+# freenode irc:
+* -> irc.freenode.net:6667
+# local stomp:
+* -> localhost:61613
+# local irc:
+* -> localhost:6667
+# local jabber/xmpp:
+* -> localhost:5222
+# local websocket:
+* -> localhost:81
+# local test port:
+* -> localhost:7777
+# built-in debugging servers
+* -> localhost:8001     # echo
+* -> localhost:8002     # lineecho
+* -> localhost:8003     # rude
+* -> localhost:8004     # announce
+* -> localhost:8005     # daemon monitoring feed
+
+# new logging configuration using the python stdlib logging.fileConfig
+[loggers]
+keys = root,orbited
+
+[handlers]
+keys = console, debug, info, error
+
+[formatters]
+keys = generic
+
+[logger_root]
+level = NOTSET
+handlers = console
+
+[logger_orbited]
+level = DEBUG
+handlers = 
+qualname = orbited
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+
+[handler_debug]
+class = FileHandler
+level = DEBUG
+formatter = generic
+args = ('debug.log', 'w')
+
+[handler_info]
+class = FileHandler
+level = INFO
+formatter = generic
+args = ('info.log', 'w')
+
+[handler_error]
+class = FileHandler
+level = ERROR
+formatter = generic
+args = ('error.log', 'w')
+
+[formatter_generic]
+format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
+datefmt = %H:%M:%S

File daemon/orbited/test/test_start.py

+from orbited.start import _parse_url
+from orbited.start import URLParseResult
+
+class TestURLParsing(object):
+    fields = ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')
+    
+    def test_url_parse_result(self):
+        test_tuple = (0, 0, 1, 1, 2, 3)
+        result = URLParseResult(test_tuple)
+        for index, field in enumerate(self.fields):
+            assert test_tuple[index] == result[index]
+            assert test_tuple[index] == getattr(result, field), field

File daemon/orbited/transports/base.py

         self.packets = []
         self.request = request
         self.opened()
-#        self.request.notifiyFinish().addCallback(self.finished)
+        self.request.notifyFinish().addBoth(self.finished)
         self.resetHeartbeat()
         self.closeDeferred = defer.Deferred()
         self.conn.transportOpened(self)
 
     def doHeartbeat(self):
         if self.closed:
-            logger.debug("don't send hearbeat -- we should be closed", )
+            logger.debug("don't send hearbeat -- we should be closed")
             raise Exception("show tb...")
         else:
             self.writeHeartbeat()
             self.heartbeatTimer.cancel()
             self.resetHeartbeat()
 
-    # i don't think this is ever called...
     def finished(self, arg):
+        """ Callback and Errback for self.request.notifyFinish.
+            
+            Commonly called because the connection is lost before the response
+            is sent. 
+        """
         logger.debug('finished: %s'%(arg,))
         self.request = None
         self.close()
             logger.debug('close called - already closed')
             return
         self.closed = True
-        logger.debug('close ', repr(self))
+        logger.debug('close %r', repr(self))
         self.heartbeatTimer.cancel()
         self.heartbeatTimer = None
         self.open = False

File daemon/release.cfg

+[general]
+name = orbited
+version = 0.7.11
+author = Michael Carter
+author_email = CarterMichael@gmail.com
+maintainer = Matthew Desmarais
+maintainer_email = matthew.desmarais@gmail.com
+url = http://www.orbited.org
+license = MIT License
+description = 
+    A browser(javascript)->tcp bridge; Comet is used to emulate TCP connections
+    in the browser; Allows you to connect a web browser directly to an IRC or
+    XMPP server, for instance.
+long_description = '',
+zip_safe = False
+classifiers = 
+    Development Status :: 4 - Beta
+    Environment :: Console
+    Intended Audience :: Developers
+    License :: OSI Approved :: MIT License
+    Operating System :: OS Independent
+    Programming Language :: Python
+    Topic :: Software Development :: Libraries :: Python Modules
+package_data = 
+    *.js 
+    *.html
+    *.css 
+    *.ico 
+    *.gif 
+    *.jpg 
+    *.png 
+    *.txt*
+    *.py
+    *.template
+
+[distributions]
+eggs = 2.4 2.5 2.6 2.7 3.0 3.1
+source = True
+
+[entry_points:console_scripts]
+orbited = orbited.start:main
+
+[install_requires]
+morbid = ge 0.8.7.3
+twisted = eq 10.1
+
+[packages]
+setup = setuptools

File daemon/setup.cfg

+[setup]
+tag = dev
+
 [nosetests]
 verbose=True
 verbosity=3
 cover-erase=True
 cover-html=True
 cover-html-dir=reports/coverage
+exe=True

File daemon/setup.py

             ]) },
         zip_safe = False,
         install_requires = ['morbid >= 0.8.7.3',
-                            'coverage == 3.3.1',
-                            'twisted'],
+                            'twisted==10.1'],
         entry_points = '''
             [console_scripts]
             orbited = orbited.start:main