Refactor codes of the definition of ForwardedPorts

Bug: 122929848
Bug: 127394991
Test: m acloud && atest acloud_test && acloud list && acloud reconnect
Change-Id: I5ca1383843827661708cb7441ea24f0588c0e2ab
diff --git a/create/cheeps_remote_image_remote_instance.py b/create/cheeps_remote_image_remote_instance.py
index ef3b260..1b9f562 100644
--- a/create/cheeps_remote_image_remote_instance.py
+++ b/create/cheeps_remote_image_remote_instance.py
@@ -56,8 +56,7 @@
             device_factory=device_factory,
             num=avd_spec.num,
             autoconnect=avd_spec.autoconnect,
-            vnc_port=constants.DEFAULT_CHEEPS_TARGET_VNC_PORT,
-            adb_port=constants.DEFAULT_CHEEPS_TARGET_ADB_PORT)
+            avd_type=constants.TYPE_CHEEPS)
 
         # Launch vnc client if we're auto-connecting.
         if avd_spec.autoconnect:
diff --git a/create/local_image_local_instance.py b/create/local_image_local_instance.py
index 147cd3a..abbddd7 100644
--- a/create/local_image_local_instance.py
+++ b/create/local_image_local_instance.py
@@ -82,8 +82,8 @@
         result_report.SetStatus(report.Status.SUCCESS)
         result_report.AddData(
             key="devices",
-            value={"adb_port": constants.DEFAULT_ADB_PORT,
-                   constants.VNC_PORT: constants.DEFAULT_VNC_PORT})
+            value={constants.ADB_PORT: constants.CF_ADB_PORT,
+                   constants.VNC_PORT: constants.CF_VNC_PORT})
         # Launch vnc client if we're auto-connecting.
         if avd_spec.autoconnect:
             utils.LaunchVNCFromReport(result_report, avd_spec, no_prompts)
@@ -132,7 +132,7 @@
         launch_cvd_w_args = launch_cvd_path + _CMD_LAUNCH_CVD_ARGS % (
             hw_property["cpu"], hw_property["x_res"], hw_property["y_res"],
             hw_property["dpi"], hw_property["memory"], hw_property["disk"],
-            system_image_dir, constants.DEFAULT_VNC_PORT)
+            system_image_dir, constants.CF_VNC_PORT)
 
         launch_cmd = utils.AddUserGroupsToCmd(launch_cvd_w_args,
                                               constants.LIST_CF_USER_GROUPS)
@@ -165,7 +165,7 @@
                         stderr=dev_null, stdout=dev_null, shell=True)
 
                 # Delete ssvnc viewer
-                delete.CleanupSSVncviewer(constants.CF_TARGET_VNC_PORT)
+                delete.CleanupSSVncviewer(constants.CF_VNC_PORT)
 
             else:
                 print("Exiting out")
diff --git a/create/local_image_remote_instance.py b/create/local_image_remote_instance.py
index 4aab1e2..e507fb4 100644
--- a/create/local_image_remote_instance.py
+++ b/create/local_image_remote_instance.py
@@ -287,8 +287,7 @@
             "create_cf", avd_spec.cfg, device_factory, avd_spec.num,
             report_internal_ip=avd_spec.report_internal_ip,
             autoconnect=avd_spec.autoconnect,
-            vnc_port=constants.CF_TARGET_VNC_PORT,
-            adb_port=constants.CF_TARGET_ADB_PORT)
+            avd_type=constants.TYPE_CF)
         # Launch vnc client if we're auto-connecting.
         if avd_spec.autoconnect:
             utils.LaunchVNCFromReport(report, avd_spec, no_prompts)
diff --git a/delete/delete.py b/delete/delete.py
index bdd0096..2d5ec70 100644
--- a/delete/delete.py
+++ b/delete/delete.py
@@ -173,8 +173,8 @@
     except subprocess.CalledProcessError as e:
         delete_report.AddError(str(e))
         delete_report.SetStatus(report.Status.FAIL)
-
-    CleanupSSVncviewer(constants.DEFAULT_VNC_PORT)
+    # Only CF supports local instances so assume it's a CF VNC port.
+    CleanupSSVncviewer(constants.CF_VNC_PORT)
     return delete_report
 
 
diff --git a/internal/constants.py b/internal/constants.py
index b5cb4f2..f0b6796 100755
--- a/internal/constants.py
+++ b/internal/constants.py
@@ -92,25 +92,21 @@
 
 # Cuttlefish groups
 LIST_CF_USER_GROUPS = ["kvm", "cvdnetwork"]
-#For the cuttlefish remote instances: adb port is 6520 and vnc is 6444.
-CF_TARGET_ADB_PORT = 6520
-CF_TARGET_VNC_PORT = 6444
 
-# For gce_x86_phones remote instances
-DEFAULT_GCE_VNC_PORT = 6444
-DEFAULT_GCE_ADB_PORT = 5555
-# For goldfish remote instances
-DEFAULT_GOLDFISH_VNC_PORT = 6444
-DEFAULT_GOLDFISH_ADB_PORT = 5555
-# For cuttlefish remote instances
-DEFAULT_VNC_PORT = 6444
-DEFAULT_ADB_PORT = 6520
-VNC_PORT = "vnc_port"
 ADB_PORT = "adb_port"
-
-# For cheeps remote instances.
-DEFAULT_CHEEPS_TARGET_ADB_PORT = 9222
-DEFAULT_CHEEPS_TARGET_VNC_PORT = 5900
+VNC_PORT = "vnc_port"
+# For cuttlefish remote instances
+CF_ADB_PORT = 6520
+CF_VNC_PORT = 6444
+# For cheeps remote instances
+CHEEPS_ADB_PORT = 9222
+CHEEPS_VNC_PORT = 5900
+# For gce_x86_phones remote instances
+GCE_ADB_PORT = 5555
+GCE_VNC_PORT = 6444
+# For goldfish remote instances
+GF_ADB_PORT = 5555
+GF_VNC_PORT = 6444
 
 COMMAND_PS = ["ps", "aux"]
 CMD_LAUNCH_CVD = "launch_cvd"
diff --git a/internal/lib/utils.py b/internal/lib/utils.py
index 6f527a3..6d0f4a2 100755
--- a/internal/lib/utils.py
+++ b/internal/lib/utils.py
@@ -61,6 +61,17 @@
 # Store the ports that vnc/adb are forwarded to, both are integers.
 ForwardedPorts = collections.namedtuple("ForwardedPorts", [constants.VNC_PORT,
                                                            constants.ADB_PORT])
+AVD_PORT_DICT = {
+    constants.TYPE_GCE: ForwardedPorts(constants.GCE_VNC_PORT,
+                                       constants.GCE_ADB_PORT),
+    constants.TYPE_CF: ForwardedPorts(constants.CF_VNC_PORT,
+                                      constants.CF_ADB_PORT),
+    constants.TYPE_GF: ForwardedPorts(constants.GF_VNC_PORT,
+                                      constants.GF_ADB_PORT),
+    constants.TYPE_CHEEPS: ForwardedPorts(constants.CHEEPS_VNC_PORT,
+                                          constants.CHEEPS_ADB_PORT)
+}
+
 _VNC_BIN = "ssvnc"
 _CMD_KILL = ["pkill", "-9", "-f"]
 _CMD_PGREP = "pgrep"
@@ -902,8 +913,8 @@
             PrintColorString("No VNC port specified, skipping VNC startup.",
                              TextColors.FAIL)
 
-def LaunchVncClient(port=constants.DEFAULT_VNC_PORT, avd_width=None,
-                    avd_height=None, no_prompts=False):
+
+def LaunchVncClient(port, avd_width=None, avd_height=None, no_prompts=False):
     """Launch ssvnc.
 
     Args:
diff --git a/list/instance.py b/list/instance.py
index 4cc64a7..b347785 100644
--- a/list/instance.py
+++ b/list/instance.py
@@ -26,7 +26,6 @@
 - and more!
 """
 
-import collections
 import datetime
 import logging
 import re
@@ -61,9 +60,6 @@
 _FULL_NAME_STRING = ("device serial: %(device_serial)s (%(instance_name)s) "
                      "elapsed time: %(elapsed_time)s")
 
-ForwardedPorts = collections.namedtuple("ForwardedPorts",
-                                        [constants.VNC_PORT, constants.ADB_PORT])
-
 
 def _GetElapsedTime(start_time):
     """Calculate the elapsed time from start_time till now.
@@ -225,14 +221,14 @@
                 local_instance._elapsed_time = _GetElapsedTime(date_str)
                 local_instance._fullname = (_FULL_NAME_STRING %
                                             {"device_serial": "127.0.0.1:%d" %
-                                                              constants.DEFAULT_ADB_PORT,
+                                                              constants.CF_ADB_PORT,
                                              "instance_name": local_instance._name,
                                              "elapsed_time": local_instance._elapsed_time})
                 local_instance._avd_type = constants.TYPE_CF
                 local_instance._ip = "127.0.0.1"
                 local_instance._status = constants.INS_STATUS_RUNNING
-                local_instance._adb_port = constants.DEFAULT_ADB_PORT
-                local_instance._vnc_port = constants.DEFAULT_VNC_PORT
+                local_instance._adb_port = constants.CF_ADB_PORT
+                local_instance._vnc_port = constants.CF_VNC_PORT
                 local_instance._display = ("%sx%s (%s)" % (x_res, y_res, dpi))
                 local_instance._is_local = True
                 local_instance._ssh_tunnel_is_connected = True
@@ -336,12 +332,8 @@
             used in the ssh forwarded call. Both fields are integers.
         """
         process_output = subprocess.check_output(constants.COMMAND_PS)
-        default_vnc_port = (constants.DEFAULT_GCE_VNC_PORT
-                            if avd_type == constants.TYPE_GCE
-                            else constants.DEFAULT_VNC_PORT)
-        default_adb_port = (constants.DEFAULT_GCE_ADB_PORT
-                            if avd_type == constants.TYPE_GCE
-                            else constants.DEFAULT_ADB_PORT)
+        default_vnc_port = utils.AVD_PORT_DICT[avd_type].vnc_port
+        default_adb_port = utils.AVD_PORT_DICT[avd_type].adb_port
         re_pattern = re.compile(_RE_SSH_TUNNEL_PATTERN %
                                 (_RE_GROUP_VNC, default_vnc_port,
                                  _RE_GROUP_ADB, default_adb_port, ip))
@@ -359,4 +351,4 @@
                       "IP:%s, forwarding (adb:%d, vnc:%d)"), ip, adb_port,
                      vnc_port)
 
-        return ForwardedPorts(vnc_port=vnc_port, adb_port=adb_port)
+        return utils.ForwardedPorts(vnc_port=vnc_port, adb_port=adb_port)
diff --git a/list/instance_test.py b/list/instance_test.py
index e0f4ffd..e29994b 100644
--- a/list/instance_test.py
+++ b/list/instance_test.py
@@ -57,7 +57,7 @@
         self.assertEqual("1080x1920 (480)", local_instance.display)
         self.assertEqual("Sat Nov 10 21:55:10 2018", local_instance.createtime)
         expected_full_name = "device serial: 127.0.0.1:%s (%s) elapsed time: %s" % (
-            constants.DEFAULT_ADB_PORT, constants.LOCAL_INS_NAME, "fake_time")
+            constants.CF_ADB_PORT, constants.LOCAL_INS_NAME, "fake_time")
         self.assertEqual(expected_full_name, local_instance.fullname)
 
         # test return None if no launch_cvd process found
@@ -95,7 +95,7 @@
         self.Patch(instance, "_GetElapsedTime", return_value="fake_time")
         forwarded_ports = instance.RemoteInstance(
             mock.MagicMock()).GetAdbVncPortFromSSHTunnel(
-                "fake_ip", "fake_avd_type")
+                "fake_ip", constants.TYPE_CF)
         self.assertEqual(54321, forwarded_ports.adb_port)
         self.assertEqual(12345, forwarded_ports.vnc_port)
 
diff --git a/public/actions/common_operations.py b/public/actions/common_operations.py
index ff86217..af453c9 100644
--- a/public/actions/common_operations.py
+++ b/public/actions/common_operations.py
@@ -34,6 +34,7 @@
 
 logger = logging.getLogger(__name__)
 
+
 def CreateSshKeyPairIfNecessary(cfg):
     """Create ssh key pair if necessary.
 
@@ -237,9 +238,8 @@
 # TODO: Delete unused-argument when b/119614469 is resolved.
 # pylint: disable=unused-argument
 # pylint: disable=too-many-locals
-def CreateDevices(command, cfg, device_factory, num,
+def CreateDevices(command, cfg, device_factory, num, avd_type,
                   report_internal_ip=False, autoconnect=False,
-                  vnc_port=None, adb_port=None,
                   serial_log_file=None, logcat_file=None):
     """Create a set of devices using the given factory.
 
@@ -252,10 +252,9 @@
         cfg: An AcloudConfig instance.
         device_factory: A factory capable of producing a single device.
         num: The number of devices to create.
+        avd_type: String, the AVD type(cuttlefish, goldfish...).
         report_internal_ip: Boolean to report the internal ip instead of
                             external ip.
-        vnc_port: (int) The VNC port to use for a remote instance.
-        adb_port: (int) The ADB port to use for a remote instance.
         serial_log_file: String, the file path to tar the serial logs.
         logcat_file: String, the file path to tar the logcats.
         autoconnect: Boolean, whether to auto connect to device.
@@ -295,14 +294,11 @@
                 "instance_name": device.instance_name
             }
             if autoconnect:
-                if (not vnc_port) or (not adb_port):
-                    logger.error("vnc_port and adb_port must be specified to"
-                                 " use autoconnect")
-                forwarded_ports = utils.AutoConnect(ip,
-                                                    cfg.ssh_private_key_path,
-                                                    vnc_port,
-                                                    adb_port,
-                                                    getpass.getuser())
+                forwarded_ports = utils.AutoConnect(
+                    ip, cfg.ssh_private_key_path,
+                    utils.AVD_PORT_DICT[avd_type].vnc_port,
+                    utils.AVD_PORT_DICT[avd_type].adb_port,
+                    getpass.getuser())
                 device_dict[constants.VNC_PORT] = forwarded_ports.vnc_port
                 device_dict[constants.ADB_PORT] = forwarded_ports.adb_port
             if device.instance_name in failures:
diff --git a/public/actions/common_operations_test.py b/public/actions/common_operations_test.py
index 205a321..a234162 100644
--- a/public/actions/common_operations_test.py
+++ b/public/actions/common_operations_test.py
@@ -36,6 +36,7 @@
     IP = gcompute_client.IP(external="127.0.0.1", internal="10.0.0.1")
     INSTANCE = "fake-instance"
     CMD = "test-cmd"
+    AVD_TYPE = "fake-type"
 
     def setUp(self):
         """Set up the test."""
@@ -84,7 +85,8 @@
         """Test Create Devices."""
         cfg = self._CreateCfg()
         _report = common_operations.CreateDevices(self.CMD, cfg,
-                                                  self.device_factory, 1)
+                                                  self.device_factory, 1,
+                                                  self.AVD_TYPE)
         self.assertEqual(_report.command, self.CMD)
         self.assertEqual(_report.status, report.Status.SUCCESS)
         self.assertEqual(
@@ -99,6 +101,7 @@
         cfg = self._CreateCfg()
         _report = common_operations.CreateDevices(self.CMD, cfg,
                                                   self.device_factory, 1,
+                                                  self.AVD_TYPE,
                                                   report_internal_ip=True)
         self.assertEqual(_report.command, self.CMD)
         self.assertEqual(_report.status, report.Status.SUCCESS)
diff --git a/public/actions/create_cuttlefish_action.py b/public/actions/create_cuttlefish_action.py
index 288d67f..6543976 100644
--- a/public/actions/create_cuttlefish_action.py
+++ b/public/actions/create_cuttlefish_action.py
@@ -162,14 +162,7 @@
         report_internal_ip)
     device_factory = CuttlefishDeviceFactory(cfg, build_target, build_id,
                                              kernel_build_id, avd_spec)
-    return common_operations.CreateDevices(
-        command="create_cf",
-        cfg=cfg,
-        device_factory=device_factory,
-        num=num,
-        report_internal_ip=report_internal_ip,
-        autoconnect=autoconnect,
-        vnc_port=constants.CF_TARGET_VNC_PORT,
-        adb_port=constants.CF_TARGET_ADB_PORT,
-        serial_log_file=serial_log_file,
-        logcat_file=logcat_file)
+    return common_operations.CreateDevices("create_cf", cfg, device_factory,
+                                           num, constants.TYPE_CF,
+                                           report_internal_ip, autoconnect,
+                                           serial_log_file, logcat_file)
diff --git a/public/actions/create_goldfish_action.py b/public/actions/create_goldfish_action.py
index 8046227..e8ca651 100644
--- a/public/actions/create_goldfish_action.py
+++ b/public/actions/create_goldfish_action.py
@@ -264,14 +264,7 @@
                                            cfg.emulator_build_target,
                                            emulator_build_id, gpu, avd_spec)
 
-    return common_operations.CreateDevices(
-        command="create_gf",
-        cfg=cfg,
-        device_factory=device_factory,
-        num=num,
-        report_internal_ip=report_internal_ip,
-        autoconnect=autoconnect,
-        vnc_port=constants.DEFAULT_GOLDFISH_VNC_PORT,
-        adb_port=constants.DEFAULT_GOLDFISH_ADB_PORT,
-        serial_log_file=serial_log_file,
-        logcat_file=logcat_file)
+    return common_operations.CreateDevices("create_gf", cfg, device_factory,
+                                           num, constants.TYPE_GF,
+                                           report_internal_ip, autoconnect,
+                                           serial_log_file, logcat_file)
diff --git a/public/device_driver.py b/public/device_driver.py
index 4d54a98..46339be 100755
--- a/public/device_driver.py
+++ b/public/device_driver.py
@@ -401,8 +401,8 @@
                 forwarded_ports = utils.AutoConnect(
                     ip,
                     cfg.ssh_private_key_path,
-                    constants.DEFAULT_GCE_VNC_PORT,
-                    constants.DEFAULT_GCE_ADB_PORT,
+                    constants.GCE_VNC_PORT,
+                    constants.GCE_ADB_PORT,
                     _SSH_USER)
                 device_dict[constants.VNC_PORT] = forwarded_ports.vnc_port
                 device_dict[constants.ADB_PORT] = forwarded_ports.adb_port
diff --git a/reconnect/reconnect.py b/reconnect/reconnect.py
index 27f6280..b4dc027 100644
--- a/reconnect/reconnect.py
+++ b/reconnect/reconnect.py
@@ -21,12 +21,10 @@
 
 from __future__ import print_function
 
-from collections import namedtuple
 import getpass
 import re
 
 from acloud.delete import delete
-from acloud.internal import constants
 from acloud.internal.lib import auth
 from acloud.internal.lib import android_compute_client
 from acloud.internal.lib import utils
@@ -36,15 +34,6 @@
 
 _RE_DISPLAY = re.compile(r"([\d]+)x([\d]+)\s.*")
 _VNC_STARTED_PATTERN = "ssvnc vnc://127.0.0.1:%(vnc_port)d"
-# TODO(b/122929848): merge all definition of ForwardedPorts into one spot.
-ForwardedPorts = namedtuple("ForwardedPorts",
-                            [constants.VNC_PORT, constants.ADB_PORT])
-_AVD_PORT_CLASS_DICT = {
-    constants.TYPE_GCE: ForwardedPorts(constants.DEFAULT_GCE_VNC_PORT,
-                                       constants.DEFAULT_GCE_ADB_PORT),
-    constants.TYPE_CF: ForwardedPorts(constants.CF_TARGET_VNC_PORT,
-                                      constants.CF_TARGET_ADB_PORT)
-}
 
 
 def StartVnc(vnc_port, display):
@@ -110,8 +99,8 @@
         forwarded_ports = utils.AutoConnect(
             instance.ip,
             ssh_private_key_path,
-            _AVD_PORT_CLASS_DICT.get(instance.avd_type).vnc_port,
-            _AVD_PORT_CLASS_DICT.get(instance.avd_type).adb_port,
+            utils.AVD_PORT_DICT[instance.avd_type].vnc_port,
+            utils.AVD_PORT_DICT[instance.avd_type].adb_port,
             getpass.getuser())
         vnc_port = forwarded_ports.vnc_port
 
diff --git a/reconnect/reconnect_test.py b/reconnect/reconnect_test.py
index b00c131..82e4b6c 100644
--- a/reconnect/reconnect_test.py
+++ b/reconnect/reconnect_test.py
@@ -74,8 +74,8 @@
         reconnect.ReconnectInstance(ssh_private_key_path, instance_object)
         utils.AutoConnect.assert_called_with(instance_object.ip,
                                              ssh_private_key_path,
-                                             constants.CF_TARGET_VNC_PORT,
-                                             constants.CF_TARGET_ADB_PORT,
+                                             constants.CF_VNC_PORT,
+                                             constants.CF_ADB_PORT,
                                              "fake_user")
         utils.LaunchVncClient.assert_called_with(11111)
 
@@ -84,8 +84,8 @@
         reconnect.ReconnectInstance(ssh_private_key_path, instance_object)
         utils.AutoConnect.assert_called_with(instance_object.ip,
                                              ssh_private_key_path,
-                                             constants.CF_TARGET_VNC_PORT,
-                                             constants.CF_TARGET_ADB_PORT,
+                                             constants.CF_VNC_PORT,
+                                             constants.CF_ADB_PORT,
                                              "fake_user")
         utils.LaunchVncClient.assert_called_with(11111, "999", "777")
 
@@ -117,8 +117,8 @@
         reconnect.ReconnectInstance(ssh_private_key_path, instance_object)
         utils.AutoConnect.assert_called_with(instance_object.ip,
                                              ssh_private_key_path,
-                                             constants.DEFAULT_GCE_VNC_PORT,
-                                             constants.DEFAULT_GCE_ADB_PORT,
+                                             constants.GCE_VNC_PORT,
+                                             constants.GCE_ADB_PORT,
                                              "fake_user")
 
         #test reconnect remote instance when avd_type as cuttlefish.
@@ -126,8 +126,8 @@
         reconnect.ReconnectInstance(ssh_private_key_path, instance_object)
         utils.AutoConnect.assert_called_with(instance_object.ip,
                                              ssh_private_key_path,
-                                             constants.CF_TARGET_VNC_PORT,
-                                             constants.CF_TARGET_ADB_PORT,
+                                             constants.CF_VNC_PORT,
+                                             constants.CF_ADB_PORT,
                                              "fake_user")
 
     def testStartVnc(self):