mrc0mmand / rpms / libguestfs

Forked from rpms/libguestfs 3 years ago
Clone

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

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