def rebase_volume_backing_file(self, req): cmd = jsonobject.loads(req[http.REQUEST_BODY]) rsp = NfsRebaseVolumeBackingFileRsp() if not cmd.dstImageCacheTemplateFolderPath: qcow2s = shell.call("find %s -type f -regex '.*\.qcow2$'" % cmd.dstVolumeFolderPath) else: qcow2s = shell.call( "find %s %s -type f -regex '.*\.qcow2$'" % (cmd.dstVolumeFolderPath, cmd.dstImageCacheTemplateFolderPath)) for qcow2 in qcow2s.split(): fmt = shell.call( "%s %s | grep '^file format' | awk -F ': ' '{ print $2 }'" % (qemu_img.subcmd('info'), qcow2)) if fmt.strip() != "qcow2": continue backing_file = linux.qcow2_get_backing_file(qcow2) if backing_file == "": continue # actions like `create snapshot -> recover snapshot -> delete snapshot` may produce garbage qcow2, whose backing file doesn't exist new_backing_file = backing_file.replace(cmd.srcPsMountPath, cmd.dstPsMountPath) if not os.path.exists(new_backing_file): logger.debug( "the backing file[%s] of volume[%s] doesn't exist, skip rebasing" % (new_backing_file, qcow2)) continue linux.qcow2_rebase_no_check(new_backing_file, qcow2) return jsonobject.dumps(rsp)
def get_image_format(): out = shell.call( '%s %s' % (qemu_img.subcmd('info'), cmd.primaryStorageInstallPath)) for l in out.split('\n'): if 'file format' in l: _, f = l.split(':') return f.strip() raise Exception( 'cannot get image format of %s, qemu-img info outputs:\n%s\n' % (cmd.primaryStorageInstallPath, out))
def heartbeat_file_exists(): touch = shell.ShellCmd( 'timeout %s %s %s' % (cmd.storageCheckerTimeout, qemu_img.subcmd('info'), get_ceph_rbd_args())) touch(False) if touch.return_code == 0: return True logger.warn('cannot query heartbeat image: %s: %s' % (cmd.heartbeatImagePath, touch.stderr)) return False
def download_from_sftp(self, req): cmd = jsonobject.loads(req[http.REQUEST_BODY]) rsp = DownloadBitsFromSftpBackupStorageRsp() sub_vol_dir = os.path.dirname(cmd.primaryStorageInstallPath) if not os.path.exists(sub_vol_dir): parent_dir = os.path.dirname(sub_vol_dir) shell.call('mkdir -p %s' % parent_dir) shell.call('btrfs subvolume create %s' % sub_vol_dir) linux.scp_download(cmd.hostname, cmd.sshKey, cmd.backupStorageInstallPath, cmd.primaryStorageInstallPath) def get_image_format(): out = shell.call( '%s %s' % (qemu_img.subcmd('info'), cmd.primaryStorageInstallPath)) for l in out.split('\n'): if 'file format' in l: _, f = l.split(':') return f.strip() raise Exception( 'cannot get image format of %s, qemu-img info outputs:\n%s\n' % (cmd.primaryStorageInstallPath, out)) f = get_image_format() if 'qcow2' in f: shell.call( '%s -f qcow2 -O raw %s %s.img' % (qemu_img.subcmd('convert'), cmd.primaryStorageInstallPath, cmd.primaryStorageInstallPath)) shell.call( 'mv %s.img %s' % (cmd.primaryStorageInstallPath, cmd.primaryStorageInstallPath)) elif 'raw' in f: pass else: raise Exception('unsupported image format[%s] of %s' % (f, cmd.primaryStorageInstallPath)) rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity() logger.debug('downloaded %s:%s to %s' % (cmd.hostname, cmd.backupStorageInstallPath, cmd.primaryStorageInstallPath)) return jsonobject.dumps(rsp)
def qcow2_convert_to_raw(src, dst): return bash.bash_roe('%s -f qcow2 -O raw %s %s' % (qemu_img.subcmd('convert'), src, dst))
def get_volume_format(path): info = json.loads( bash.bash_o("%s %s --output json" % (qemu_img.subcmd('info'), path))) logger.debug(info) return info["format"]
def download(self, req): rsp = DownloadRsp() def _get_origin_format(path): qcow2_length = 0x9007 if path.startswith('http://') or path.startswith( 'https://') or path.startswith('ftp://'): resp = urllib2.urlopen(path) qhdr = resp.read(qcow2_length) resp.close() elif path.startswith('sftp://'): fd, tmp_file = tempfile.mkstemp() get_header_from_pipe_cmd = "timeout 60 head --bytes=%d %s > %s" % ( qcow2_length, pipe_path, tmp_file) clean_cmd = "pkill -f %s" % pipe_path shell.run( '%s & %s && %s' % (scp_to_pipe_cmd, get_header_from_pipe_cmd, clean_cmd)) qhdr = os.read(fd, qcow2_length) if os.path.exists(tmp_file): os.remove(tmp_file) else: resp = open(path) qhdr = resp.read(qcow2_length) resp.close() if len(qhdr) < qcow2_length: return "raw" return get_image_format_from_buf(qhdr) def get_origin_format(fpath, fail_if_has_backing_file=True): image_format = _get_origin_format(fpath) if image_format == "derivedQcow2" and fail_if_has_backing_file: raise Exception('image has backing file or %s is not exist!' % fpath) return image_format cmd = jsonobject.loads(req[http.REQUEST_BODY]) shell = traceable_shell.get_shell(cmd) pool, image_name = self._parse_install_path(cmd.installPath) tmp_image_name = 'tmp-%s' % image_name @rollbackable def _1(): shell.check_run('rbd rm %s/%s' % (pool, tmp_image_name)) def _getRealSize(length): '''length looks like: 10245K''' logger.debug(length) if not length[-1].isalpha(): return length units = { "g": lambda x: x * 1024 * 1024 * 1024, "m": lambda x: x * 1024 * 1024, "k": lambda x: x * 1024, } try: if not length[-1].isalpha(): return length return units[length[-1].lower()](int(length[:-1])) except: logger.warn(linux.get_exception_stacktrace()) return length # whether we have an upload request if cmd.url.startswith(self.UPLOAD_PROTO): self._prepare_upload(cmd) rsp.size = 0 rsp.uploadPath = self._get_upload_path(req) self._set_capacity_to_response(rsp) return jsonobject.dumps(rsp) if cmd.sendCommandUrl: Report.url = cmd.sendCommandUrl report = Report(cmd.threadContext, cmd.threadContextStack) report.processType = "AddImage" report.resourceUuid = cmd.imageUuid report.progress_report("0", "start") url = urlparse.urlparse(cmd.url) if url.scheme in ('http', 'https', 'ftp'): image_format = get_origin_format(cmd.url, True) cmd.url = linux.shellquote(cmd.url) # roll back tmp ceph file after import it _1() _, PFILE = tempfile.mkstemp() content_length = shell.call( """curl -sLI %s|awk '/[cC]ontent-[lL]ength/{print $NF}'""" % cmd.url).splitlines()[-1] total = _getRealSize(content_length) def _getProgress(synced): last = linux.tail_1(PFILE).strip() if not last or len(last.split( )) < 1 or 'HTTP request sent, awaiting response' in last: return synced logger.debug("last synced: %s" % last) written = _getRealSize(last.split()[0]) if total > 0 and synced < written: synced = written if synced < total: percent = int(round(float(synced) / float(total) * 90)) report.progress_report(percent, "report") return synced logger.debug("content-length is: %s" % total) _, _, err = shell.bash_progress_1( 'set -o pipefail;wget --no-check-certificate -O - %s 2>%s| rbd import --image-format 2 - %s/%s' % (cmd.url, PFILE, pool, tmp_image_name), _getProgress) if err: raise err actual_size = linux.get_file_size_by_http_head(cmd.url) if os.path.exists(PFILE): os.remove(PFILE) elif url.scheme == 'sftp': port = (url.port, 22)[url.port is None] _, PFILE = tempfile.mkstemp() ssh_pswd_file = None pipe_path = PFILE + "fifo" scp_to_pipe_cmd = "scp -P %d -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null %s@%s:%s %s" % ( port, url.username, url.hostname, url.path, pipe_path) sftp_command = "sftp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=no -P %s -b /dev/stdin %s@%s" % ( port, url.username, url.hostname) + " <<EOF\n%s\nEOF\n" if url.password is not None: ssh_pswd_file = linux.write_to_temp_file(url.password) scp_to_pipe_cmd = 'sshpass -f %s %s' % (ssh_pswd_file, scp_to_pipe_cmd) sftp_command = 'sshpass -f %s %s' % (ssh_pswd_file, sftp_command) actual_size = shell.call( sftp_command % ("ls -l " + url.path)).splitlines()[1].strip().split()[4] os.mkfifo(pipe_path) image_format = get_origin_format(cmd.url, True) cmd.url = linux.shellquote(cmd.url) # roll back tmp ceph file after import it _1() def _get_progress(synced): if not os.path.exists(PFILE): return synced last = linux.tail_1(PFILE).strip() if not last or not last.isdigit(): return synced report.progress_report(int(last) * 90 / 100, "report") return synced get_content_from_pipe_cmd = "pv -s %s -n %s 2>%s" % ( actual_size, pipe_path, PFILE) import_from_pipe_cmd = "rbd import --image-format 2 - %s/%s" % ( pool, tmp_image_name) _, _, err = shell.bash_progress_1( 'set -o pipefail; %s & %s | %s' % (scp_to_pipe_cmd, get_content_from_pipe_cmd, import_from_pipe_cmd), _get_progress) if ssh_pswd_file: linux.rm_file_force(ssh_pswd_file) linux.rm_file_force(PFILE) linux.rm_file_force(pipe_path) if err: raise err elif url.scheme == 'file': src_path = cmd.url.lstrip('file:') src_path = os.path.normpath(src_path) if not os.path.isfile(src_path): raise Exception('cannot find the file[%s]' % src_path) image_format = get_origin_format(src_path, True) # roll back tmp ceph file after import it _1() shell.check_run("rbd import --image-format 2 %s %s/%s" % (src_path, pool, tmp_image_name)) actual_size = os.path.getsize(src_path) else: raise Exception('unknown url[%s]' % cmd.url) file_format = shell.call( "set -o pipefail; %s rbd:%s/%s | grep 'file format' | cut -d ':' -f 2" % (qemu_img.subcmd('info'), pool, tmp_image_name)) file_format = file_format.strip() if file_format not in ['qcow2', 'raw']: raise Exception('unknown image format: %s' % file_format) if file_format == 'qcow2': conf_path = None try: with open('/etc/ceph/ceph.conf', 'r') as fd: conf = fd.read() conf = '%s\n%s\n' % (conf, 'rbd default format = 2') conf_path = linux.write_to_temp_file(conf) shell.check_run( '%s -f qcow2 -O rbd rbd:%s/%s rbd:%s/%s:conf=%s' % (qemu_img.subcmd('convert'), pool, tmp_image_name, pool, image_name, conf_path)) shell.check_run('rbd rm %s/%s' % (pool, tmp_image_name)) finally: if conf_path: os.remove(conf_path) else: shell.check_run('rbd mv %s/%s %s/%s' % (pool, tmp_image_name, pool, image_name)) report.progress_report("100", "finish") @rollbackable def _2(): shell.check_run('rbd rm %s/%s' % (pool, image_name)) _2() o = shell.call('rbd --format json info %s/%s' % (pool, image_name)) image_stats = jsonobject.loads(o) rsp.size = long(image_stats.size_) rsp.actualSize = actual_size if image_format == "qcow2": rsp.format = "raw" else: rsp.format = image_format self._set_capacity_to_response(rsp) return jsonobject.dumps(rsp)
def stream_body(task, fpath, entity, boundary): def _progress_consumer(total): task.downloadedSize = total @thread.AsyncThread def _do_import(task, fpath): shell.check_run("cat %s | rbd import --image-format 2 - %s" % (fpath, task.tmpPath)) while True: headers = cherrypy._cpreqbody.Part.read_headers(entity.fp) p = CustomPart(entity.fp, headers, boundary, fpath, _progress_consumer) if not p.filename: continue # start consumer _do_import(task, fpath) try: p.process() except Exception as e: logger.warn('process image %s failed: %s' % (task.imageUuid, str(e))) pass finally: if p.wfd is not None: p.wfd.close() break if task.downloadedSize != task.expectedSize: task.fail('incomplete upload, got %d, expect %d' % (task.downloadedSize, task.expectedSize)) shell.run('rbd rm %s' % task.tmpPath) return file_format = None try: file_format = linux.get_img_fmt('rbd:' + task.tmpPath) except Exception as e: task.fail('upload image %s failed: %s' % (task.imageUuid, str(e))) return if file_format == 'qcow2': if linux.qcow2_get_backing_file('rbd:' + task.tmpPath): task.fail('Qcow2 image %s has backing file' % task.imageUuid) shell.run('rbd rm %s' % task.tmpPath) return conf_path = None try: with open('/etc/ceph/ceph.conf', 'r') as fd: conf = fd.read() conf = '%s\n%s\n' % (conf, 'rbd default format = 2') conf_path = linux.write_to_temp_file(conf) shell.check_run('%s -f qcow2 -O rbd rbd:%s rbd:%s:conf=%s' % (qemu_img.subcmd('convert'), task.tmpPath, task.dstPath, conf_path)) except Exception as e: task.fail('cannot convert Qcow2 image %s to rbd' % task.imageUuid) logger.warn('convert image %s failed: %s', (task.imageUuid, str(e))) return finally: shell.run('rbd rm %s' % task.tmpPath) if conf_path: os.remove(conf_path) else: shell.check_run('rbd mv %s %s' % (task.tmpPath, task.dstPath)) task.success()
def do_sftp_download(self, cmd, pool, image_name): hostname = cmd.hostname prikey = cmd.sshKey port = cmd.sshPort if cmd.bandWidth is not None: bandWidth = 'pv -q -L %s |' % cmd.bandWidth else: bandWidth = '' tmp_image_name = 'tmp-%s' % image_name prikey_file = linux.write_to_temp_file(prikey) @rollbackable def _0(): tpath = "%s/%s" % (pool, tmp_image_name) shell.call('rbd info %s > /dev/null && rbd rm %s' % (tpath, tpath)) _0() def rbd_check_rm(pool, name): if shell.run('rbd info %s/%s' % (pool, name)) == 0: shell.check_run('rbd rm %s/%s' % (pool, name)) try: rbd_check_rm(pool, tmp_image_name) shell.call( self._wrap_shareable_cmd( cmd, 'set -o pipefail; ssh -p %d -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i %s root@%s cat %s | %s rbd import --image-format 2 - %s/%s' % (port, prikey_file, hostname, remote_shell_quote(cmd.backupStorageInstallPath), bandWidth, pool, tmp_image_name))) finally: os.remove(prikey_file) @rollbackable def _1(): shell.call('rbd rm %s/%s' % (pool, tmp_image_name)) _1() file_format = shell.call( "set -o pipefail; %s rbd:%s/%s | grep 'file format' | cut -d ':' -f 2" % (qemu_img.subcmd('info'), pool, tmp_image_name)) file_format = file_format.strip() if file_format not in ['qcow2', 'raw']: raise Exception('unknown image format: %s' % file_format) rbd_check_rm(pool, image_name) if file_format == 'qcow2': conf_path = None try: with open('/etc/ceph/ceph.conf', 'r') as fd: conf = fd.read() conf = '%s\n%s\n' % (conf, 'rbd default format = 2') conf_path = linux.write_to_temp_file(conf) shell.call('%s -f qcow2 -O rbd rbd:%s/%s rbd:%s/%s:conf=%s' % (qemu_img.subcmd('convert'), pool, tmp_image_name, pool, image_name, conf_path)) shell.call('rbd rm %s/%s' % (pool, tmp_image_name)) finally: if conf_path: os.remove(conf_path) else: shell.call('rbd mv %s/%s %s/%s' % (pool, tmp_image_name, pool, image_name))
def _get_qcow2_sizes(self, path): cmd = "%s --output=json '%s'" % (qemu_img.subcmd('info'), path) _, output = commands.getstatusoutput(cmd) return long(json.loads(output)['actual-size']), long(json.loads(output)['virtual-size'])