def ftp_get_command(connection, remote_path, local_path): """Retrieve a file via FTP :param connection: a Connection object. :param remote_path: path to the remote file :param local_path: path to local destination :raises: PowerVMFileTransferFailed """ try: ftp = ftplib.FTP(host=connection.host, user=connection.username, passwd=connection.password) ftp.cwd(os.path.dirname(remote_path)) name = os.path.basename(remote_path) LOG.debug(_("ftp GET %(remote_path)s to: %(local_path)s"), { 'remote_path': remote_path, 'local_path': local_path }) with open(local_path, 'w') as ftpfile: ftpcmd = 'RETR %s' % name ftp.retrbinary(ftpcmd, ftpfile.write) ftp.close() except Exception: LOG.error(_("File transfer from PowerVM manager failed")) raise exception.PowerVMFTPTransferFailed(ftp_cmd='GET', source_path=remote_path, dest_path=local_path)
def test_copy_image_file_ftp_failed(self): file_path = os.tempnam('/tmp', 'image') remote_path = '/mnt/openstack/images' exp_remote_path = os.path.join(remote_path, os.path.basename(file_path)) exp_cmd = ' '.join(['/usr/bin/rm -f', exp_remote_path]) fake_noop = lambda *args, **kwargs: None fake_op = self.powervm_adapter self.stubs.Set(fake_op, 'run_vios_command', fake_noop) self.stubs.Set(fake_op, '_checksum_local_file', fake_noop) self.mox.StubOutWithMock(common, 'ftp_put_command') self.mox.StubOutWithMock(self.powervm_adapter, 'run_vios_command_as_root') msg_args = { 'ftp_cmd': 'PUT', 'source_path': file_path, 'dest_path': remote_path } exp_exception = exception.PowerVMFTPTransferFailed(**msg_args) common.ftp_put_command(self.connection, file_path, remote_path).AndRaise(exp_exception) self.powervm_adapter.run_vios_command_as_root(exp_cmd).AndReturn([]) self.mox.ReplayAll() self.assertRaises(exception.PowerVMFTPTransferFailed, self.powervm_adapter._copy_image_file, file_path, remote_path)
def ftp_put_command(connection, local_path, remote_dir): """Method to transfer a file via ftp. :param connection: a Connection object. :param local_path: path to the local file :param remote_dir: path to remote destination :raises: PowerVMFileTransferFailed """ try: ftp = ftplib.FTP(host=connection.host, user=connection.username, passwd=connection.password) ftp.cwd(remote_dir) name = os.path.split(local_path)[1] f = open(local_path, "rb") ftp.storbinary("STOR " + name, f) f.close() ftp.close() except Exception: LOG.error(_('File transfer to PowerVM manager failed')) raise exception.PowerVMFTPTransferFailed(ftp_cmd='PUT', source_path=local_path, dest_path=remote_dir)