Connecting to an NBD server temporarily, for a "one-shot" operation, is
quite similar to "Std_utils.with_open_in" and
"Std_utils.with_open_out",
as there are cleanup operations regardless of whether the "one-shot"
operation completes successfully or throws an exception.
Introduce the "Utils.with_nbd_connect_unix" function, which takes a Unix
domain socket pathname, a list of metadata contexts to request from the
NBD server, and calls a function with the live NBD server connection.
Bugzilla:
https://bugzilla.redhat.com/show_bug.cgi?id=2027598
Signed-off-by: Laszlo Ersek <lersek(a)redhat.com>
---
Notes:
v2:
- move the function to the Utils module, from Nbdkit [Rich]
- rename the function to "with_nbd_connect_unix" (from
"with_connect_unix")
- update the commit message
lib/Makefile.am | 2 +-
lib/utils.mli | 10 ++++++++++
lib/utils.ml | 12 ++++++++++++
3 files changed, 23 insertions(+), 1 deletion(-)
diff --git a/lib/Makefile.am b/lib/Makefile.am
index c274b9ecf6c7..1fab25b326f5 100644
--- a/lib/Makefile.am
+++ b/lib/Makefile.am
@@ -80,7 +80,7 @@ BOBJECTS = config.cmo $(SOURCES_ML:.ml=.cmo)
XOBJECTS = $(BOBJECTS:.cmo=.cmx)
OCAMLPACKAGES = \
- -package str,unix \
+ -package str,unix,nbd \
-I $(builddir) \
-I $(top_builddir)/common/mlgettext \
-I $(top_builddir)/common/mlpcre \
diff --git a/lib/utils.mli b/lib/utils.mli
index c9b4bd631d65..f41e825e747d 100644
--- a/lib/utils.mli
+++ b/lib/utils.mli
@@ -77,3 +77,13 @@ val metaversion : string
Eventually we may switch to using an "open metadata" format instead
(eg. XML). *)
+
+val with_nbd_connect_unix : socket:string ->
+ meta_contexts:string list ->
+ f:(NBD.t -> 'a) ->
+ 'a
+(** [with_nbd_connect_unix socket meta_contexts f] calls function [f] with the
+ NBD server at Unix domain socket [socket] connected, and the metadata
+ contexts in [meta_contexts] requested (each of which is not necessarily
+ supported by the server though). The connection is torn down either on
+ normal return or if the function [f] throws an exception. *)
diff --git a/lib/utils.ml b/lib/utils.ml
index c18a467cb57c..86967f342e6e 100644
--- a/lib/utils.ml
+++ b/lib/utils.ml
@@ -164,3 +164,15 @@ let rec wait_for_file filename timeout =
)
let metaversion = Digest.to_hex (Digest.string Config.package_version_full)
+
+let with_nbd_connect_unix ~socket ~meta_contexts ~f =
+ let nbd = NBD.create () in
+ protect
+ ~f:(fun () ->
+ List.iter (NBD.add_meta_context nbd) meta_contexts;
+ NBD.connect_unix nbd socket;
+ protect
+ ~f:(fun () -> f nbd)
+ ~finally:(fun () -> NBD.shutdown nbd)
+ )
+ ~finally:(fun () -> NBD.close nbd)
--
2.19.1.3.g30247aa5d201