Skip to content

Commit

Permalink
lib/utils: add the "Utils.with_nbd_connect_unix" helper function
Browse files Browse the repository at this point in the history
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@redhat.com>
Message-Id: <20211210113537.10907-2-lersek@redhat.com>
Acked-by: Richard W.M. Jones <rjones@redhat.com>
  • Loading branch information
lersek committed Dec 10, 2021
1 parent 9bb0e7f commit b4a8ccf
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/Makefile.am
Expand Up @@ -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 \
Expand Down
12 changes: 12 additions & 0 deletions lib/utils.ml
Expand Up @@ -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)
10 changes: 10 additions & 0 deletions lib/utils.mli
Expand Up @@ -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. *)

0 comments on commit b4a8ccf

Please sign in to comment.