Bug 996862 - Remove NetworkTools from mozdevice. r=ahal
authorWilliam Lachance <wlach@mozilla.com>
Mon, 21 Apr 2014 15:56:42 -0400
changeset 180255 b65cb4bc310fe4922ce042a78a0e7cfbdd940dea
parent 180254 b035f5a9c20e34a8d6aff18b05fc2f6190edca04
child 180256 e2514d232f9058d06ca6065b93c145a72f3dfe14
push id272
push userpvanderbeken@mozilla.com
push dateMon, 05 May 2014 16:31:18 +0000
reviewersahal
bugs996862
milestone31.0a1
Bug 996862 - Remove NetworkTools from mozdevice. r=ahal
testing/mozbase/mozdevice/mozdevice/devicemanager.py
testing/mozbase/mozdevice/mozdevice/devicemanagerSUT.py
testing/mozbase/mozdevice/mozdevice/droid.py
testing/mozbase/mozdevice/setup.py
testing/mozbase/mozdevice/sut_tests/dmunit.py
--- a/testing/mozbase/mozdevice/mozdevice/devicemanager.py
+++ b/testing/mozbase/mozdevice/mozdevice/devicemanager.py
@@ -568,75 +568,16 @@ class DeviceManager(object):
                     break
             if needsQuoting:
                 arg = '\'%s\'' % arg
 
             quotedCmd.append(arg)
 
         return " ".join(quotedCmd)
 
-
-class NetworkTools:
-    def __init__(self):
-        pass
-
-    # Utilities to get the local ip address
-    def getInterfaceIp(self, ifname):
-        if os.name != "nt":
-            import fcntl
-            import struct
-            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-            return socket.inet_ntoa(fcntl.ioctl(
-                                    s.fileno(),
-                                    0x8915,  # SIOCGIFADDR
-                                    struct.pack('256s', ifname[:15])
-                                    )[20:24])
-        else:
-            return None
-
-    def getLanIp(self):
-        try:
-            ip = socket.gethostbyname(socket.gethostname())
-        except socket.gaierror:
-            ip = socket.gethostbyname(socket.gethostname() + ".local") # for Mac OS X
-        if (ip is None or ip.startswith("127.")) and os.name != "nt":
-            interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
-            for ifname in interfaces:
-                try:
-                    ip = self.getInterfaceIp(ifname)
-                    break
-                except IOError:
-                    pass
-        return ip
-
-    # Gets an open port starting with the seed by incrementing by 1 each time
-    def findOpenPort(self, ip, seed):
-        try:
-            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
-            connected = False
-            if isinstance(seed, basestring):
-                seed = int(seed)
-            maxportnum = seed + 5000 # We will try at most 5000 ports to find an open one
-            while not connected:
-                try:
-                    s.bind((ip, seed))
-                    connected = True
-                    s.close()
-                    break
-                except:
-                    if seed > maxportnum:
-                        self._logger.error("Automation Error: Could not find open port after checking 5000 ports")
-                        raise
-                seed += 1
-        except:
-            self._logger.error("Automation Error: Socket error trying to find open port")
-
-        return seed
-
 def _pop_last_line(file_obj):
     """
     Utility function to get the last line from a file (shared between ADB and
     SUT device managers). Function also removes it from the file. Intended to
     strip off the return code from a shell command.
     """
     bytes_from_end = 1
     file_obj.seek(0, 2)
--- a/testing/mozbase/mozdevice/mozdevice/devicemanagerSUT.py
+++ b/testing/mozbase/mozdevice/mozdevice/devicemanagerSUT.py
@@ -1,23 +1,24 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import datetime
 import mozlog
+import moznetwork
 import select
 import socket
 import time
 import os
 import re
 import posixpath
 import subprocess
 import StringIO
-from devicemanager import DeviceManager, DMError, NetworkTools, _pop_last_line
+from devicemanager import DeviceManager, DMError, _pop_last_line
 import errno
 from distutils.version import StrictVersion
 
 class DeviceManagerSUT(DeviceManager):
     """
     Implementation of DeviceManager interface that speaks to a device over
     TCP/IP using the "system under test" protocol. A software agent such as
     Negatus (http://github.com/mozilla/Negatus) or the Mozilla Android SUTAgent
@@ -726,20 +727,16 @@ class DeviceManagerSUT(DeviceManager):
             destDir = posixpath.dirname(filePath)
 
         if destDir[-1] != '/':
             destDir += '/'
 
         self._runCmds([{ 'cmd': 'unzp %s %s' % (filePath, destDir)}])
 
     def _getRebootServerSocket(self, ipAddr):
-        # FIXME: getLanIp() only works on linux -- someday would be nice to
-        # replace this with moznetwork, but we probably don't want to add
-        # more internal deps to mozdevice while it's still being used by
-        # things like talos and sut_tools which pull us in statically
         serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         serverSocket.settimeout(60.0)
         serverSocket.bind((ipAddr, 0))
         serverSocket.listen(1)
         self._logger.debug('Created reboot callback server at %s:%d' %
                            serverSocket.getsockname())
         return serverSocket
@@ -785,18 +782,17 @@ class DeviceManagerSUT(DeviceManager):
 
         # if we're waiting, create a listening server and pass information on
         # it to the device before rebooting (we do this instead of just polling
         # to make sure the device actually rebooted -- yes, there are probably
         # simpler ways of doing this like polling uptime, but this is what we're
         # doing for now)
         if wait:
             if not ipAddr:
-                nettools = NetworkTools()
-                ipAddr = nettools.getLanIp()
+                ipAddr = moznetwork.get_ip()
             serverSocket = self._getRebootServerSocket(ipAddr)
             # The update.info command tells the SUTAgent to send a TCP message
             # after restarting.
             destname = '/data/data/com.mozilla.SUTAgentAndroid/files/update.info'
             data = "%s,%s\rrebooting\r" % serverSocket.getsockname()
             self._runCmds([{'cmd': 'push %s %s' % (destname, len(data)),
                             'data': data}])
             cmd += " %s %s" % serverSocket.getsockname()
@@ -884,18 +880,17 @@ class DeviceManagerSUT(DeviceManager):
         else:
             cmd += processName + ' ' + appBundlePath
 
         if destPath:
             cmd += " " + destPath
 
         if wait:
             if not ipAddr:
-                nettools = NetworkTools()
-                ipAddr = nettools.getLanIp()
+                ipAddr = moznetwork.get_ip()
             serverSocket = self._getRebootServerSocket(ipAddr)
             cmd += " %s %s" % serverSocket.getsockname()
 
         self._logger.debug("updateApp using command: " % cmd)
 
         self._runCmds([{'cmd': cmd}])
 
         if wait:
--- a/testing/mozbase/mozdevice/mozdevice/droid.py
+++ b/testing/mozbase/mozdevice/mozdevice/droid.py
@@ -1,18 +1,19 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import StringIO
+import moznetwork
 import re
 import threading
 
 from Zeroconf import Zeroconf, ServiceBrowser
-from devicemanager import ZeroconfListener, NetworkTools
+from devicemanager import ZeroconfListener
 from devicemanagerADB import DeviceManagerADB
 from devicemanagerSUT import DeviceManagerSUT
 from devicemanager import DMError
 
 class DroidMixin(object):
     """Mixin to extend DeviceManager with Android-specific functionality"""
 
     def _getExtraAmStartArgs(self):
@@ -164,27 +165,24 @@ class DroidSUT(DeviceManagerSUT, DroidMi
 
         return []
 
     def getTopActivity(self):
         return self._runCmds([{ 'cmd': "activity" }]).strip()
 
 def DroidConnectByHWID(hwid, timeout=30, **kwargs):
     """Try to connect to the given device by waiting for it to show up using mDNS with the given timeout."""
-    nt = NetworkTools()
-    local_ip = nt.getLanIp()
-
-    zc = Zeroconf(local_ip)
+    zc = Zeroconf(moznetwork.get_ip())
 
     evt = threading.Event()
     listener = ZeroconfListener(hwid, evt)
     sb = ServiceBrowser(zc, "_sutagent._tcp.local.", listener)
     foundIP = None
     if evt.wait(timeout):
-        # we found the hwid 
+        # we found the hwid
         foundIP = listener.ip
     sb.cancel()
     zc.close()
 
     if foundIP is not None:
         return DroidSUT(foundIP, **kwargs)
     print "Connected via SUT to %s [at %s]" % (hwid, foundIP)
 
--- a/testing/mozbase/mozdevice/setup.py
+++ b/testing/mozbase/mozdevice/setup.py
@@ -4,16 +4,17 @@
 
 from setuptools import setup
 
 PACKAGE_NAME = 'mozdevice'
 PACKAGE_VERSION = '0.33'
 
 deps = ['mozfile >= 1.0',
         'mozlog',
+        'moznetwork >= 0.24'
        ]
 
 setup(name=PACKAGE_NAME,
       version=PACKAGE_VERSION,
       description="Mozilla-authored device management",
       long_description="see http://mozbase.readthedocs.org/",
       classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
       keywords='',
--- a/testing/mozbase/mozdevice/sut_tests/dmunit.py
+++ b/testing/mozbase/mozdevice/sut_tests/dmunit.py
@@ -27,17 +27,16 @@ class DeviceManagerTestCase(unittest.Tes
     def _setUp(self):
         """ Override this if you want set-up code in your test."""
         return
 
     def setUp(self):
         self.dm = devicemanagerSUT.DeviceManagerSUT(host=ip, port=port,
                                                     logLevel=log_level)
         self.dmerror = devicemanager.DMError
-        self.nettools = devicemanager.NetworkTools
         self._setUp()
 
 
 class DeviceManagerTestLoader(unittest.TestLoader):
 
     def __init__(self, isTestDevice=False):
         self.isTestDevice = isTestDevice