mrc0mmand / rpms / libguestfs

Forked from rpms/libguestfs 3 years ago
Clone

Blame SOURCES/0012-v2v-Add-o-rhv-upload-output-mode-RHBZ-1557273.patch

df3bb2
From 79aa92b800800592551f1389db0a059b3f111f33 Mon Sep 17 00:00:00 2001
df3bb2
From: "Richard W.M. Jones" <rjones@redhat.com>
df3bb2
Date: Mon, 12 Feb 2018 16:45:02 +0000
df3bb2
Subject: [PATCH] v2v: Add -o rhv-upload output mode (RHBZ#1557273).
df3bb2
MIME-Version: 1.0
df3bb2
Content-Type: text/plain; charset=UTF-8
df3bb2
Content-Transfer-Encoding: 8bit
df3bb2
df3bb2
This adds a new output mode to virt-v2v.  virt-v2v -o rhv-upload
df3bb2
streams images directly to an oVirt or RHV >= 4 Data Domain using the
df3bb2
oVirt SDK v4.  It is more efficient than -o rhv because it does not
df3bb2
need to go via the Export Storage Domain, and is possible for humans
df3bb2
to use unlike -o vdsm.
df3bb2
df3bb2
The implementation uses the Python SDK (‘ovirtsdk4’ module).  An
df3bb2
nbdkit Python 3 plugin translates NBD calls from qemu into HTTPS
df3bb2
requests to oVirt via the SDK.
df3bb2
df3bb2
(cherry picked from commit cc04573927cca97de60d544d37467e67c25867a7)
df3bb2
---
df3bb2
 .gitignore                                |   3 +
df3bb2
 TODO                                      |  27 ++
df3bb2
 v2v/Makefile.am                           |  30 +-
df3bb2
 v2v/cmdline.ml                            |  41 ++
df3bb2
 v2v/embed.sh                              |  48 +++
df3bb2
 v2v/output_rhv_upload.ml                  | 401 +++++++++++++++++++
df3bb2
 v2v/output_rhv_upload.mli                 |  33 ++
df3bb2
 v2v/output_rhv_upload_createvm_source.mli |  19 +
df3bb2
 v2v/output_rhv_upload_plugin_source.mli   |  19 +
df3bb2
 v2v/output_rhv_upload_precheck_source.mli |  19 +
df3bb2
 v2v/rhv-upload-createvm.py                |  86 +++++
df3bb2
 v2v/rhv-upload-plugin.py                  | 445 ++++++++++++++++++++++
df3bb2
 v2v/rhv-upload-precheck.py                |  73 ++++
df3bb2
 v2v/test-v2v-o-rhv-upload-oo-query.sh     |  38 ++
df3bb2
 v2v/test-v2v-python-syntax.sh             |  45 +++
df3bb2
 v2v/virt-v2v.pod                          | 138 ++++++-
df3bb2
 16 files changed, 1447 insertions(+), 18 deletions(-)
df3bb2
 create mode 100755 v2v/embed.sh
df3bb2
 create mode 100644 v2v/output_rhv_upload.ml
df3bb2
 create mode 100644 v2v/output_rhv_upload.mli
df3bb2
 create mode 100644 v2v/output_rhv_upload_createvm_source.mli
df3bb2
 create mode 100644 v2v/output_rhv_upload_plugin_source.mli
df3bb2
 create mode 100644 v2v/output_rhv_upload_precheck_source.mli
df3bb2
 create mode 100644 v2v/rhv-upload-createvm.py
df3bb2
 create mode 100644 v2v/rhv-upload-plugin.py
df3bb2
 create mode 100644 v2v/rhv-upload-precheck.py
df3bb2
 create mode 100755 v2v/test-v2v-o-rhv-upload-oo-query.sh
df3bb2
 create mode 100755 v2v/test-v2v-python-syntax.sh
df3bb2
df3bb2
diff --git a/.gitignore b/.gitignore
df3bb2
index 8101a2d9b..af80e36d1 100644
df3bb2
--- a/.gitignore
df3bb2
+++ b/.gitignore
df3bb2
@@ -672,6 +672,9 @@ Makefile.in
df3bb2
 /utils/qemu-speed-test/qemu-speed-test
df3bb2
 /v2v/.depend
df3bb2
 /v2v/oUnit-*
df3bb2
+/v2v/output_rhv_upload_createvm_source.ml
df3bb2
+/v2v/output_rhv_upload_plugin_source.ml
df3bb2
+/v2v/output_rhv_upload_precheck_source.ml
df3bb2
 /v2v/real-*.d/
df3bb2
 /v2v/real-*.img
df3bb2
 /v2v/real-*.xml
df3bb2
diff --git a/TODO b/TODO
df3bb2
index 2e37ce67c..d196a3f6b 100644
df3bb2
--- a/TODO
df3bb2
+++ b/TODO
df3bb2
@@ -570,3 +570,30 @@ Subsecond handling in virt-diff, virt-ls
df3bb2
 
df3bb2
 Handle nanoseconds properly.  You should be able to specify them on
df3bb2
 the command line and display them.
df3bb2
+
df3bb2
+virt-v2v -o rhv-upload
df3bb2
+----------------------
df3bb2
+
df3bb2
+* Set or disable the ticket timeout.  The default is going to be
df3bb2
+  increased (from current 60 seconds), so maybe we won't have to
df3bb2
+  set it.  See also:
df3bb2
+  https://bugzilla.redhat.com/show_bug.cgi?id=1563278
df3bb2
+
df3bb2
+* qcow2 cannot be supported yet because there is not yet any
df3bb2
+  concept in imageio of read+write handles.
df3bb2
+  https://bugzilla.redhat.com/show_bug.cgi?id=1563299
df3bb2
+
df3bb2
+* preallocated cannot be supported yet because imageio doesn't
df3bb2
+  know how to zero the image efficiently, instead it runs an
df3bb2
+  fallocate process which writes to every block and that takes
df3bb2
+  many minutes.
df3bb2
+
df3bb2
+* Really check what insecure/rhv_cafile do and implement it correctly.
df3bb2
+
df3bb2
+* Measure and resolve performance problems.
df3bb2
+
df3bb2
+* Allocated image size is unknown for v2v uploads, but imageio needs
df3bb2
+  to know it.  We pass initial_size == provisioned_size == virtual size.
df3bb2
+  That can't be fixed from the v2v side.
df3bb2
+
df3bb2
+* There are unresolved issues about how to clean up disks on failure.
df3bb2
diff --git a/v2v/Makefile.am b/v2v/Makefile.am
df3bb2
index 482ba58e5..694a64573 100644
df3bb2
--- a/v2v/Makefile.am
df3bb2
+++ b/v2v/Makefile.am
df3bb2
@@ -22,12 +22,19 @@ generator_built = \
df3bb2
 	uefi.mli
df3bb2
 
df3bb2
 BUILT_SOURCES = \
df3bb2
-	$(generator_built)
df3bb2
+	$(generator_built) \
df3bb2
+	output_rhv_upload_createvm_source.ml \
df3bb2
+	output_rhv_upload_plugin_source.ml \
df3bb2
+	output_rhv_upload_precheck_source.ml
df3bb2
 
df3bb2
 EXTRA_DIST = \
df3bb2
 	$(SOURCES_MLI) $(SOURCES_ML) $(SOURCES_C) \
df3bb2
 	copy_to_local.ml \
df3bb2
 	copy_to_local.mli \
df3bb2
+	embed-code.sh \
df3bb2
+	rhv-upload-createvm.py \
df3bb2
+	rhv-upload-plugin.py \
df3bb2
+	rhv-upload-precheck.py \
df3bb2
 	v2v_unit_tests.ml \
df3bb2
 	virt-v2v.pod \
df3bb2
 	virt-v2v-copy-to-local.pod
df3bb2
@@ -62,6 +69,10 @@ SOURCES_MLI = \
df3bb2
 	output_null.mli \
df3bb2
 	output_qemu.mli \
df3bb2
 	output_rhv.mli \
df3bb2
+	output_rhv_upload.mli \
df3bb2
+	output_rhv_upload_createvm_source.mli \
df3bb2
+	output_rhv_upload_plugin_source.mli \
df3bb2
+	output_rhv_upload_precheck_source.mli \
df3bb2
 	output_vdsm.mli \
df3bb2
 	parse_ova.mli \
df3bb2
 	parse_ovf_from_ova.mli \
df3bb2
@@ -116,6 +127,10 @@ SOURCES_ML = \
df3bb2
 	output_local.ml \
df3bb2
 	output_qemu.ml \
df3bb2
 	output_rhv.ml \
df3bb2
+	output_rhv_upload_createvm_source.ml \
df3bb2
+	output_rhv_upload_plugin_source.ml \
df3bb2
+	output_rhv_upload_precheck_source.ml \
df3bb2
+	output_rhv_upload.ml \
df3bb2
 	output_vdsm.ml \
df3bb2
 	inspect_source.ml \
df3bb2
 	target_bus_assignment.ml \
df3bb2
@@ -126,6 +141,15 @@ SOURCES_C = \
df3bb2
 	libvirt_utils-c.c \
df3bb2
 	qemuopts-c.c
df3bb2
 
df3bb2
+# These files are generated and contain rhv-upload-*.py embedded as an
df3bb2
+# OCaml string.
df3bb2
+output_rhv_upload_createvm_source.ml: rhv-upload-createvm.py
df3bb2
+	./embed.sh code $^ $@
df3bb2
+output_rhv_upload_plugin_source.ml: rhv-upload-plugin.py
df3bb2
+	./embed.sh code $^ $@
df3bb2
+output_rhv_upload_precheck_source.ml: rhv-upload-precheck.py
df3bb2
+	./embed.sh code $^ $@
df3bb2
+
df3bb2
 if HAVE_OCAML
df3bb2
 
df3bb2
 bin_PROGRAMS = virt-v2v virt-v2v-copy-to-local
df3bb2
@@ -295,6 +319,7 @@ TESTS_ENVIRONMENT = $(top_builddir)/run --test
df3bb2
 
df3bb2
 TESTS = \
df3bb2
 	test-v2v-docs.sh \
df3bb2
+	test-v2v-python-syntax.sh \
df3bb2
 	test-v2v-i-ova-bad-sha1.sh \
df3bb2
 	test-v2v-i-ova-bad-sha256.sh \
df3bb2
 	test-v2v-i-ova-formats.sh \
df3bb2
@@ -308,6 +333,7 @@ TESTS = \
df3bb2
 	test-v2v-i-ova-two-disks.sh \
df3bb2
 	test-v2v-i-vmx.sh \
df3bb2
 	test-v2v-it-vddk-io-query.sh \
df3bb2
+	test-v2v-o-rhv-upload-oo-query.sh \
df3bb2
 	test-v2v-o-vdsm-oo-query.sh \
df3bb2
 	test-v2v-bad-networks-and-bridges.sh
df3bb2
 
df3bb2
@@ -483,6 +509,7 @@ EXTRA_DIST += \
df3bb2
 	test-v2v-o-null.sh \
df3bb2
 	test-v2v-o-qemu.sh \
df3bb2
 	test-v2v-o-rhv.sh \
df3bb2
+	test-v2v-o-rhv-upload-oo-query.sh \
df3bb2
 	test-v2v-o-vdsm-oo-query.sh \
df3bb2
 	test-v2v-o-vdsm-options.sh \
df3bb2
 	test-v2v-oa-option.sh \
df3bb2
@@ -491,6 +518,7 @@ EXTRA_DIST += \
df3bb2
 	test-v2v-print-source.expected \
df3bb2
 	test-v2v-print-source.sh \
df3bb2
 	test-v2v-print-source.xml \
df3bb2
+	test-v2v-python-syntax.sh \
df3bb2
 	test-v2v-conversion-of.sh \
df3bb2
 	test-v2v-sound.sh \
df3bb2
 	test-v2v-sound.xml \
df3bb2
diff --git a/v2v/cmdline.ml b/v2v/cmdline.ml
df3bb2
index 5b8f686a8..9b1348c37 100644
df3bb2
--- a/v2v/cmdline.ml
df3bb2
+++ b/v2v/cmdline.ml
df3bb2
@@ -133,6 +133,8 @@ let parse_cmdline () =
df3bb2
     | "disk" | "local" -> output_mode := `Local
df3bb2
     | "null" -> output_mode := `Null
df3bb2
     | "ovirt" | "rhv" | "rhev" -> output_mode := `RHV
df3bb2
+    | "ovirt-upload" | "ovirt_upload" | "rhv-upload" | "rhv_upload" ->
df3bb2
+       output_mode := `RHV_Upload
df3bb2
     | "qemu" -> output_mode := `QEmu
df3bb2
     | "vdsm" -> output_mode := `VDSM
df3bb2
     | s ->
df3bb2
@@ -392,6 +394,16 @@ read the man page virt-v2v(1).
df3bb2
     | `Null -> no_options (); `Null
df3bb2
     | `RHV -> no_options (); `RHV
df3bb2
     | `QEmu -> no_options (); `QEmu
df3bb2
+    | `RHV_Upload ->
df3bb2
+       if is_query then (
df3bb2
+         Output_rhv_upload.print_output_options ();
df3bb2
+         exit 0
df3bb2
+       )
df3bb2
+       else (
df3bb2
+         let rhv_options =
df3bb2
+           Output_rhv_upload.parse_output_options output_options in
df3bb2
+         `RHV_Upload rhv_options
df3bb2
+       )
df3bb2
     | `VDSM ->
df3bb2
        if is_query then (
df3bb2
          Output_vdsm.print_output_options ();
df3bb2
@@ -568,6 +580,35 @@ read the man page virt-v2v(1).
df3bb2
       Output_rhv.output_rhv os output_alloc,
df3bb2
       output_format, output_alloc
df3bb2
 
df3bb2
+    | `RHV_Upload rhv_options ->
df3bb2
+      let output_conn =
df3bb2
+        match output_conn with
df3bb2
+        | None ->
df3bb2
+           error (f_"-o rhv-upload: use ‘-oc’ to point to the oVirt or RHV server REST API URL, which is usually https://servername/ovirt-engine/api")
df3bb2
+        | Some oc -> oc in
df3bb2
+      (* Output format / sparse must currently be raw+sparse.  We can
df3bb2
+       * change this in future.  See TODO file for details. XXX
df3bb2
+       *)
df3bb2
+      if output_alloc <> Sparse || output_format <> Some "raw" then
df3bb2
+        error (f_"-o rhv-upload: currently you must use ‘-of raw’ and you cannot use ‘-oa preallocated’ with this output mode.  These restrictions will be loosened in a future version.");
df3bb2
+      (* In theory we could make the password optional in future. *)
df3bb2
+      let output_password =
df3bb2
+        match output_password with
df3bb2
+        | None ->
df3bb2
+           error (f_"-o rhv-upload: output password file was not specified, use ‘-op’ to point to a file which contains the password used to connect to the oVirt or RHV server")
df3bb2
+        | Some op -> op in
df3bb2
+      let os =
df3bb2
+        match output_storage with
df3bb2
+        | None ->
df3bb2
+           error (f_"-o rhv-upload: output storage was not specified, use ‘-os’");
df3bb2
+        | Some os -> os in
df3bb2
+      if qemu_boot then
df3bb2
+        error_option_cannot_be_used_in_output_mode "rhv-upload" "--qemu-boot";
df3bb2
+      Output_rhv_upload.output_rhv_upload output_alloc output_conn
df3bb2
+                                          output_password os
df3bb2
+                                          rhv_options,
df3bb2
+      output_format, output_alloc
df3bb2
+
df3bb2
     | `VDSM vdsm_options ->
df3bb2
       if output_password <> None then
df3bb2
         error_option_cannot_be_used_in_output_mode "vdsm" "-op";
df3bb2
diff --git a/v2v/embed.sh b/v2v/embed.sh
df3bb2
new file mode 100755
df3bb2
index 000000000..363d7e2b0
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/embed.sh
df3bb2
@@ -0,0 +1,48 @@
df3bb2
+#!/bin/bash -
df3bb2
+# Embed code or other content into an OCaml file.
df3bb2
+# Copyright (C) 2018 Red Hat Inc.
df3bb2
+#
df3bb2
+# This program is free software; you can redistribute it and/or modify
df3bb2
+# it under the terms of the GNU General Public License as published by
df3bb2
+# the Free Software Foundation; either version 2 of the License, or
df3bb2
+# (at your option) any later version.
df3bb2
+#
df3bb2
+# This program is distributed in the hope that it will be useful,
df3bb2
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+# GNU General Public License for more details.
df3bb2
+#
df3bb2
+# You should have received a copy of the GNU General Public License
df3bb2
+# along with this program; if not, write to the Free Software
df3bb2
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+
df3bb2
+# Embed code or other content into an OCaml file.
df3bb2
+#
df3bb2
+# It is embedded into a string.  As OCaml string literals have virtually
df3bb2
+# no restrictions on length or content we only have to escape double
df3bb2
+# quotes for backslash characters.
df3bb2
+
df3bb2
+if [ $# -ne 3 ]; then
df3bb2
+    echo "embed.sh identifier input output"
df3bb2
+    exit 1
df3bb2
+fi
df3bb2
+
df3bb2
+set -e
df3bb2
+set -u
df3bb2
+
df3bb2
+ident="$1"
df3bb2
+input="$2"
df3bb2
+output="$3"
df3bb2
+
df3bb2
+rm -f "$output" "$output"-t
df3bb2
+
df3bb2
+exec >"$output"-t
df3bb2
+
df3bb2
+echo "(* Generated by embed.sh from $input *)"
df3bb2
+echo
df3bb2
+echo let "$ident" = '"'
df3bb2
+sed -e 's/\(["\]\)/\\\1/g' < "$input"
df3bb2
+echo '"'
df3bb2
+
df3bb2
+chmod -w "$output"-t
df3bb2
+mv "$output"-t "$output"
df3bb2
diff --git a/v2v/output_rhv_upload.ml b/v2v/output_rhv_upload.ml
df3bb2
new file mode 100644
df3bb2
index 000000000..129461242
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/output_rhv_upload.ml
df3bb2
@@ -0,0 +1,401 @@
df3bb2
+(* virt-v2v
df3bb2
+ * Copyright (C) 2009-2018 Red Hat Inc.
df3bb2
+ *
df3bb2
+ * This program is free software; you can redistribute it and/or modify
df3bb2
+ * it under the terms of the GNU General Public License as published by
df3bb2
+ * the Free Software Foundation; either version 2 of the License, or
df3bb2
+ * (at your option) any later version.
df3bb2
+ *
df3bb2
+ * This program is distributed in the hope that it will be useful,
df3bb2
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+ * GNU General Public License for more details.
df3bb2
+ *
df3bb2
+ * You should have received a copy of the GNU General Public License along
df3bb2
+ * with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+ *)
df3bb2
+
df3bb2
+open Printf
df3bb2
+open Unix
df3bb2
+
df3bb2
+open Std_utils
df3bb2
+open Tools_utils
df3bb2
+open Unix_utils
df3bb2
+open Common_gettext.Gettext
df3bb2
+
df3bb2
+open Types
df3bb2
+open Utils
df3bb2
+
df3bb2
+type rhv_options = {
df3bb2
+  rhv_cafile : string;
df3bb2
+  rhv_cluster : string option;
df3bb2
+  rhv_direct : bool;
df3bb2
+  rhv_verifypeer : bool;
df3bb2
+}
df3bb2
+
df3bb2
+let print_output_options () =
df3bb2
+  printf (f_"Output options (-oo) which can be used with -o rhv-upload:
df3bb2
+
df3bb2
+  -oo rhv-cafile=CA.PEM           Set ‘ca.pem’ certificate bundle filename.
df3bb2
+  -oo rhv-cluster=CLUSTERNAME     Set RHV cluster name.
df3bb2
+  -oo rhv-direct[=true|false]     Use direct transfer mode (default: false).
df3bb2
+  -oo rhv-verifypeer[=true|false] Verify server identity (default: false).
df3bb2
+")
df3bb2
+
df3bb2
+let parse_output_options options =
df3bb2
+  let rhv_cafile = ref None in
df3bb2
+  let rhv_cluster = ref None in
df3bb2
+  let rhv_direct = ref false in
df3bb2
+  let rhv_verifypeer = ref false in
df3bb2
+
df3bb2
+  List.iter (
df3bb2
+    function
df3bb2
+    | "rhv-cafile", v ->
df3bb2
+       if !rhv_cafile <> None then
df3bb2
+         error (f_"-o rhv-upload: -oo rhv-cafile set twice");
df3bb2
+       rhv_cafile := Some v
df3bb2
+    | "rhv-cluster", v ->
df3bb2
+       if !rhv_cluster <> None then
df3bb2
+         error (f_"-o rhv-upload: -oo rhv-cluster set twice");
df3bb2
+       rhv_cluster := Some v
df3bb2
+    | "rhv-direct", "" -> rhv_direct := true
df3bb2
+    | "rhv-direct", v -> rhv_direct := bool_of_string v
df3bb2
+    | "rhv-verifypeer", "" -> rhv_verifypeer := true
df3bb2
+    | "rhv-verifypeer", v -> rhv_verifypeer := bool_of_string v
df3bb2
+    | k, _ ->
df3bb2
+       error (f_"-o rhv-upload: unknown output option ‘-oo %s’") k
df3bb2
+  ) options;
df3bb2
+
df3bb2
+  let rhv_cafile =
df3bb2
+    match !rhv_cafile with
df3bb2
+    | Some s -> s
df3bb2
+    | None ->
df3bb2
+       error (f_"-o rhv-upload: must use ‘-oo rhv-cafile’ to supply the path to the oVirt or RHV user’s ‘ca.pem’ file") in
df3bb2
+  let rhv_cluster = !rhv_cluster in
df3bb2
+  let rhv_direct = !rhv_direct in
df3bb2
+  let rhv_verifypeer = !rhv_verifypeer in
df3bb2
+
df3bb2
+  { rhv_cafile; rhv_cluster; rhv_direct; rhv_verifypeer }
df3bb2
+
df3bb2
+let python3 = "python3" (* Defined by PEP 394 *)
df3bb2
+let pidfile_timeout = 30
df3bb2
+let finalization_timeout = 5*60
df3bb2
+
df3bb2
+class output_rhv_upload output_alloc output_conn
df3bb2
+                        output_password output_storage
df3bb2
+                        rhv_options =
df3bb2
+  (* Create a temporary directory which will be deleted on exit. *)
df3bb2
+  let tmpdir =
df3bb2
+    let base_dir = (open_guestfs ())#get_cachedir () in
df3bb2
+    let t = Mkdtemp.temp_dir ~base_dir "rhvupload." in
df3bb2
+    rmdir_on_exit t;
df3bb2
+    t in
df3bb2
+
df3bb2
+  let diskid_file_of_id id = tmpdir // sprintf "diskid.%d" id in
df3bb2
+
df3bb2
+  (* Write the Python precheck, plugin and create VM to a temporary file. *)
df3bb2
+  let precheck =
df3bb2
+    let precheck = tmpdir // "rhv-upload-precheck.py" in
df3bb2
+    with_open_out
df3bb2
+      precheck
df3bb2
+      (fun chan -> output_string chan Output_rhv_upload_precheck_source.code);
df3bb2
+    precheck in
df3bb2
+  let plugin =
df3bb2
+    let plugin = tmpdir // "rhv-upload-plugin.py" in
df3bb2
+    with_open_out
df3bb2
+      plugin
df3bb2
+      (fun chan -> output_string chan Output_rhv_upload_plugin_source.code);
df3bb2
+    plugin in
df3bb2
+  let createvm =
df3bb2
+    let createvm = tmpdir // "rhv-upload-createvm.py" in
df3bb2
+    with_open_out
df3bb2
+      createvm
df3bb2
+      (fun chan -> output_string chan Output_rhv_upload_createvm_source.code);
df3bb2
+    createvm in
df3bb2
+
df3bb2
+  (* Is SELinux enabled and enforcing on the host? *)
df3bb2
+  let have_selinux =
df3bb2
+    0 = Sys.command "getenforce 2>/dev/null | grep -isq Enforcing" in
df3bb2
+
df3bb2
+  (* Check that the Python binary is available. *)
df3bb2
+  let error_unless_python_binary_on_path () =
df3bb2
+    try ignore (which python3)
df3bb2
+    with Executable_not_found _ ->
df3bb2
+      error (f_"no python binary called ‘%s’ can be found on the $PATH")
df3bb2
+            python3
df3bb2
+  in
df3bb2
+
df3bb2
+  (* Check that nbdkit is available and new enough. *)
df3bb2
+  let error_unless_nbdkit_working () =
df3bb2
+    if 0 <> Sys.command "nbdkit --version >/dev/null" then
df3bb2
+      error (f_"nbdkit is not installed or not working.  It is required to use ‘-o rhv-upload’.  See \"OUTPUT TO RHV\" in the virt-v2v(1) manual.");
df3bb2
+
df3bb2
+    (* Check it's a new enough version.  The latest features we
df3bb2
+     * require are ‘--exit-with-parent’ and ‘--selinux-label’, both
df3bb2
+     * added in 1.1.14.  (We use 1.1.16 as the minimum here because
df3bb2
+     * it also adds the selinux=yes|no flag in --dump-config).
df3bb2
+     *)
df3bb2
+    let lines = external_command "nbdkit --help" in
df3bb2
+    let lines = String.concat " " lines in
df3bb2
+    if String.find lines "exit-with-parent" == -1 ||
df3bb2
+       String.find lines "selinux-label" == -1 then
df3bb2
+      error (f_"nbdkit is not new enough, you need to upgrade to nbdkit ≥ 1.1.16")
df3bb2
+  in
df3bb2
+
df3bb2
+  (* Check that the python3 plugin is installed and working
df3bb2
+   * and can load the plugin script.
df3bb2
+   *)
df3bb2
+  let error_unless_nbdkit_python3_working () =
df3bb2
+    let cmd = sprintf "nbdkit %s %s --dump-plugin >/dev/null"
df3bb2
+                      python3 (quote plugin) in
df3bb2
+    if Sys.command cmd <> 0 then
df3bb2
+      error (f_"nbdkit Python 3 plugin is not installed or not working.  It is required if you want to use ‘-o rhv-upload’.
df3bb2
+
df3bb2
+See also \"OUTPUT TO RHV\" in the virt-v2v(1) manual.")
df3bb2
+  in
df3bb2
+
df3bb2
+  (* Check that nbdkit was compiled with SELinux support (for the
df3bb2
+   * --selinux-label option).
df3bb2
+   *)
df3bb2
+  let error_unless_nbdkit_compiled_with_selinux () =
df3bb2
+    let lines = external_command "nbdkit --dump-config" in
df3bb2
+    (* In nbdkit <= 1.1.15 the selinux attribute was not present
df3bb2
+     * at all in --dump-config output so there was no way to tell.
df3bb2
+     * Ignore this case because there will be an error later when
df3bb2
+     * we try to use the --selinux-label parameter.
df3bb2
+     *)
df3bb2
+    if List.mem "selinux=no" (List.map String.trim lines) then
df3bb2
+      error (f_"nbdkit was compiled without SELinux support.  You will have to recompile nbdkit with libselinux-devel installed, or else set SELinux to Permissive mode while doing the conversion.")
df3bb2
+  in
df3bb2
+
df3bb2
+  (* JSON parameters which are invariant between disks. *)
df3bb2
+  let json_params = [
df3bb2
+    "verbose", JSON.Bool (verbose ());
df3bb2
+
df3bb2
+    "output_conn", JSON.String output_conn;
df3bb2
+    "output_password", JSON.String output_password;
df3bb2
+    "output_storage", JSON.String output_storage;
df3bb2
+    "output_sparse", JSON.Bool (match output_alloc with
df3bb2
+                                | Sparse -> true
df3bb2
+                                | Preallocated -> false);
df3bb2
+    "rhv_cafile", JSON.String rhv_options.rhv_cafile;
df3bb2
+    "rhv_cluster",
df3bb2
+      JSON.String (Option.default "Default" rhv_options.rhv_cluster);
df3bb2
+    "rhv_direct", JSON.Bool rhv_options.rhv_direct;
df3bb2
+
df3bb2
+    (* The 'Insecure' flag seems to be a number with various possible
df3bb2
+     * meanings, however we just set it to True/False.
df3bb2
+     *
df3bb2
+     * https://github.com/oVirt/ovirt-engine-sdk/blob/19aa7070b80e60a4cfd910448287aecf9083acbe/sdk/lib/ovirtsdk4/__init__.py#L395
df3bb2
+     *)
df3bb2
+    "insecure", JSON.Bool (not rhv_options.rhv_verifypeer);
df3bb2
+  ] in
df3bb2
+
df3bb2
+  (* nbdkit command line args which are invariant between disks. *)
df3bb2
+  let nbdkit_args =
df3bb2
+    let args = [
df3bb2
+      "nbdkit";
df3bb2
+
df3bb2
+      "--foreground";           (* run in foreground *)
df3bb2
+      "--exit-with-parent";     (* exit when virt-v2v exits *)
df3bb2
+      "--newstyle";             (* use newstyle NBD protocol *)
df3bb2
+      "--exportname"; "/";
df3bb2
+
df3bb2
+      "python3";                (* use the nbdkit Python 3 plugin *)
df3bb2
+      plugin;                   (* Python plugin script *)
df3bb2
+    ] in
df3bb2
+    let args = if verbose () then args @ ["--verbose"] else args in
df3bb2
+    let args =
df3bb2
+      (* label the socket so qemu can open it *)
df3bb2
+      if have_selinux then
df3bb2
+        args @ ["--selinux-label"; "system_u:object_r:svirt_t:s0"]
df3bb2
+      else args in
df3bb2
+    args in
df3bb2
+
df3bb2
+object
df3bb2
+  inherit output
df3bb2
+
df3bb2
+  method precheck () =
df3bb2
+    error_unless_python_binary_on_path ();
df3bb2
+    error_unless_nbdkit_working ();
df3bb2
+    error_unless_nbdkit_python3_working ();
df3bb2
+    if have_selinux then
df3bb2
+      error_unless_nbdkit_compiled_with_selinux ()
df3bb2
+
df3bb2
+  method as_options =
df3bb2
+    "-o rhv-upload" ^
df3bb2
+    (match output_alloc with
df3bb2
+     | Sparse -> "" (* default, don't need to print it *)
df3bb2
+     | Preallocated -> " -oa preallocated") ^
df3bb2
+    sprintf " -oc %s -op %s -os %s"
df3bb2
+            output_conn output_password output_storage
df3bb2
+
df3bb2
+  method supported_firmware = [ TargetBIOS ]
df3bb2
+
df3bb2
+  method prepare_targets source targets =
df3bb2
+    let output_name = source.s_name in
df3bb2
+    let json_params =
df3bb2
+      ("output_name", JSON.String output_name) :: json_params in
df3bb2
+
df3bb2
+    (* Python code prechecks.  These can't run in #precheck because
df3bb2
+     * we need to know the name of the virtual machine.
df3bb2
+     *)
df3bb2
+    let json_param_file = tmpdir // "params.json" in
df3bb2
+    with_open_out
df3bb2
+      json_param_file
df3bb2
+      (fun chan -> output_string chan (JSON.string_of_doc json_params));
df3bb2
+    if run_command [ python3; precheck; json_param_file ] <> 0 then
df3bb2
+      error (f_"failed server prechecks, see earlier errors");
df3bb2
+
df3bb2
+    (* Create an nbdkit instance for each disk and set the
df3bb2
+     * target URI to point to the NBD socket.
df3bb2
+     *)
df3bb2
+    List.map (
df3bb2
+      fun t ->
df3bb2
+        let id = t.target_overlay.ov_source.s_disk_id in
df3bb2
+        let disk_name = sprintf "%s-%03d" output_name id in
df3bb2
+        let json_params =
df3bb2
+          ("disk_name", JSON.String disk_name) :: json_params in
df3bb2
+
df3bb2
+        let disk_format =
df3bb2
+          match t.target_format with
df3bb2
+          | ("raw" | "qcow2") as fmt -> fmt
df3bb2
+          | _ ->
df3bb2
+             error (f_"rhv-upload: -of %s: Only output format ‘raw’ or ‘qcow2’ is supported.  If the input is in a different format then force one of these output formats by adding either ‘-of raw’ or ‘-of qcow2’ on the command line.")
df3bb2
+                   t.target_format in
df3bb2
+        let json_params =
df3bb2
+          ("disk_format", JSON.String disk_format) :: json_params in
df3bb2
+
df3bb2
+        let disk_size = t.target_overlay.ov_virtual_size in
df3bb2
+        let json_params =
df3bb2
+          ("disk_size", JSON.Int64 disk_size) :: json_params in
df3bb2
+
df3bb2
+        (* Ask the plugin to write the disk ID to a special file. *)
df3bb2
+        let diskid_file = diskid_file_of_id id in
df3bb2
+        let json_params =
df3bb2
+          ("diskid_file", JSON.String diskid_file) :: json_params in
df3bb2
+
df3bb2
+        (* Write the JSON parameters to a file. *)
df3bb2
+        let json_param_file = tmpdir // sprintf "params%d.json" id in
df3bb2
+        with_open_out
df3bb2
+          json_param_file
df3bb2
+          (fun chan -> output_string chan (JSON.string_of_doc json_params));
df3bb2
+
df3bb2
+        let sock = tmpdir // sprintf "nbdkit%d.sock" id in
df3bb2
+        let pidfile = tmpdir // sprintf "nbdkit%d.pid" id in
df3bb2
+
df3bb2
+        (* Add common arguments to per-target arguments. *)
df3bb2
+        let args =
df3bb2
+          nbdkit_args @ [ "--pidfile"; pidfile;
df3bb2
+                          "--unix"; sock;
df3bb2
+                          sprintf "params=%s" json_param_file ] in
df3bb2
+
df3bb2
+        (* Print the full command we are about to run when debugging. *)
df3bb2
+        if verbose () then (
df3bb2
+          eprintf "running nbdkit:\n";
df3bb2
+          List.iter (fun arg -> eprintf " %s" (quote arg)) args;
df3bb2
+          prerr_newline ()
df3bb2
+        );
df3bb2
+
df3bb2
+        (* Start an nbdkit instance in the background.  By using
df3bb2
+         * --exit-with-parent we don't have to worry about clean-up.
df3bb2
+         *)
df3bb2
+        let args = Array.of_list args in
df3bb2
+        let pid = fork () in
df3bb2
+        if pid = 0 then (
df3bb2
+          (* Child process (nbdkit). *)
df3bb2
+          execvp "nbdkit" args
df3bb2
+        );
df3bb2
+
df3bb2
+        (* Wait for the pidfile to appear so we know that nbdkit
df3bb2
+         * is listening for requests.
df3bb2
+         *)
df3bb2
+        if not (wait_for_file pidfile pidfile_timeout) then (
df3bb2
+          if verbose () then
df3bb2
+            error (f_"nbdkit did not start up.  See previous debugging messages for problems.")
df3bb2
+          else
df3bb2
+            error (f_"nbdkit did not start up.  There may be errors printed by nbdkit above.
df3bb2
+
df3bb2
+If the messages above are not sufficient to diagnose the problem then add the ‘virt-v2v -v -x’ options and examine the debugging output carefully.")
df3bb2
+        );
df3bb2
+
df3bb2
+        if have_selinux then (
df3bb2
+          (* Note that Unix domain sockets have both a file label and
df3bb2
+           * a socket/process label.  Using --selinux-label above
df3bb2
+           * only set the socket label, but we must also set the file
df3bb2
+           * label.
df3bb2
+           *)
df3bb2
+          ignore (
df3bb2
+              run_command ["chcon"; "system_u:object_r:svirt_image_t:s0";
df3bb2
+                           sock]
df3bb2
+          );
df3bb2
+        );
df3bb2
+        (* ... and the regular Unix permissions, in case qemu is
df3bb2
+         * running as another user.
df3bb2
+         *)
df3bb2
+        chmod sock 0o777;
df3bb2
+
df3bb2
+        (* Tell ‘qemu-img convert’ to write to the nbd socket which is
df3bb2
+         * connected to nbdkit.
df3bb2
+         *)
df3bb2
+        let json_params = [
df3bb2
+          "file.driver", JSON.String "nbd";
df3bb2
+          "file.path", JSON.String sock;
df3bb2
+          "file.export", JSON.String "/";
df3bb2
+        ] in
df3bb2
+        let target_file =
df3bb2
+          TargetURI ("json:" ^ JSON.string_of_doc json_params) in
df3bb2
+        { t with target_file }
df3bb2
+    ) targets
df3bb2
+
df3bb2
+  method create_metadata source targets _ guestcaps inspect target_firmware =
df3bb2
+    (* Get the UUIDs of each disk image.  These files are written
df3bb2
+     * out by the nbdkit plugins on successful finalization of the
df3bb2
+     * transfer.
df3bb2
+     *)
df3bb2
+    let nr_disks = List.length targets in
df3bb2
+    let image_uuids =
df3bb2
+      List.map (
df3bb2
+        fun t ->
df3bb2
+          let id = t.target_overlay.ov_source.s_disk_id in
df3bb2
+          let diskid_file = diskid_file_of_id id in
df3bb2
+          if not (wait_for_file diskid_file finalization_timeout) then
df3bb2
+            error (f_"transfer of disk %d/%d failed, see earlier error messages")
df3bb2
+                  (id+1) nr_disks;
df3bb2
+          let diskid = read_whole_file diskid_file in
df3bb2
+          diskid
df3bb2
+      ) targets in
df3bb2
+
df3bb2
+    (* We don't have the storage domain UUID, but instead we write
df3bb2
+     * in a magic value which the Python code (which can get it)
df3bb2
+     * will substitute.
df3bb2
+     *)
df3bb2
+    let sd_uuid = "@SD_UUID@" in
df3bb2
+
df3bb2
+    (* The volume and VM UUIDs are made up. *)
df3bb2
+    let vol_uuids = List.map (fun _ -> uuidgen ()) targets
df3bb2
+    and vm_uuid = uuidgen () in
df3bb2
+
df3bb2
+    (* Create the metadata. *)
df3bb2
+    let ovf =
df3bb2
+      Create_ovf.create_ovf source targets guestcaps inspect
df3bb2
+                            output_alloc
df3bb2
+                            sd_uuid image_uuids vol_uuids vm_uuid
df3bb2
+                            OVirt in
df3bb2
+    let ovf = DOM.doc_to_string ovf in
df3bb2
+
df3bb2
+    let json_param_file = tmpdir // "params.json" in
df3bb2
+    with_open_out
df3bb2
+      json_param_file
df3bb2
+      (fun chan -> output_string chan (JSON.string_of_doc json_params));
df3bb2
+
df3bb2
+    let ovf_file = tmpdir // "vm.ovf" in
df3bb2
+    with_open_out ovf_file (fun chan -> output_string chan ovf);
df3bb2
+    if run_command [ python3; createvm; json_param_file; ovf_file ] <> 0 then
df3bb2
+      error (f_"failed to create virtual machine, see earlier errors")
df3bb2
+
df3bb2
+end
df3bb2
+
df3bb2
+let output_rhv_upload = new output_rhv_upload
df3bb2
+let () = Modules_list.register_output_module "rhv-upload"
df3bb2
diff --git a/v2v/output_rhv_upload.mli b/v2v/output_rhv_upload.mli
df3bb2
new file mode 100644
df3bb2
index 000000000..f6cd69a61
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/output_rhv_upload.mli
df3bb2
@@ -0,0 +1,33 @@
df3bb2
+(* virt-v2v
df3bb2
+ * Copyright (C) 2009-2018 Red Hat Inc.
df3bb2
+ *
df3bb2
+ * This program is free software; you can redistribute it and/or modify
df3bb2
+ * it under the terms of the GNU General Public License as published by
df3bb2
+ * the Free Software Foundation; either version 2 of the License, or
df3bb2
+ * (at your option) any later version.
df3bb2
+ *
df3bb2
+ * This program is distributed in the hope that it will be useful,
df3bb2
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+ * GNU General Public License for more details.
df3bb2
+ *
df3bb2
+ * You should have received a copy of the GNU General Public License along
df3bb2
+ * with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+ *)
df3bb2
+
df3bb2
+(** [-o rhv-upload] target. *)
df3bb2
+
df3bb2
+type rhv_options
df3bb2
+(** Miscellaneous extra command line parameters used by rhv-upload. *)
df3bb2
+
df3bb2
+val print_output_options : unit -> unit
df3bb2
+val parse_output_options : (string * string) list -> rhv_options
df3bb2
+(** Print and parse rhv-upload -oo options. *)
df3bb2
+
df3bb2
+val output_rhv_upload : Types.output_allocation -> string -> string ->
df3bb2
+                        string -> rhv_options -> Types.output
df3bb2
+(** [output_rhv_upload output_alloc output_conn output_password output_storage
df3bb2
+     rhv_options]
df3bb2
+    creates and returns a new {!Types.output} object specialized for writing
df3bb2
+    output to oVirt or RHV directly via RHV APIs. *)
df3bb2
diff --git a/v2v/output_rhv_upload_createvm_source.mli b/v2v/output_rhv_upload_createvm_source.mli
df3bb2
new file mode 100644
df3bb2
index 000000000..c1bafa15b
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/output_rhv_upload_createvm_source.mli
df3bb2
@@ -0,0 +1,19 @@
df3bb2
+(* virt-v2v
df3bb2
+ * Copyright (C) 2018 Red Hat Inc.
df3bb2
+ *
df3bb2
+ * This program is free software; you can redistribute it and/or modify
df3bb2
+ * it under the terms of the GNU General Public License as published by
df3bb2
+ * the Free Software Foundation; either version 2 of the License, or
df3bb2
+ * (at your option) any later version.
df3bb2
+ *
df3bb2
+ * This program is distributed in the hope that it will be useful,
df3bb2
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+ * GNU General Public License for more details.
df3bb2
+ *
df3bb2
+ * You should have received a copy of the GNU General Public License along
df3bb2
+ * with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+ *)
df3bb2
+
df3bb2
+val code : string
df3bb2
diff --git a/v2v/output_rhv_upload_plugin_source.mli b/v2v/output_rhv_upload_plugin_source.mli
df3bb2
new file mode 100644
df3bb2
index 000000000..c1bafa15b
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/output_rhv_upload_plugin_source.mli
df3bb2
@@ -0,0 +1,19 @@
df3bb2
+(* virt-v2v
df3bb2
+ * Copyright (C) 2018 Red Hat Inc.
df3bb2
+ *
df3bb2
+ * This program is free software; you can redistribute it and/or modify
df3bb2
+ * it under the terms of the GNU General Public License as published by
df3bb2
+ * the Free Software Foundation; either version 2 of the License, or
df3bb2
+ * (at your option) any later version.
df3bb2
+ *
df3bb2
+ * This program is distributed in the hope that it will be useful,
df3bb2
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+ * GNU General Public License for more details.
df3bb2
+ *
df3bb2
+ * You should have received a copy of the GNU General Public License along
df3bb2
+ * with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+ *)
df3bb2
+
df3bb2
+val code : string
df3bb2
diff --git a/v2v/output_rhv_upload_precheck_source.mli b/v2v/output_rhv_upload_precheck_source.mli
df3bb2
new file mode 100644
df3bb2
index 000000000..c1bafa15b
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/output_rhv_upload_precheck_source.mli
df3bb2
@@ -0,0 +1,19 @@
df3bb2
+(* virt-v2v
df3bb2
+ * Copyright (C) 2018 Red Hat Inc.
df3bb2
+ *
df3bb2
+ * This program is free software; you can redistribute it and/or modify
df3bb2
+ * it under the terms of the GNU General Public License as published by
df3bb2
+ * the Free Software Foundation; either version 2 of the License, or
df3bb2
+ * (at your option) any later version.
df3bb2
+ *
df3bb2
+ * This program is distributed in the hope that it will be useful,
df3bb2
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+ * GNU General Public License for more details.
df3bb2
+ *
df3bb2
+ * You should have received a copy of the GNU General Public License along
df3bb2
+ * with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+ *)
df3bb2
+
df3bb2
+val code : string
df3bb2
diff --git a/v2v/rhv-upload-createvm.py b/v2v/rhv-upload-createvm.py
df3bb2
new file mode 100644
df3bb2
index 000000000..a34627ec8
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/rhv-upload-createvm.py
df3bb2
@@ -0,0 +1,86 @@
df3bb2
+# -*- python -*-
df3bb2
+# oVirt or RHV upload create VM used by ‘virt-v2v -o rhv-upload’
df3bb2
+# Copyright (C) 2018 Red Hat Inc.
df3bb2
+#
df3bb2
+# This program is free software; you can redistribute it and/or modify
df3bb2
+# it under the terms of the GNU General Public License as published by
df3bb2
+# the Free Software Foundation; either version 2 of the License, or
df3bb2
+# (at your option) any later version.
df3bb2
+#
df3bb2
+# This program is distributed in the hope that it will be useful,
df3bb2
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+# GNU General Public License for more details.
df3bb2
+#
df3bb2
+# You should have received a copy of the GNU General Public License along
df3bb2
+# with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+
df3bb2
+import json
df3bb2
+import logging
df3bb2
+import sys
df3bb2
+import time
df3bb2
+
df3bb2
+from http.client import HTTPSConnection
df3bb2
+from urllib.parse import urlparse
df3bb2
+
df3bb2
+import ovirtsdk4 as sdk
df3bb2
+import ovirtsdk4.types as types
df3bb2
+
df3bb2
+# Parameters are passed in via a JSON doc from the OCaml code.
df3bb2
+# Because this Python code ships embedded inside virt-v2v there
df3bb2
+# is no formal API here.
df3bb2
+params = None
df3bb2
+ovf = None                      # OVF file
df3bb2
+
df3bb2
+if len(sys.argv) != 3:
df3bb2
+    raise RuntimeError("incorrect number of parameters")
df3bb2
+
df3bb2
+# Parameters are passed in via a JSON document.
df3bb2
+with open(sys.argv[1], 'r') as fp:
df3bb2
+    params = json.load(fp)
df3bb2
+
df3bb2
+# What is passed in is a password file, read the actual password.
df3bb2
+with open(params['output_password'], 'r') as fp:
df3bb2
+    output_password = fp.read()
df3bb2
+output_password = output_password.rstrip()
df3bb2
+
df3bb2
+# Read the OVF document.
df3bb2
+with open(sys.argv[2], 'r') as fp:
df3bb2
+    ovf = fp.read()
df3bb2
+
df3bb2
+# Parse out the username from the output_conn URL.
df3bb2
+parsed = urlparse(params['output_conn'])
df3bb2
+username = parsed.username or "admin@internal"
df3bb2
+
df3bb2
+# Connect to the server.
df3bb2
+connection = sdk.Connection(
df3bb2
+    url = params['output_conn'],
df3bb2
+    username = username,
df3bb2
+    password = output_password,
df3bb2
+    ca_file = params['rhv_cafile'],
df3bb2
+    log = logging.getLogger(),
df3bb2
+    insecure = params['insecure'],
df3bb2
+)
df3bb2
+
df3bb2
+system_service = connection.system_service()
df3bb2
+
df3bb2
+# Get the storage domain UUID and substitute it into the OVF doc.
df3bb2
+sds_service = system_service.storage_domains_service()
df3bb2
+sd = sds_service.list(search=("name=%s" % params['output_storage']))[0]
df3bb2
+sd_uuid = sd.id
df3bb2
+
df3bb2
+ovf.replace("@SD_UUID@", sd_uuid)
df3bb2
+
df3bb2
+vms_service = system_service.vms_service()
df3bb2
+vm = vms_service.add(
df3bb2
+    types.Vm(
df3bb2
+        cluster=types.Cluster(name = params['rhv_cluster']),
df3bb2
+        initialization=types.Initialization(
df3bb2
+            configuration = types.Configuration(
df3bb2
+                type = types.ConfigurationType.OVA,
df3bb2
+                data = ovf,
df3bb2
+            )
df3bb2
+        )
df3bb2
+    )
df3bb2
+)
df3bb2
diff --git a/v2v/rhv-upload-plugin.py b/v2v/rhv-upload-plugin.py
df3bb2
new file mode 100644
df3bb2
index 000000000..791c9e7d2
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/rhv-upload-plugin.py
df3bb2
@@ -0,0 +1,445 @@
df3bb2
+# -*- python -*-
df3bb2
+# oVirt or RHV upload nbdkit plugin used by ‘virt-v2v -o rhv-upload’
df3bb2
+# Copyright (C) 2018 Red Hat Inc.
df3bb2
+#
df3bb2
+# This program is free software; you can redistribute it and/or modify
df3bb2
+# it under the terms of the GNU General Public License as published by
df3bb2
+# the Free Software Foundation; either version 2 of the License, or
df3bb2
+# (at your option) any later version.
df3bb2
+#
df3bb2
+# This program is distributed in the hope that it will be useful,
df3bb2
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+# GNU General Public License for more details.
df3bb2
+#
df3bb2
+# You should have received a copy of the GNU General Public License along
df3bb2
+# with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+
df3bb2
+import builtins
df3bb2
+import json
df3bb2
+import logging
df3bb2
+import ssl
df3bb2
+import sys
df3bb2
+import time
df3bb2
+
df3bb2
+from http.client import HTTPSConnection
df3bb2
+from urllib.parse import urlparse
df3bb2
+
df3bb2
+import ovirtsdk4 as sdk
df3bb2
+import ovirtsdk4.types as types
df3bb2
+
df3bb2
+# Timeout to wait for oVirt disks to change status, or the transfer
df3bb2
+# object to finish initializing [seconds].
df3bb2
+timeout = 5*60
df3bb2
+
df3bb2
+# Parameters are passed in via a JSON doc from the OCaml code.
df3bb2
+# Because this Python code ships embedded inside virt-v2v there
df3bb2
+# is no formal API here.
df3bb2
+params = None
df3bb2
+
df3bb2
+def config(key, value):
df3bb2
+    global params
df3bb2
+
df3bb2
+    if key == "params":
df3bb2
+        with builtins.open(value, 'r') as fp:
df3bb2
+            params = json.load(fp)
df3bb2
+    else:
df3bb2
+        raise RuntimeError("unknown configuration key '%s'" % key)
df3bb2
+
df3bb2
+def config_complete():
df3bb2
+    if params is None:
df3bb2
+        raise RuntimeError("missing configuration parameters")
df3bb2
+
df3bb2
+def debug(s):
df3bb2
+    if params['verbose']:
df3bb2
+        print(s, file=sys.stderr)
df3bb2
+        sys.stderr.flush()
df3bb2
+
df3bb2
+def open(readonly):
df3bb2
+    # Parse out the username from the output_conn URL.
df3bb2
+    parsed = urlparse(params['output_conn'])
df3bb2
+    username = parsed.username or "admin@internal"
df3bb2
+
df3bb2
+    # Read the password from file.
df3bb2
+    with builtins.open(params['output_password'], 'r') as fp:
df3bb2
+        password = fp.read()
df3bb2
+    password = password.rstrip()
df3bb2
+
df3bb2
+    # Connect to the server.
df3bb2
+    connection = sdk.Connection(
df3bb2
+        url = params['output_conn'],
df3bb2
+        username = username,
df3bb2
+        password = password,
df3bb2
+        ca_file = params['rhv_cafile'],
df3bb2
+        log = logging.getLogger(),
df3bb2
+        insecure = params['insecure'],
df3bb2
+    )
df3bb2
+
df3bb2
+    system_service = connection.system_service()
df3bb2
+
df3bb2
+    # Create the disk.
df3bb2
+    disks_service = system_service.disks_service()
df3bb2
+    if params['disk_format'] == "raw":
df3bb2
+        disk_format = types.DiskFormat.RAW
df3bb2
+    else:
df3bb2
+        disk_format = types.DiskFormat.COW
df3bb2
+    disk = disks_service.add(
df3bb2
+        disk = types.Disk(
df3bb2
+            name = params['disk_name'],
df3bb2
+            description = "Uploaded by virt-v2v",
df3bb2
+            format = disk_format,
df3bb2
+            initial_size = params['disk_size'],
df3bb2
+            provisioned_size = params['disk_size'],
df3bb2
+            # XXX Ignores params['output_sparse'].
df3bb2
+            # Handling this properly will be complex, see:
df3bb2
+            # https://www.redhat.com/archives/libguestfs/2018-March/msg00177.html
df3bb2
+            sparse = True,
df3bb2
+            storage_domains = [
df3bb2
+                types.StorageDomain(
df3bb2
+                    name = params['output_storage'],
df3bb2
+                )
df3bb2
+            ],
df3bb2
+        )
df3bb2
+    )
df3bb2
+
df3bb2
+    # Wait till the disk is up, as the transfer can't start if the
df3bb2
+    # disk is locked:
df3bb2
+    disk_service = disks_service.disk_service(disk.id)
df3bb2
+    debug("disk.id = %r" % disk.id)
df3bb2
+
df3bb2
+    endt = time.time() + timeout
df3bb2
+    while True:
df3bb2
+        time.sleep(5)
df3bb2
+        disk = disk_service.get()
df3bb2
+        if disk.status == types.DiskStatus.OK:
df3bb2
+            break
df3bb2
+        if time.time() > endt:
df3bb2
+            raise RuntimeError("timed out waiting for disk to become unlocked")
df3bb2
+
df3bb2
+    # Get a reference to the transfer service.
df3bb2
+    transfers_service = system_service.image_transfers_service()
df3bb2
+
df3bb2
+    # Create a new image transfer.
df3bb2
+    transfer = transfers_service.add(
df3bb2
+        types.ImageTransfer(
df3bb2
+            image = types.Image(
df3bb2
+                id = disk.id
df3bb2
+            )
df3bb2
+        )
df3bb2
+    )
df3bb2
+    debug("transfer.id = %r" % transfer.id)
df3bb2
+
df3bb2
+    # Get a reference to the created transfer service.
df3bb2
+    transfer_service = transfers_service.image_transfer_service(transfer.id)
df3bb2
+
df3bb2
+    # After adding a new transfer for the disk, the transfer's status
df3bb2
+    # will be INITIALIZING.  Wait until the init phase is over. The
df3bb2
+    # actual transfer can start when its status is "Transferring".
df3bb2
+    endt = time.time() + timeout
df3bb2
+    while True:
df3bb2
+        time.sleep(5)
df3bb2
+        transfer = transfer_service.get()
df3bb2
+        if transfer.phase != types.ImageTransferPhase.INITIALIZING:
df3bb2
+            break
df3bb2
+        if time.time() > endt:
df3bb2
+            raise RuntimeError("timed out waiting for transfer status " +
df3bb2
+                               "!= INITIALIZING")
df3bb2
+
df3bb2
+    # Now we have permission to start the transfer.
df3bb2
+    if params['rhv_direct']:
df3bb2
+        if transfer.transfer_url is None:
df3bb2
+            raise RuntimeError("direct upload to host not supported, " +
df3bb2
+                               "requires ovirt-engine >= 4.2 and only works " +
df3bb2
+                               "when virt-v2v is run within the oVirt/RHV " +
df3bb2
+                               "environment, eg. on an oVirt node.")
df3bb2
+        destination_url = urlparse(transfer.transfer_url)
df3bb2
+    else:
df3bb2
+        destination_url = urlparse(transfer.proxy_url)
df3bb2
+
df3bb2
+    context = ssl.create_default_context()
df3bb2
+    context.load_verify_locations(cafile = params['rhv_cafile'])
df3bb2
+
df3bb2
+    http = HTTPSConnection(
df3bb2
+        destination_url.hostname,
df3bb2
+        destination_url.port,
df3bb2
+        context = context
df3bb2
+    )
df3bb2
+
df3bb2
+    # Save everything we need to make requests in the handle.
df3bb2
+    return {
df3bb2
+        'can_flush': False,
df3bb2
+        'can_trim': False,
df3bb2
+        'can_zero': False,
df3bb2
+        'connection': connection,
df3bb2
+        'disk': disk,
df3bb2
+        'disk_service': disk_service,
df3bb2
+        'failed': False,
df3bb2
+        'got_options': False,
df3bb2
+        'highestwrite': 0,
df3bb2
+        'http': http,
df3bb2
+        'needs_auth': not params['rhv_direct'],
df3bb2
+        'path': destination_url.path,
df3bb2
+        'transfer': transfer,
df3bb2
+        'transfer_service': transfer_service,
df3bb2
+    }
df3bb2
+
df3bb2
+# Can we issue zero, trim or flush requests?
df3bb2
+def get_options(h):
df3bb2
+    if h['got_options']:
df3bb2
+        return
df3bb2
+    h['got_options'] = True
df3bb2
+
df3bb2
+    http = h['http']
df3bb2
+    transfer = h['transfer']
df3bb2
+
df3bb2
+    http.putrequest("OPTIONS", h['path'])
df3bb2
+    http.putheader("Authorization", transfer.signed_ticket)
df3bb2
+    http.endheaders()
df3bb2
+
df3bb2
+    r = http.getresponse()
df3bb2
+    if r.status == 200:
df3bb2
+        # New imageio never needs authentication.
df3bb2
+        h['needs_auth'] = False
df3bb2
+
df3bb2
+        j = json.loads(r.read())
df3bb2
+        h['can_zero'] = "zero" in j['features']
df3bb2
+        h['can_trim'] = "trim" in j['features']
df3bb2
+        h['can_flush'] = "flush" in j['features']
df3bb2
+
df3bb2
+    # Old imageio servers returned either 405 Method Not Allowed or
df3bb2
+    # 204 No Content (with an empty body).  If we see that we leave
df3bb2
+    # all the features as False and they will be emulated.
df3bb2
+    elif r.status == 405 or r.status == 204:
df3bb2
+        pass
df3bb2
+
df3bb2
+    else:
df3bb2
+        raise RuntimeError("could not use OPTIONS request: %d: %s" %
df3bb2
+                           (r.status, r.reason))
df3bb2
+
df3bb2
+def can_trim(h):
df3bb2
+    get_options(h)
df3bb2
+    return h['can_trim']
df3bb2
+
df3bb2
+def can_flush(h):
df3bb2
+    get_options(h)
df3bb2
+    return h['can_flush']
df3bb2
+
df3bb2
+def get_size(h):
df3bb2
+    return params['disk_size']
df3bb2
+
df3bb2
+# For documentation see:
df3bb2
+# https://github.com/oVirt/ovirt-imageio/blob/master/docs/random-io.md
df3bb2
+# For examples of working code to read/write from the server, see:
df3bb2
+# https://github.com/oVirt/ovirt-imageio/blob/master/daemon/test/server_test.py
df3bb2
+
df3bb2
+def pread(h, count, offset):
df3bb2
+    http = h['http']
df3bb2
+    transfer = h['transfer']
df3bb2
+    transfer_service = h['transfer_service']
df3bb2
+
df3bb2
+    http.putrequest("GET", h['path'])
df3bb2
+    # Authorization is only needed for old imageio.
df3bb2
+    if h['needs_auth']:
df3bb2
+        http.putheader("Authorization", transfer.signed_ticket)
df3bb2
+    http.putheader("Range", "bytes=%d-%d" % (offset, offset+count-1))
df3bb2
+    http.endheaders()
df3bb2
+
df3bb2
+    r = http.getresponse()
df3bb2
+    # 206 = HTTP Partial Content.
df3bb2
+    if r.status != 206:
df3bb2
+        h['transfer_service'].pause()
df3bb2
+        h['failed'] = True
df3bb2
+        raise RuntimeError("could not read sector (%d, %d): %d: %s" %
df3bb2
+                           (offset, count, r.status, r.reason))
df3bb2
+    return r.read()
df3bb2
+
df3bb2
+def pwrite(h, buf, offset):
df3bb2
+    http = h['http']
df3bb2
+    transfer = h['transfer']
df3bb2
+    transfer_service = h['transfer_service']
df3bb2
+
df3bb2
+    count = len(buf)
df3bb2
+    h['highestwrite'] = max(h['highestwrite'], offset+count)
df3bb2
+
df3bb2
+    http.putrequest("PUT", h['path'] + "?flush=n")
df3bb2
+    # Authorization is only needed for old imageio.
df3bb2
+    if h['needs_auth']:
df3bb2
+        http.putheader("Authorization", transfer.signed_ticket)
df3bb2
+    # The oVirt server only uses the first part of the range, and the
df3bb2
+    # content-length.
df3bb2
+    http.putheader("Content-Range", "bytes %d-%d/*" % (offset, offset+count-1))
df3bb2
+    http.putheader("Content-Length", str(count))
df3bb2
+    http.endheaders()
df3bb2
+    http.send(buf)
df3bb2
+
df3bb2
+    r = http.getresponse()
df3bb2
+    if r.status != 200:
df3bb2
+        transfer_service.pause()
df3bb2
+        h['failed'] = True
df3bb2
+        raise RuntimeError("could not write sector (%d, %d): %d: %s" %
df3bb2
+                           (offset, count, r.status, r.reason))
df3bb2
+
df3bb2
+def zero(h, count, offset, may_trim):
df3bb2
+    http = h['http']
df3bb2
+    transfer = h['transfer']
df3bb2
+    transfer_service = h['transfer_service']
df3bb2
+
df3bb2
+    # Unlike the trim and flush calls, there is no 'can_zero' method
df3bb2
+    # so nbdkit could call this even if the server doesn't support
df3bb2
+    # zeroing.  If this is the case we must emulate.
df3bb2
+    if not h['can_zero']:
df3bb2
+        emulate_zero(h, count, offset)
df3bb2
+        return
df3bb2
+
df3bb2
+    # Construct the JSON request for zeroing.
df3bb2
+    buf = json.dumps({'op': "zero",
df3bb2
+                      'offset': offset,
df3bb2
+                      'size': count,
df3bb2
+                      'flush': False}).encode()
df3bb2
+
df3bb2
+    http.putrequest("PATCH", h['path'])
df3bb2
+    http.putheader("Content-Type", "application/json")
df3bb2
+    http.putheader("Content-Length", len(buf))
df3bb2
+    http.endheaders()
df3bb2
+    http.send(buf)
df3bb2
+
df3bb2
+    r = http.getresponse()
df3bb2
+    if r.status != 200:
df3bb2
+        transfer_service.pause()
df3bb2
+        h['failed'] = True
df3bb2
+        raise RuntimeError("could not zero sector (%d, %d): %d: %s" %
df3bb2
+                           (offset, count, r.status, r.reason))
df3bb2
+
df3bb2
+def emulate_zero(h, count, offset):
df3bb2
+    # qemu-img convert starts by trying to zero/trim the whole device.
df3bb2
+    # Since we've just created a new disk it's safe to ignore these
df3bb2
+    # requests as long as they are smaller than the highest write seen.
df3bb2
+    # After that we must emulate them with writes.
df3bb2
+    if offset+count < h['highestwrite']:
df3bb2
+        http.putrequest("PUT", h['path'])
df3bb2
+        # Authorization is only needed for old imageio.
df3bb2
+        if h['needs_auth']:
df3bb2
+            http.putheader("Authorization", transfer.signed_ticket)
df3bb2
+        http.putheader("Content-Range",
df3bb2
+                       "bytes %d-%d/*" % (offset, offset+count-1))
df3bb2
+        http.putheader("Content-Length", str(count))
df3bb2
+        http.endheaders()
df3bb2
+
df3bb2
+        buf = bytearray(128*1024)
df3bb2
+        while count > len(buf):
df3bb2
+            http.send(buf)
df3bb2
+            count -= len(buf)
df3bb2
+        http.send(buffer(buf, 0, count))
df3bb2
+
df3bb2
+        r = http.getresponse()
df3bb2
+        if r.status != 200:
df3bb2
+            transfer_service.pause()
df3bb2
+            h['failed'] = True
df3bb2
+            raise RuntimeError("could not write zeroes (%d, %d): %d: %s" %
df3bb2
+                               (offset, count, r.status, r.reason))
df3bb2
+
df3bb2
+def trim(h, count, offset):
df3bb2
+    http = h['http']
df3bb2
+    transfer = h['transfer']
df3bb2
+    transfer_service = h['transfer_service']
df3bb2
+
df3bb2
+    # Construct the JSON request for trimming.
df3bb2
+    buf = json.dumps({'op': "trim",
df3bb2
+                      'offset': offset,
df3bb2
+                      'size': count,
df3bb2
+                      'flush': False}).encode()
df3bb2
+
df3bb2
+    http.putrequest("PATCH", h['path'])
df3bb2
+    http.putheader("Content-Type", "application/json")
df3bb2
+    http.putheader("Content-Length", len(buf))
df3bb2
+    http.endheaders()
df3bb2
+    http.send(buf)
df3bb2
+
df3bb2
+    r = http.getresponse()
df3bb2
+    if r.status != 200:
df3bb2
+        transfer_service.pause()
df3bb2
+        h['failed'] = True
df3bb2
+        raise RuntimeError("could not trim sector (%d, %d): %d: %s" %
df3bb2
+                           (offset, count, r.status, r.reason))
df3bb2
+
df3bb2
+def flush(h):
df3bb2
+    http = h['http']
df3bb2
+    transfer = h['transfer']
df3bb2
+    transfer_service = h['transfer_service']
df3bb2
+
df3bb2
+    # Construct the JSON request for flushing.
df3bb2
+    buf = json.dumps({'op': "flush"}).encode()
df3bb2
+
df3bb2
+    http.putrequest("PATCH", h['path'])
df3bb2
+    http.putheader("Content-Type", "application/json")
df3bb2
+    http.putheader("Content-Length", len(buf))
df3bb2
+    http.endheaders()
df3bb2
+    http.send(buf)
df3bb2
+
df3bb2
+    r = http.getresponse()
df3bb2
+    if r.status != 200:
df3bb2
+        transfer_service.pause()
df3bb2
+        h['failed'] = True
df3bb2
+        raise RuntimeError("could not flush: %d: %s" % (r.status, r.reason))
df3bb2
+
df3bb2
+def delete_disk_on_failure(h):
df3bb2
+    disk_service = h['disk_service']
df3bb2
+    disk_service.remove()
df3bb2
+
df3bb2
+def close(h):
df3bb2
+    http = h['http']
df3bb2
+    connection = h['connection']
df3bb2
+
df3bb2
+    # This is sometimes necessary because python doesn't set up
df3bb2
+    # sys.stderr to be line buffered and so debug, errors or
df3bb2
+    # exceptions printed previously might not be emitted before the
df3bb2
+    # plugin exits.
df3bb2
+    sys.stderr.flush()
df3bb2
+
df3bb2
+    # If the connection failed earlier ensure we clean up the disk.
df3bb2
+    if h['failed']:
df3bb2
+        delete_disk_on_failure(h)
df3bb2
+        connection.close()
df3bb2
+        return
df3bb2
+
df3bb2
+    try:
df3bb2
+        # Issue a flush request on close so that the data is written to
df3bb2
+        # persistent store before we create the VM.
df3bb2
+        if h['can_flush']:
df3bb2
+            flush(h)
df3bb2
+
df3bb2
+        http.close()
df3bb2
+
df3bb2
+        disk = h['disk']
df3bb2
+        transfer_service = h['transfer_service']
df3bb2
+
df3bb2
+        transfer_service.finalize()
df3bb2
+
df3bb2
+        # Wait until the transfer disk job is completed since
df3bb2
+        # only then we can be sure the disk is unlocked.  As this
df3bb2
+        # code is not very clear, what's happening is that we are
df3bb2
+        # waiting for the transfer object to cease to exist, which
df3bb2
+        # falls through to the exception case and then we can
df3bb2
+        # continue.
df3bb2
+        endt = time.time() + timeout
df3bb2
+        try:
df3bb2
+            while True:
df3bb2
+                time.sleep(1)
df3bb2
+                tmp = transfer_service.get()
df3bb2
+                if time.time() > endt:
df3bb2
+                    raise RuntimeError("timed out waiting for transfer " +
df3bb2
+                                       "to finalize")
df3bb2
+        except sdk.NotFoundError:
df3bb2
+            pass
df3bb2
+
df3bb2
+        # Write the disk ID file.  Only do this on successful completion.
df3bb2
+        with builtins.open(params['diskid_file'], 'w') as fp:
df3bb2
+            fp.write(disk.id)
df3bb2
+
df3bb2
+    except:
df3bb2
+        # Otherwise on any failure we must clean up the disk.
df3bb2
+        delete_disk_on_failure(h)
df3bb2
+        raise
df3bb2
+
df3bb2
+    connection.close()
df3bb2
diff --git a/v2v/rhv-upload-precheck.py b/v2v/rhv-upload-precheck.py
df3bb2
new file mode 100644
df3bb2
index 000000000..2798a29dd
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/rhv-upload-precheck.py
df3bb2
@@ -0,0 +1,73 @@
df3bb2
+# -*- python -*-
df3bb2
+# oVirt or RHV pre-upload checks used by ‘virt-v2v -o rhv-upload’
df3bb2
+# Copyright (C) 2018 Red Hat Inc.
df3bb2
+#
df3bb2
+# This program is free software; you can redistribute it and/or modify
df3bb2
+# it under the terms of the GNU General Public License as published by
df3bb2
+# the Free Software Foundation; either version 2 of the License, or
df3bb2
+# (at your option) any later version.
df3bb2
+#
df3bb2
+# This program is distributed in the hope that it will be useful,
df3bb2
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+# GNU General Public License for more details.
df3bb2
+#
df3bb2
+# You should have received a copy of the GNU General Public License along
df3bb2
+# with this program; if not, write to the Free Software Foundation, Inc.,
df3bb2
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+
df3bb2
+import json
df3bb2
+import logging
df3bb2
+import sys
df3bb2
+import time
df3bb2
+
df3bb2
+from http.client import HTTPSConnection
df3bb2
+from urllib.parse import urlparse
df3bb2
+
df3bb2
+import ovirtsdk4 as sdk
df3bb2
+import ovirtsdk4.types as types
df3bb2
+
df3bb2
+# Parameters are passed in via a JSON doc from the OCaml code.
df3bb2
+# Because this Python code ships embedded inside virt-v2v there
df3bb2
+# is no formal API here.
df3bb2
+params = None
df3bb2
+
df3bb2
+if len(sys.argv) != 2:
df3bb2
+    raise RuntimeError("incorrect number of parameters")
df3bb2
+
df3bb2
+# Parameters are passed in via a JSON document.
df3bb2
+with open(sys.argv[1], 'r') as fp:
df3bb2
+    params = json.load(fp)
df3bb2
+
df3bb2
+# What is passed in is a password file, read the actual password.
df3bb2
+with open(params['output_password'], 'r') as fp:
df3bb2
+    output_password = fp.read()
df3bb2
+output_password = output_password.rstrip()
df3bb2
+
df3bb2
+# Parse out the username from the output_conn URL.
df3bb2
+parsed = urlparse(params['output_conn'])
df3bb2
+username = parsed.username or "admin@internal"
df3bb2
+
df3bb2
+# Connect to the server.
df3bb2
+connection = sdk.Connection(
df3bb2
+    url = params['output_conn'],
df3bb2
+    username = username,
df3bb2
+    password = output_password,
df3bb2
+    ca_file = params['rhv_cafile'],
df3bb2
+    log = logging.getLogger(),
df3bb2
+    insecure = params['insecure'],
df3bb2
+)
df3bb2
+
df3bb2
+system_service = connection.system_service()
df3bb2
+
df3bb2
+# Find if a virtual machine already exists with that name.
df3bb2
+vms_service = system_service.vms_service()
df3bb2
+vms = vms_service.list(
df3bb2
+    search = ("name=%s" % params['output_name']),
df3bb2
+)
df3bb2
+if len(vms) > 0:
df3bb2
+    vm = vms[0]
df3bb2
+    raise RuntimeError("VM already exists with name ‘%s’, id ‘%s’" %
df3bb2
+                       (params['output_name'], vm.id))
df3bb2
+
df3bb2
+# Otherwise everything is OK, exit with no error.
df3bb2
diff --git a/v2v/test-v2v-o-rhv-upload-oo-query.sh b/v2v/test-v2v-o-rhv-upload-oo-query.sh
df3bb2
new file mode 100755
df3bb2
index 000000000..29d69e1c1
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/test-v2v-o-rhv-upload-oo-query.sh
df3bb2
@@ -0,0 +1,38 @@
df3bb2
+#!/bin/bash -
df3bb2
+# libguestfs virt-v2v test script
df3bb2
+# Copyright (C) 2018 Red Hat Inc.
df3bb2
+#
df3bb2
+# This program is free software; you can redistribute it and/or modify
df3bb2
+# it under the terms of the GNU General Public License as published by
df3bb2
+# the Free Software Foundation; either version 2 of the License, or
df3bb2
+# (at your option) any later version.
df3bb2
+#
df3bb2
+# This program is distributed in the hope that it will be useful,
df3bb2
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+# GNU General Public License for more details.
df3bb2
+#
df3bb2
+# You should have received a copy of the GNU General Public License
df3bb2
+# along with this program; if not, write to the Free Software
df3bb2
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+
df3bb2
+# Test -oo "?" option.
df3bb2
+
df3bb2
+set -e
df3bb2
+
df3bb2
+$TEST_FUNCTIONS
df3bb2
+skip_if_skipped
df3bb2
+
df3bb2
+export VIRT_TOOLS_DATA_DIR="$top_srcdir/test-data/fake-virt-tools"
df3bb2
+export VIRTIO_WIN="$top_srcdir/test-data/fake-virtio-win"
df3bb2
+
df3bb2
+f=test-v2v-o-rhv-upload-oo-query.actual
df3bb2
+rm -f $f
df3bb2
+
df3bb2
+$VG virt-v2v --debug-gc \
df3bb2
+    -o rhv-upload -oo "?" > $f
df3bb2
+
df3bb2
+grep -- "-oo rhv-cafile" $f
df3bb2
+grep -- "-oo rhv-verifypeer" $f
df3bb2
+
df3bb2
+rm $f
df3bb2
diff --git a/v2v/test-v2v-python-syntax.sh b/v2v/test-v2v-python-syntax.sh
df3bb2
new file mode 100755
df3bb2
index 000000000..b167f4610
df3bb2
--- /dev/null
df3bb2
+++ b/v2v/test-v2v-python-syntax.sh
df3bb2
@@ -0,0 +1,45 @@
df3bb2
+#!/bin/bash -
df3bb2
+# libguestfs
df3bb2
+# Copyright (C) 2018 Red Hat Inc.
df3bb2
+#
df3bb2
+# This program is free software; you can redistribute it and/or modify
df3bb2
+# it under the terms of the GNU General Public License as published by
df3bb2
+# the Free Software Foundation; either version 2 of the License, or
df3bb2
+# (at your option) any later version.
df3bb2
+#
df3bb2
+# This program is distributed in the hope that it will be useful,
df3bb2
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
df3bb2
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
df3bb2
+# GNU General Public License for more details.
df3bb2
+#
df3bb2
+# You should have received a copy of the GNU General Public License
df3bb2
+# along with this program; if not, write to the Free Software
df3bb2
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
df3bb2
+
df3bb2
+set -e
df3bb2
+
df3bb2
+$TEST_FUNCTIONS
df3bb2
+skip_if_skipped
df3bb2
+
df3bb2
+# Files to check.
df3bb2
+files="rhv-upload-createvm.py rhv-upload-plugin.py rhv-upload-precheck.py"
df3bb2
+
df3bb2
+# Base version of Python.
df3bb2
+python=python3
df3bb2
+
df3bb2
+# Checks the files are syntactically correct, but not very much else.
df3bb2
+for f in $files; do
df3bb2
+    $python -m py_compile $f
df3bb2
+done
df3bb2
+
df3bb2
+# Checks the files correspond to PEP8 coding style.
df3bb2
+# https://www.python.org/dev/peps/pep-0008/
df3bb2
+if $python-pep8 --version >/dev/null 2>&1; then
df3bb2
+    for f in $files; do
df3bb2
+        # Ignore:
df3bb2
+        # E226 missing whitespace around arithmetic operator
df3bb2
+        # E251 unexpected spaces around keyword / parameter equals
df3bb2
+        # E302 expected 2 blank lines, found 1
df3bb2
+        $python-pep8 --ignore=E226,E251,E302 $f
df3bb2
+    done
df3bb2
+fi
df3bb2
diff --git a/v2v/virt-v2v.pod b/v2v/virt-v2v.pod
df3bb2
index 69ca23dfd..2d2f8cfd3 100644
df3bb2
--- a/v2v/virt-v2v.pod
df3bb2
+++ b/v2v/virt-v2v.pod
df3bb2
@@ -6,15 +6,18 @@ virt-v2v - Convert a guest to use KVM
df3bb2
 
df3bb2
  virt-v2v -ic vpx://vcenter.example.com/Datacenter/esxi vmware_guest
df3bb2
 
df3bb2
- virt-v2v -ic vpx://vcenter.example.com/Datacenter/esxi vmware_guest \
df3bb2
-   -o rhv -os rhv.nfs:/export_domain --bridge ovirtmgmt
df3bb2
-
df3bb2
  virt-v2v -i libvirtxml guest-domain.xml -o local -os /var/tmp
df3bb2
 
df3bb2
  virt-v2v -i disk disk.img -o local -os /var/tmp
df3bb2
 
df3bb2
  virt-v2v -i disk disk.img -o glance
df3bb2
 
df3bb2
+ virt-v2v -ic vpx://vcenter.example.com/Datacenter/esxi vmware_guest \
df3bb2
+   -o rhv-upload -oc https://ovirt-engine.example.com/ovirt-engine/api \
df3bb2
+   -os ovirt-data -op /tmp/ovirt-admin-password -of raw \
df3bb2
+   -oo rhv-cafile=/tmp/ca.pem -oo rhv-direct \
df3bb2
+   --bridge ovirtmgmt
df3bb2
+
df3bb2
  virt-v2v -ic qemu:///system qemu_guest --in-place
df3bb2
 
df3bb2
 =head1 DESCRIPTION
df3bb2
@@ -52,20 +55,18 @@ For more information see L</INPUT FROM VMWARE VCENTER SERVER> below.
df3bb2
 =head2 Convert from VMware to RHV/oVirt
df3bb2
 
df3bb2
 This is the same as the previous example, except you want to send the
df3bb2
-guest to a RHV-M Export Storage Domain which is located remotely
df3bb2
-(over NFS) at C<rhv.nfs:/export_domain>.  If you are unclear about
df3bb2
-the location of the Export Storage Domain you should check the
df3bb2
-settings on your RHV-M management console.  Guest network
df3bb2
+guest to a RHV Data Domain using the RHV REST API.  Guest network
df3bb2
 interface(s) are connected to the target network called C<ovirtmgmt>.
df3bb2
 
df3bb2
  virt-v2v -ic vpx://vcenter.example.com/Datacenter/esxi vmware_guest \
df3bb2
-   -o rhv -os rhv.nfs:/export_domain --bridge ovirtmgmt
df3bb2
+   -o rhv-upload -oc https://ovirt-engine.example.com/ovirt-engine/api \
df3bb2
+   -os ovirt-data -op /tmp/ovirt-admin-password -of raw \
df3bb2
+   -oo rhv-cafile=/tmp/ca.pem -oo rhv-direct \
df3bb2
+   --bridge ovirtmgmt
df3bb2
 
df3bb2
 In this case the host running virt-v2v acts as a B<conversion server>.
df3bb2
 
df3bb2
-Note that after conversion, the guest will appear in the RHV-M Export
df3bb2
-Storage Domain, from where you will need to import it using the RHV-M
df3bb2
-user interface.  (See L</OUTPUT TO RHV>).
df3bb2
+For more information see L</OUTPUT TO RHV> below.
df3bb2
 
df3bb2
 =head2 Convert from ESXi hypervisor over SSH to local libvirt
df3bb2
 
df3bb2
@@ -129,9 +130,9 @@ qemu, do:
df3bb2
  Xen ───▶│ -i libvirt ──▶ │            │     │  (default) │
df3bb2
  ... ───▶│  (default) │   │            │ ──┐ └────────────┘
df3bb2
          └────────────┘   │            │ ─┐└──────▶ -o glance
df3bb2
- -i libvirtxml ─────────▶ │            │ ┐└─────────▶ -o rhv
df3bb2
- -i vmx ────────────────▶ │            │ └──────────▶ -o vdsm
df3bb2
-                          └────────────┘
df3bb2
+ -i libvirtxml ─────────▶ │            │ ┐├─────────▶ -o rhv
df3bb2
+ -i vmx ────────────────▶ │            │ │└─────────▶ -o vdsm
df3bb2
+                          └────────────┘ └──────────▶ -o rhv-upload
df3bb2
 
df3bb2
 Virt-v2v has a number of possible input and output modes, selected
df3bb2
 using the I<-i> and I<-o> options.  Only one input and output mode can
df3bb2
@@ -164,8 +165,9 @@ libvirt configuration file (mainly for testing).
df3bb2
 I<-o qemu> writes to a local disk image with a shell script for
df3bb2
 booting the guest directly in qemu (mainly for testing).
df3bb2
 
df3bb2
-I<-o rhv> is used to write to a RHV / oVirt target.  I<-o vdsm>
df3bb2
-is only used when virt-v2v runs under VDSM control.
df3bb2
+I<-o rhv-upload> is used to write to a RHV / oVirt target.  I<-o rhv>
df3bb2
+is a legacy method to write to RHV / oVirt E<lt> 4.2.  I<-o vdsm> is
df3bb2
+only used when virt-v2v runs under VDSM control.
df3bb2
 
df3bb2
 I<--in-place> instructs virt-v2v to customize the guest OS in the input
df3bb2
 virtual machine, instead of creating a new VM in the target hypervisor.
df3bb2
@@ -550,6 +552,10 @@ written.
df3bb2
 
df3bb2
 This is the same as I<-o rhv>.
df3bb2
 
df3bb2
+=item B<-o> B<ovirt-upload>
df3bb2
+
df3bb2
+This is the same as I<-o rhv-upload>.
df3bb2
+
df3bb2
 =item B<-o> B<qemu>
df3bb2
 
df3bb2
 Set the output method to I<qemu>.
df3bb2
@@ -574,6 +580,16 @@ I<-os> parameter must also be used to specify the location of the
df3bb2
 Export Storage Domain.  Note this does not actually import the guest
df3bb2
 into RHV.  You have to do that manually later using the UI.
df3bb2
 
df3bb2
+See L</OUTPUT TO RHV (OLD METHOD)> below.
df3bb2
+
df3bb2
+=item B<-o> B<rhv-upload>
df3bb2
+
df3bb2
+Set the output method to I<rhv-upload>.
df3bb2
+
df3bb2
+The converted guest is written directly to a RHV Data Domain.
df3bb2
+This is a faster method than I<-o rhv>, but requires oVirt
df3bb2
+or RHV E<ge> 4.2.
df3bb2
+
df3bb2
 See L</OUTPUT TO RHV> below.
df3bb2
 
df3bb2
 =item B<-o> B<vdsm>
df3bb2
@@ -615,7 +631,33 @@ the output name is the same as the input name.
df3bb2
 Set output option(s) related to the current output mode.
df3bb2
 To display short help on what options are available you can use:
df3bb2
 
df3bb2
- virt-v2v -o vdsm -oo "?"
df3bb2
+ virt-v2v -o rhv-upload -oo "?"
df3bb2
+
df3bb2
+=item B<-oo rhv-cafile=>F<ca.pem>
df3bb2
+
df3bb2
+For I<-o rhv-upload> (L</OUTPUT TO RHV>) only, the F<ca.pem> file
df3bb2
+(Certificate Authority), copied from F</etc/pki/ovirt-engine/ca.pem>
df3bb2
+on the oVirt engine.
df3bb2
+
df3bb2
+=item B<-oo rhv-cluster=>C<CLUSTERNAME>
df3bb2
+
df3bb2
+For I<-o rhv-upload> (L</OUTPUT TO RHV>) only, set the RHV Cluster
df3bb2
+Name.  If not given it uses C<Default>.
df3bb2
+
df3bb2
+=item B<-oo rhv-direct>
df3bb2
+
df3bb2
+For I<-o rhv-upload> (L</OUTPUT TO RHV>) only, if this option is given
df3bb2
+then virt-v2v will attempt to directly upload the disk to the oVirt
df3bb2
+node, otherwise it will proxy the upload through the oVirt engine.
df3bb2
+Direct upload requires that you have network access to the oVirt
df3bb2
+nodes.  Non-direct upload is slightly slower but should work in all
df3bb2
+situations.
df3bb2
+
df3bb2
+=item B<-oo rhv-verifypeer>
df3bb2
+
df3bb2
+For I<-o rhv-upload> (L</OUTPUT TO RHV>) only, verify the oVirt/RHV
df3bb2
+server’s identity by checking the server‘s certificate against the
df3bb2
+Certificate Authority.
df3bb2
 
df3bb2
 =item B<-oo vdsm-compat=0.10>
df3bb2
 
df3bb2
@@ -1901,6 +1943,68 @@ Define the final guest in libvirt:
df3bb2
 
df3bb2
 =head1 OUTPUT TO RHV
df3bb2
 
df3bb2
+This new method to upload guests to oVirt or RHV directly via the REST
df3bb2
+API requires oVirt/RHV E<ge> 4.2.
df3bb2
+
df3bb2
+You need to specify I<-o rhv-upload> as well as the following extra
df3bb2
+parameters:
df3bb2
+
df3bb2
+=over 4
df3bb2
+
df3bb2
+=item I<-oc> C<https://ovirt-engine.example.com/ovirt-engine/api>
df3bb2
+
df3bb2
+The URL of the REST API which is usually the server name with
df3bb2
+C</ovirt-engine/api> appended, but might be different if you installed
df3bb2
+oVirt Engine on a different path.
df3bb2
+
df3bb2
+You can optionally add a username and port number to the URL.  If the
df3bb2
+username is not specified then virt-v2v defaults to using
df3bb2
+C<admin@internal> which is the typical superuser account for oVirt
df3bb2
+instances.
df3bb2
+
df3bb2
+=item I<-of raw>
df3bb2
+
df3bb2
+Currently you must use I<-of raw> and you cannot use I<-oa preallocated>.
df3bb2
+
df3bb2
+These restrictions will be loosened in a future version.
df3bb2
+
df3bb2
+=item I<-op> F<password-file>
df3bb2
+
df3bb2
+A file containing a password to be used when connecting to the oVirt
df3bb2
+engine.  Note the file should contain the whole password, B
df3bb2
+any trailing newline>, and for security the file should have mode
df3bb2
+C<0600> so that others cannot read it.
df3bb2
+
df3bb2
+=item I<-os> C<ovirt-data>
df3bb2
+
df3bb2
+The storage domain.
df3bb2
+
df3bb2
+=item I<-oo rhv-cafile=>F<ca.pem>
df3bb2
+
df3bb2
+The F<ca.pem> file (Certificate Authority), copied from
df3bb2
+F</etc/pki/ovirt-engine/ca.pem> on the oVirt engine.
df3bb2
+
df3bb2
+=item I<-oo rhv-cluster=>C<CLUSTERNAME>
df3bb2
+
df3bb2
+Set the RHV Cluster Name.  If not given it uses C<Default>.
df3bb2
+
df3bb2
+=item I<-oo rhv-direct>
df3bb2
+
df3bb2
+If this option is given then virt-v2v will attempt to directly upload
df3bb2
+the disk to the oVirt node, otherwise it will proxy the upload through
df3bb2
+the oVirt engine.  Direct upload requires that you have network access
df3bb2
+to the oVirt nodes.  Non-direct upload is slightly slower but should
df3bb2
+work in all situations.
df3bb2
+
df3bb2
+=item I<-oo rhv-verifypeer>
df3bb2
+
df3bb2
+Verify the oVirt/RHV server’s identity by checking the server‘s
df3bb2
+certificate against the Certificate Authority.
df3bb2
+
df3bb2
+=back
df3bb2
+
df3bb2
+=head1 OUTPUT TO RHV (OLD METHOD)
df3bb2
+
df3bb2
 This section only applies to the I<-o rhv> output mode.  If you use
df3bb2
 virt-v2v from the RHV-M user interface, then behind the scenes the
df3bb2
 import is managed by VDSM using the I<-o vdsm> output mode (which end
df3bb2
-- 
df3bb2
2.21.0
df3bb2