Exemplo n.º 1
0
    def testIPAddress(self):
        """Test IP class to get ip address."""
        # Internal ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(external="1.1.1.1", internal="10.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH,
            report_internal_ip=True)
        expected_ip = "10.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)

        # External ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(external="1.1.1.1", internal="10.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ip = "1.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)

        # Only one ip case.
        ssh_object = ssh.Ssh(
            ip=ssh.IP(ip="1.1.1.1"),
            user=self.FAKE_SSH_USER,
            ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ip = "1.1.1.1"
        self.assertEqual(ssh_object._ip, expected_ip)
Exemplo n.º 2
0
def _IsWebrtcEnable(instance, host_user, host_ssh_private_key_path,
                    extra_args_ssh_tunnel):
    """Check local/remote instance webRTC is enable.

    Args:
        instance: Local/Remote Instance object.
        host_user: String of user login into the instance.
        host_ssh_private_key_path: String of host key for logging in to the
                                   host.
        extra_args_ssh_tunnel: String, extra args for ssh tunnel connection.

    Returns:
        Boolean: True if cf_runtime_cfg.enable_webrtc is True.
    """
    if instance.islocal:
        return instance.cf_runtime_cfg.enable_webrtc
    ssh = ssh_object.Ssh(ip=ssh_object.IP(ip=instance.ip),
                         user=host_user,
                         ssh_private_key_path=host_ssh_private_key_path,
                         extra_args_ssh_tunnel=extra_args_ssh_tunnel)
    remote_cuttlefish_config = os.path.join(constants.REMOTE_LOG_FOLDER,
                                            constants.CUTTLEFISH_CONFIG_FILE)
    raw_data = ssh.GetCmdOutput("cat " + remote_cuttlefish_config)
    try:
        cf_runtime_cfg = cvd_runtime_config.CvdRuntimeConfig(
            raw_data=raw_data.strip())
        return cf_runtime_cfg.enable_webrtc
    except errors.ConfigError:
        logger.debug("No cuttlefish config[%s] found!",
                     remote_cuttlefish_config)
    return False
Exemplo n.º 3
0
 def testGetBaseCmdWithInternalIP(self):
     """Test get base command with internal ip."""
     ssh_object = ssh.Ssh(
         ip=self.FAKE_IP,
         user=self.FAKE_SSH_USER,
         ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH,
         report_internal_ip=self.FAKE_REPORT_INTERNAL_IP)
     expected_ssh_cmd = (
         "/usr/bin/ssh -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
         "-o StrictHostKeyChecking=no -l fake_user 10.1.1.1")
     self.assertEqual(ssh_object.GetBaseCmd(constants.SSH_BIN),
                      expected_ssh_cmd)
Exemplo n.º 4
0
 def testWaitForSsh(self):
     """Test WaitForSsh."""
     ssh_object = ssh.Ssh(
         ip=self.FAKE_IP,
         user=self.FAKE_SSH_USER,
         ssh_private_key_path=self.FAKE_SSH_PRIVATE_KEY_PATH,
         report_internal_ip=self.FAKE_REPORT_INTERNAL_IP)
     self.Patch(ssh, "_SshCall", return_value=-1)
     self.assertRaises(errors.DeviceConnectionError,
                       ssh_object.WaitForSsh,
                       timeout=1,
                       max_retry=1)
Exemplo n.º 5
0
 def testDisplayLog(self, mock_ssh_run):
     """Test DisplayLog."""
     fake_ip = ssh.IP(external="1.1.1.1", internal="10.1.1.1")
     _ssh = ssh.Ssh(ip=fake_ip,
                    user=constants.GCE_USER,
                    ssh_private_key_path="/fake/acloud_rea")
     self.Patch(utils, "GetUserAnswerYes", return_value="Y")
     log_file = "file1.log"
     pull.DisplayLog(_ssh, log_file)
     expected_cmd = "tail -f -n +1 %s" % log_file
     mock_ssh_run.assert_has_calls(
         [mock.call(expected_cmd, show_output=True)])
    def testUploadArtifacts(self, mock_ssh_run, mock_shell):
        """Test UploadArtifacts."""
        fake_host_package = "/fake/host_package.tar.gz"
        fake_image = "/fake/aosp_cf_x86_phone-img-eng.username.zip"
        fake_local_image_dir = "/fake_image"
        fake_ip = ssh.IP(external="1.1.1.1", internal="10.1.1.1")
        args = mock.MagicMock()
        # Test local image extract from image zip case.
        args.config_file = ""
        args.avd_type = constants.TYPE_CF
        args.flavor = "phone"
        args.local_image = "fake_local_image"
        args.adb_port = None
        avd_spec_local_image = avd_spec.AVDSpec(args)
        factory = remote_instance_cf_device_factory.RemoteInstanceDeviceFactory(
            avd_spec_local_image,
            fake_image,
            fake_host_package)
        factory._ssh = ssh.Ssh(ip=fake_ip,
                               user=constants.GCE_USER,
                               ssh_private_key_path="/fake/acloud_rea")
        factory._UploadArtifacts(fake_image, fake_host_package, fake_local_image_dir)
        expected_cmd1 = ("/usr/bin/install_zip.sh . < %s" % fake_image)
        expected_cmd2 = ("tar -x -z -f - < %s" % fake_host_package)
        mock_ssh_run.assert_has_calls([
            mock.call(expected_cmd1),
            mock.call(expected_cmd2)])

        # Test local image get from local folder case.
        fake_image = None
        self.Patch(glob, "glob", return_value=["fake.img"])
        factory._UploadArtifacts(fake_image, fake_host_package, fake_local_image_dir)
        expected_cmd = (
            "tar -cf - --lzop -S -C %s fake.img | "
            "%s -- tar -xf - --lzop -S" %
            (fake_local_image_dir, factory._ssh.GetBaseCmd(constants.SSH_BIN)))
        mock_shell.assert_called_once_with(expected_cmd)

        mock_shell.reset_mock()
        m = mock.mock_open(read_data = (
            "boot.img\n"
            "cache.img\n"
            "super.img\n"
            "userdata.img\n"
            "vendor_boot.img\n"))
        with mock.patch.object(six.moves.builtins, "open", m):
            factory._UploadArtifacts(fake_image, fake_host_package, fake_local_image_dir)
            expected_cmd = (
                "tar -cf - --lzop -S -C %s boot.img cache.img super.img userdata.img vendor_boot.img | "
                "%s -- tar -xf - --lzop -S" %
                (fake_local_image_dir, factory._ssh.GetBaseCmd(constants.SSH_BIN)))
            mock_shell.assert_called_once_with(expected_cmd)
Exemplo n.º 7
0
    def testCreateInstance(self, mock_shell, mock_create_gce):
        fake_host_package = "/fake/host_package.tar.gz"
        fake_ip = ssh.IP(external="1.1.1.1", internal="10.1.1.1")
        args = mock.MagicMock()
        # Test local image extract from image zip case.
        args.config_file = ""
        args.avd_type = constants.TYPE_FVP
        args.flavor = "phone"
        args.local_image = "fake_local_image"
        args.local_image_dir = "fake_local_image_dir"
        args.adb_port = None
        avd_spec_local_image = avd_spec.AVDSpec(args)
        factory = remote_instance_fvp_device_factory.RemoteInstanceDeviceFactory(
            avd_spec_local_image)
        factory._ssh = ssh.Ssh(ip=fake_ip,
                               user=constants.GCE_USER,
                               ssh_private_key_path="/fake/acloud_rea")
        m = mock.mock_open(read_data=("bl1.bin\n"
                                      "boot.img\n"
                                      "fip.bin\n"
                                      "system-qemu.img\n"
                                      "userdata.img\n"))
        with mock.patch.object(six.moves.builtins, "open", m):
            factory.CreateInstance()

        mock_create_gce.assert_called_once()

        expected_cmds = [
            ("tar -cf - --lzop -S -C /path/to/product/out bl1.bin boot.img "
             "fip.bin system-qemu.img userdata.img | "
             "%s -- tar -xf - --lzop -S" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
            ("tar -cf - --lzop -S -C /path/to/model . | "
             "%s -- tar -xf - --lzop -S" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
            ("%s device/generic/goldfish/fvpbase/run_model_only "
             "[email protected]:run_model_only" %
             factory._ssh.GetBaseCmd(constants.SCP_BIN)),
            ("%s -- mkdir -p lib64" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
            ("%s /path/to/host/out/lib64/bind_to_localhost.so "
             "[email protected]:lib64/bind_to_localhost.so" %
             factory._ssh.GetBaseCmd(constants.SCP_BIN)),
            ("%s -- sh -c \"'ANDROID_HOST_OUT=. ANDROID_PRODUCT_OUT=. "
             "MODEL_BIN=./FVP_Base_RevC-2xAEMv8A "
             "./run_model_only > /dev/null 2> /dev/null &'\"" %
             factory._ssh.GetBaseCmd(constants.SSH_BIN)),
        ]
        mock_shell.assert_has_calls([mock.call(cmd) for cmd in expected_cmds])
Exemplo n.º 8
0
 def testSshRunCmd(self):
     """Test ssh run command."""
     self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
     ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                          self.FAKE_SSH_PRIVATE_KEY_PATH)
     ssh_object.Run("command")
     expected_cmd = (
         "exec /usr/bin/ssh -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
         "-o StrictHostKeyChecking=no -l fake_user 1.1.1.1 command")
     subprocess.Popen.assert_called_with(expected_cmd,
                                         shell=True,
                                         stderr=-2,
                                         stdin=None,
                                         stdout=-1,
                                         universal_newlines=True)
Exemplo n.º 9
0
    def testGetBaseCmd(self):
        """Test get base command."""
        ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                             self.FAKE_SSH_PRIVATE_KEY_PATH)
        expected_ssh_cmd = (
            "/usr/bin/ssh -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no -l fake_user 1.1.1.1")
        self.assertEqual(ssh_object.GetBaseCmd(constants.SSH_BIN),
                         expected_ssh_cmd)

        expected_scp_cmd = (
            "/usr/bin/scp -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
            "-o StrictHostKeyChecking=no")
        self.assertEqual(ssh_object.GetBaseCmd(constants.SCP_BIN),
                         expected_scp_cmd)
Exemplo n.º 10
0
 def testScpPushFileCmd(self):
     """Test scp push file command."""
     self.Patch(subprocess, "Popen", return_value=self.created_subprocess)
     ssh_object = ssh.Ssh(self.FAKE_IP, self.FAKE_SSH_USER,
                          self.FAKE_SSH_PRIVATE_KEY_PATH)
     ssh_object.ScpPushFile("/tmp/test", "/tmp/test_1.log")
     expected_cmd = (
         "exec /usr/bin/scp -i /fake/acloud_rea -q -o UserKnownHostsFile=/dev/null "
         "-o StrictHostKeyChecking=no /tmp/test [email protected]:/tmp/test_1.log"
     )
     subprocess.Popen.assert_called_with(expected_cmd,
                                         shell=True,
                                         stderr=-2,
                                         stdin=None,
                                         stdout=-1,
                                         universal_newlines=True)
    def _InitRemotehost(self):
        """Initialize remote host.

        Determine the remote host instance name, and activate ssh. It need to
        get the IP address in the common_operation. So need to pass the IP and
        ssh to compute_client.

        build_target: The format is like "aosp_cf_x86_phone". We only get info
                      from the user build image file name. If the file name is
                      not custom format (no "-"), we will use $TARGET_PRODUCT
                      from environment variable as build_target.

        Returns:
            A string, representing instance name.
        """
        image_name = os.path.basename(
            self._local_image_artifact) if self._local_image_artifact else ""
        build_target = (os.environ.get(constants.ENV_BUILD_TARGET) if "-" not
                        in image_name else image_name.split("-")[0])
        build_id = self._USER_BUILD
        if self._avd_spec.image_source == constants.IMAGE_SRC_REMOTE:
            build_id = self._avd_spec.remote_image[constants.BUILD_ID]

        instance = "%s-%s-%s-%s" % (constants.INSTANCE_TYPE_HOST,
                                    self._avd_spec.remote_host,
                                    build_id, build_target)
        ip = ssh.IP(ip=self._avd_spec.remote_host)
        self._ssh = ssh.Ssh(
            ip=ip,
            user=self._avd_spec.host_user,
            ssh_private_key_path=(self._avd_spec.host_ssh_private_key_path or
                                  self._cfg.ssh_private_key_path),
            extra_args_ssh_tunnel=self._cfg.extra_args_ssh_tunnel,
            report_internal_ip=self._report_internal_ip)
        self._compute_client.InitRemoteHost(
            self._ssh, ip, self._avd_spec.host_user)
        return instance
Exemplo n.º 12
0
def CleanUpRemoteHost(cfg, remote_host, host_user,
                      host_ssh_private_key_path=None):
    """Clean up the remote host.

    Args:
        cfg: An AcloudConfig instance.
        remote_host : String, ip address or host name of the remote host.
        host_user: String of user login into the instance.
        host_ssh_private_key_path: String of host key for logging in to the
                                   host.

    Returns:
        A Report instance.
    """
    delete_report = report.Report(command="delete")
    credentials = auth.CreateCredentials(cfg)
    compute_client = cvd_compute_client_multi_stage.CvdComputeClient(
        acloud_config=cfg,
        oauth2_credentials=credentials)
    ssh = ssh_object.Ssh(
        ip=ssh_object.IP(ip=remote_host),
        user=host_user,
        ssh_private_key_path=(
            host_ssh_private_key_path or cfg.ssh_private_key_path))
    try:
        compute_client.InitRemoteHost(ssh, remote_host, host_user)
        delete_report.SetStatus(report.Status.SUCCESS)
        device_driver.AddDeletionResultToReport(
            delete_report, [remote_host], failed=[],
            error_msgs=[],
            resource_name="remote host")
    except subprocess.CalledProcessError as e:
        delete_report.AddError(str(e))
        delete_report.SetStatus(report.Status.FAIL)

    return delete_report