autotest: Clean up default SSID logic

This causes stumpy cells to stop having SSIDs that start with
chromeos1-shelf...  This was happening because the path to the
ip command is different on stumpy cells, and this logic was hardcoding
this command.  Fix this by moving the building up of default SSIDs to
inside the Linux router where it rightly belongs.

BUG=None
TEST=Ran wifi_matfunc suite, which shows that both old and new style
tests are compatible with this change.  Ran a test out of
network_WiFiPerf which actually triggers the SSID generation logic
to prove that older WiFi tests also benefit from this change.

Change-Id: Ib33407503a0a1c6d8922d84e9c4458be43a6dd06
Reviewed-on: https://gerrit.chromium.org/gerrit/64955
Tested-by: Christopher Wiley <wiley@chromium.org>
Reviewed-by: mukesh agrawal <quiche@chromium.org>
Commit-Queue: Christopher Wiley <wiley@chromium.org>
diff --git a/server/cros/network/hostap_config.py b/server/cros/network/hostap_config.py
index d2f9037..ae923b4 100644
--- a/server/cros/network/hostap_config.py
+++ b/server/cros/network/hostap_config.py
@@ -4,8 +4,6 @@
 
 import copy
 import logging
-import random
-import string
 
 from autotest_lib.client.common_lib import error
 from autotest_lib.client.common_lib.cros.network import xmlrpc_security_types
@@ -197,9 +195,7 @@
 
         self.wmm_enabled = False
         self.hw_mode = mode or self.MODE_11B
-        suffix_letters = string.ascii_lowercase + string.digits
-        unique_suffix = ''.join(random.choice(suffix_letters) for x in range(5))
-        self.ssid_suffix = '_%s_ch%d' % (unique_suffix, self.channel)
+        self.ssid_suffix = '_ch%d' % self.channel
         if n_capabilities is None:
             n_capabilities = []
         self.n_capabilities = set()
@@ -268,15 +264,5 @@
                         self.security_config))
 
 
-    def get_ssid(self, default_ssid):
-        """Build up the SSID for this network given a router's default SSID.
-
-        @param default_ssid string default ssid for a router.
-        @return string configured ssid or a slight mutation of the default ssid.
-
-        """
-        return self.ssid or (default_ssid + self.ssid_suffix)[-32:]
-
-
     def get_security_hostapd_conf(self):
         return self.security_config.get_hostapd_config()
diff --git a/server/cros/network/wifi_test_context_manager.py b/server/cros/network/wifi_test_context_manager.py
index c54b5f6..7e95c56 100644
--- a/server/cros/network/wifi_test_context_manager.py
+++ b/server/cros/network/wifi_test_context_manager.py
@@ -186,16 +186,12 @@
         router_host = hosts.SSHHost(self.router_address, port=router_port)
         # TODO(wiley) Simplify the router and make the parameters explicit.
         router_params = {}
-        default_ssid = wifi_test_utils.get_default_ssid(self._test_name,
-                                                        self.router_address,
-                                                        router_host)
-        logging.info('Default router SSID is %s.', default_ssid)
         if site_linux_cros_router.isLinuxCrosRouter(router_host):
             self._router = site_linux_cros_router.LinuxCrosRouter(
-                    router_host, router_params, default_ssid)
+                    router_host, router_params, self._test_name)
         else:
             self._router = site_linux_bridge_router.LinuxBridgeRouter(
-                    router_host, router_params, default_ssid)
+                    router_host, router_params, self._test_name)
         # If we're testing WiFi, we're probably going to need one of these.
         self._router.create_wifi_device()
         # The '_server' is a machine which hosts network
diff --git a/server/cros/wifi_test_utils.py b/server/cros/wifi_test_utils.py
index a72ff68..b423887 100644
--- a/server/cros/wifi_test_utils.py
+++ b/server/cros/wifi_test_utils.py
@@ -2,7 +2,6 @@
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
-import base64
 import datetime
 import logging
 import os
@@ -137,47 +136,6 @@
     raise error.TestFail('Unable to find %s on %s' % (cmd, host.ip))
 
 
-def get_default_ssid(test_name, ipaddr, host):
-    """
-    Calculate ssid based on test name.
-
-    This lets us track progress by watching beacon frames.  Generate a unique
-    suffix for this SSID based either a unique MAC address on the AP, or
-    failing this, the IP address of the AP.
-
-    @param test_name String name of this test (e.g. network_WiFiMatFunc).
-    @param ipaddr String IP address of the AP in this test.
-    @param host Host object representing the router.
-    @return String 32 character SSID.
-
-    """
-    if test_name.find('network_') == 0:
-        # Many of our tests start with this very uninteresting prefix.
-        # Remove it so we can have more unique substring bytes.
-        test_name = test_name[len('network_'):]
-    address_lines = []
-    if host:
-        address_lines = host.run('/usr/sbin/ip addr show',
-                                 ignore_status=True).stdout.splitlines()
-
-    mac_re = re.compile('link/ether (?P<mac>(([0-9a-f]{2}):?){6}) ',
-                        flags=re.IGNORECASE)
-    for line in address_lines:
-        mac_match = mac_re.search(line)
-        if mac_match:
-            mac_string = mac_match.group('mac')
-            if mac_string not in ['00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff']:
-                mac_bytes = ''
-                for octet in mac_string.split(':'):
-                    mac_bytes += chr(int(octet, 16))
-                unique_name = base64.b64encode(mac_bytes)
-                break
-    else:
-        unique_name = ipaddr
-    return re.sub('[^a-zA-Z0-9_]', '_', '%s_%s' %
-            (test_name, unique_name))[0:32]
-
-
 def get_wlan_devs(host, command_iw):
     """Get a list of WiFi devices.
 
diff --git a/server/site_linux_bridge_router.py b/server/site_linux_bridge_router.py
index 130304a..27e31b5 100644
--- a/server/site_linux_bridge_router.py
+++ b/server/site_linux_bridge_router.py
@@ -16,8 +16,8 @@
     """
 
 
-    def __init__(self, host, params, defssid):
-        site_linux_router.LinuxRouter.__init__(self, host, params, defssid)
+    def __init__(self, host, params, test_name):
+        site_linux_router.LinuxRouter.__init__(self, host, params, test_name)
 
         self.bridgeif = params.get('bridgedev', "br-lan")
         self.wiredif = params.get('wiredev', "eth0")
diff --git a/server/site_linux_cros_router.py b/server/site_linux_cros_router.py
index 7963747..1e66308 100644
--- a/server/site_linux_cros_router.py
+++ b/server/site_linux_cros_router.py
@@ -29,7 +29,7 @@
                 [self.CAPABILITY_IBSS])
 
 
-    def __init__(self, host, params, defssid):
+    def __init__(self, host, params, test_name):
         cros_params = params.copy()
         cros_params.update({
             'cmd_ip': '/usr/local/sbin/ip',
@@ -41,7 +41,7 @@
                 'monitor': 'usb',
                 'managed': 'pci'
             }})
-        super(LinuxCrosRouter, self).__init__(host, cros_params, defssid)
+        super(LinuxCrosRouter, self).__init__(host, cros_params, test_name)
         self.cmd_iptables = params.get('cmd_iptables', '/sbin/iptables')
 
 
diff --git a/server/site_linux_router.py b/server/site_linux_router.py
index 1a3c4e1..bbf6bcf 100644
--- a/server/site_linux_router.py
+++ b/server/site_linux_router.py
@@ -2,8 +2,11 @@
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
+import base64
 import logging
+import random
 import re
+import string
 
 from autotest_lib.client.common_lib import error
 from autotest_lib.server import site_linux_system
@@ -32,6 +35,8 @@
 
     """
 
+    KNOWN_TEST_PREFIX = 'network_WiFi'
+    SUFFIX_LETTERS = string.ascii_lowercase + string.digits
 
     def get_capabilities(self):
         """@return iterable object of AP capabilities for this system."""
@@ -45,12 +50,12 @@
         return super(LinuxRouter, self).get_capabilities().union(caps)
 
 
-    def __init__(self, host, params, defssid):
+    def __init__(self, host, params, test_name):
         """Build a LinuxRouter.
 
         @param host Host object representing the remote machine.
         @param params dict of settings from site_wifitest based tests.
-        @param defssid string default SSID for networks created on this router.
+        @param test_name string name of this test.  Used in SSID creation.
 
         """
         site_linux_system.LinuxSystem.__init__(self, host, params, 'router')
@@ -68,9 +73,15 @@
 
         # hostapd configuration persists throughout the test, subsequent
         # 'config' commands only modify it.
-        self.defssid = defssid
+        self.ssid_prefix = test_name
+        if self.ssid_prefix.startswith(self.KNOWN_TEST_PREFIX):
+            # Many of our tests start with an uninteresting prefix.
+            # Remove it so we can have more unique bytes.
+            self.ssid_prefix = self.ssid_prefix[len(self.KNOWN_TEST_PREFIX):]
+        self.ssid_prefix = self.ssid_prefix.lstrip('_')
+        self.ssid_prefix += '_'
+
         self.default_config = {
-            'ssid': defssid,
             'hw_mode': 'g',
             'ctrl_interface': '/tmp/hostapd-test.control',
             'logger_syslog': '-1',
@@ -86,9 +97,7 @@
         }
         self.station = {
             'configured': False,
-            'conf': {
-                'ssid': defssid,
-            },
+            'conf': {},
         }
         self.local_servers = []
         self.hostapd_instances = []
@@ -251,9 +260,16 @@
         conf['rts_threshold'] = '2347'
         conf['fragm_threshold'] = '2346'
         conf['driver'] = self.hostapd['driver']
+        conf['ssid'] = self._get_ssid('')
         return conf
 
 
+    def _get_ssid(self, suffix):
+        unique_salt = ''.join([random.choice(self.SUFFIX_LETTERS)
+                               for x in range(5)])
+        return (self.ssid_prefix + unique_salt + suffix)[-32:]
+
+
     def hostap_configure(self, configuration, multi_interface=None):
         """Build up a hostapd configuration file and start hostapd.
 
@@ -268,7 +284,8 @@
             self.deconfig()
         # Start with the default hostapd config parameters.
         conf = self.__get_default_hostap_config()
-        conf['ssid'] = configuration.get_ssid(self.defssid)
+        conf['ssid'] = (configuration.ssid or
+                        self._get_ssid(configuration.ssid_suffix))
         if configuration.bssid:
             conf['bssid'] = configuration.bssid
         conf['channel'] = configuration.channel
@@ -332,7 +349,7 @@
             if k == 'ssid':
                 conf['ssid'] = v
             elif k == 'ssid_suffix':
-                conf['ssid'] = self.defssid[:(32-len(v))] + v
+                conf['ssid'] = self._get_ssid(v)
             elif k == 'channel':
                 freq = int(v)
                 self.hostapd['frequency'] = freq
@@ -492,12 +509,13 @@
             self.deconfig()
         interface = self._get_wlanif(config.frequency, self.phytype,
                                      config.hw_mode)
-        ssid = config.get_ssid(self.defssid)
-        self.station['conf']['ssid'] = ssid
+        self.station['conf']['ssid'] = (config.ssid or
+                                        self._get_ssid(config.ssid_suffix))
         # Connect the station
         self.router.run('%s link set %s up' % (self.cmd_ip, interface))
-        self.router.run('%s dev %s ibss join %s %d' % (self.cmd_iw, interface,
-                                                       ssid, config.frequency))
+        self.router.run('%s dev %s ibss join %s %d' % (
+                self.cmd_iw, interface, self.station['conf']['ssid'],
+                config.frequency))
         # Always start a local server.
         self.start_local_server(interface)
         # Remember that this interface is up.
@@ -719,6 +737,9 @@
         if self.hostapd['configured']:
             return self.hostapd['conf']['ssid']
 
+        if not 'ssid' in self.station['conf']:
+            raise error.TestFail('Requested ssid of an unconfigured AP.')
+
         return self.station['conf']['ssid']
 
 
diff --git a/server/site_wifitest.py b/server/site_wifitest.py
index 081ca73..2a36dca 100644
--- a/server/site_wifitest.py
+++ b/server/site_wifitest.py
@@ -141,9 +141,6 @@
 
         self.router = hosts.SSHHost(router['addr'],
                                     port=int(router.get('port', 22)))
-        self.defssid = wifi_test_utils.get_default_ssid(self.name,
-                                                        router['addr'],
-                                                        self.router)
 
         defaults = config.get('defaults', {})
         self.deftimeout = defaults.get('timeout', 30)
@@ -156,10 +153,10 @@
 
         if site_linux_cros_router.isLinuxCrosRouter(self.router):
             self.wifi = site_linux_cros_router.LinuxCrosRouter(
-                self.router, router, self.defssid)
+                self.router, router, self.name)
         else:
             self.wifi = site_linux_bridge_router.LinuxBridgeRouter(
-                self.router, router, self.defssid)
+                self.router, router, self.name)
 
         attenuator = config.get('attenuator', dict())
         # NB: Attenuator must be reachable on the control network