ea127cb3972afbfb97507f2af98585fe20738342
[virt-df.git] / lib / diskimage_lvm2.ml
1 (* 'df' command for virtual domains.
2
3    (C) Copyright 2007 Richard W.M. Jones, Red Hat Inc.
4    http://libvirt.org/
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20    Support for LVM2 PVs.
21 *)
22
23 open Printf
24 open ExtList
25
26 open Diskimage_utils
27 open Diskimage_lvm2_metadata
28
29 open Int63.Operators
30
31 let plugin_id = "LVM2"
32
33 let sector_size_int = 512
34 let sector_size = ~^sector_size_int
35
36 (*----------------------------------------------------------------------*)
37 (* Block device which can do linear maps, same as the kernel dm-linear.c *)
38 class linear_map_device name extent_size segments =
39   (* The segments are passed containing (start_extent, extent_count, ...)
40    * but it's easier to deal with (start_extent, end_extent, ...) so
41    * rewrite them.
42    *)
43   let segments = List.map
44     (fun (start_extent, extent_count, dev, pvoffset) ->
45        (start_extent, start_extent +^ extent_count, dev, pvoffset)
46     ) segments in
47
48   (* Calculate the size of the device (in bytes).  Note that because
49    * of the random nature of the mapping this doesn't imply that we can
50    * satisfy any read request up to the full size.
51    *)
52   let size_in_extents =
53     List.fold_left max ~^0
54       (List.map (fun (_, end_extent, _, _) -> end_extent) segments) in
55   let size = size_in_extents *^ extent_size in
56 object (self)
57   inherit device
58   method name = name
59   method size = size
60
61   (* The natural blocksize for LVM devices is the extent size.
62    * NB. Throws a runtime exception if the extent size is bigger
63    * than an int (only likely to matter on 32 bit).
64    *)
65   method blocksize = extent_size
66
67   (* Map block (extent) i to the underlying device. *)
68   method mapblock i =
69     if i < ~^0 || i >= size_in_extents then
70       invalid_arg "linear_map_device: read outside device";
71
72     let rec loop = function
73       | [] ->
74           []
75       | (start_extent, end_extent, dev, pvoffset) :: rest ->
76           if start_extent <= i && i < end_extent then
77             [dev, (pvoffset +^ i) *^ extent_size]
78           else
79             loop rest
80     in
81     loop segments
82
83   (* NB. Use the superclass #read method. *)
84 end
85
86 (*----------------------------------------------------------------------*)
87 (* Probe to see if it's an LVM2 PV. *)
88 let rec probe lvm_plugin_id dev =
89   try
90     let uuid, _ = read_pv_label dev in
91     if !debug then
92       eprintf "LVM2 detected PV UUID %s\n%!" uuid;
93     { lvm_plugin_id = lvm_plugin_id; pv_uuid = uuid }
94   with exn ->
95     if !debug then prerr_endline (Printexc.to_string exn);
96     raise Not_found
97
98 and read_pv_label dev =
99   (* Load the first 8 sectors.  I found by experimentation that
100    * the second sector contains the header ("LABELONE" etc) and
101    * the nineth sector contains some additional information about
102    * the location of the current metadata.
103    *)
104   let bits = dev#read_bitstring ~^0 (~^9 *^ sector_size) in
105
106   (*Bitmatch.hexdump_bitstring stdout bits;*)
107
108   bitmatch bits with
109   | {
110       (* sector 0 *)
111       sector0 : sector_size_int*8 : bitstring;
112
113       (* sector 1 *)
114       "LABELONE" : 64 : string;         (* "LABELONE" *)
115       _ : 128 : bitstring;              (* Seems to contain something. *)
116       "LVM2 001" : 64 : string;         (* "LVM2 001" *)
117       uuid : 256 : string;              (* UUID *)
118       endsect : (sector_size_int-64)*8 : bitstring;(* to end of second sector *)
119
120       (* sectors 2-7 *)
121       sectors234567 : sector_size_int*8 * 6 : bitstring;
122
123       (* sector 8 *)
124       _ : 320 : bitstring;              (* start of sector 8 *)
125       metadata_offset : 32 : littleendian; (* metadata offset *)
126       _ : 32 : bitstring;
127       metadata_length : 32 : littleendian (* length of metadata (bytes) *)
128     } ->
129
130       (* Metadata offset is relative to end of PV label. *)
131       let metadata_offset = Int63.of_int32 metadata_offset +^ ~^0x1000 in
132       (* Metadata length appears to include the trailing \000 which
133        * we don't want.
134        *)
135       let metadata_length = Int63.of_int32 metadata_length -^ ~^1 in
136
137       let metadata = read_metadata dev metadata_offset metadata_length in
138
139       uuid, metadata
140
141   | { _ } ->
142       invalid_arg
143         (sprintf "LVM2: read_pv_label: %s: not an LVM2 physical volume"
144            dev#name)
145
146 and read_metadata dev offset len =
147   if !debug then
148     eprintf "metadata: offset %s len %s bytes\n%!"
149       (Int63.to_string offset) (Int63.to_string len);
150
151   (* Check the offset and length are sensible. *)
152   if offset <= ~^0x1200 || offset >= dev#size
153     || len <= ~^0 || offset +^ len >= dev#size then
154       invalid_arg "LVM2: read_metadata: bad metadata offset or length";
155
156   (* If it is outside the disk boundaries, this will throw an exception,
157    * otherwise it will read and return the metadata string.
158    *)
159   dev#read offset len
160
161 (*----------------------------------------------------------------------*)
162 (* We are passed a list of devices which we previously identified
163  * as PVs belonging to us.  From these produce a list of all LVs
164  * (as devices) and return them.  Note that we don't try to detect
165  * what is on these LVs - that will be done in the main code.
166  *)
167 let rec list devs =
168   (* Read the UUID and metadata (again) from each device to end up with
169    * an assoc list of PVs, keyed on the UUID.
170    *)
171   let pvs = List.map (
172     fun dev ->
173       let uuid, metadata = read_pv_label dev in
174       (uuid, (metadata, dev))
175   ) devs in
176
177   (* Parse the metadata using the external lexer/parser. *)
178   let pvs = List.map (
179     fun (uuid, (metadata, dev)) ->
180       uuid, (Diskimage_lvm2_lexer.parse_lvm2_metadata_from_string metadata,
181              dev)
182   ) pvs in
183
184   (* Print the parsed metadata. *)
185   if !debug then
186     List.iter (
187       fun (uuid, (metadata, dev)) ->
188         eprintf "metadata for PV UUID %s on %s:\n" uuid dev#name;
189         output_metadata stderr metadata
190     ) pvs;
191
192   (* Scan for volume groups.  The first entry in the metadata
193    * appears to be the volume group name.  This gives us a
194    * list of VGs and the metadata for each underlying PV.
195    *)
196   let vgnames =
197     List.filter_map (
198       function
199       | pvuuid, (((vgname, Metadata vgmeta) :: _), dev) ->
200           Some (vgname, (pvuuid, vgmeta))
201       | _ -> None
202     ) pvs in
203
204   let cmp ((a:string),_) ((b:string),_) = compare a b in
205   let vgnames = List.sort ~cmp vgnames in
206   let vgs = group_by vgnames in
207
208   (* Note that the metadata is supposed to be duplicated
209    * identically across all PVs (for redundancy purposes).
210    * In theory we should check this and use the 'seqno'
211    * field to find the latest metadata if it doesn't match,
212    * but in fact we don't check this.
213    *)
214   let vgs = List.map (
215     fun (vgname, metas) ->
216       let pvuuids = List.map fst metas in
217       let _, vgmeta = List.hd metas in (* just pick any metadata *)
218       vgname, (pvuuids, vgmeta)) vgs in
219
220   (* Print the VGs. *)
221   if !debug then
222     List.iter (
223       fun (vgname, (pvuuids, vgmeta)) ->
224         eprintf "VG %s is on PVs: %s\n%!" vgname (String.concat "," pvuuids)
225     ) vgs;
226
227   (* Some useful getter functions.  If these can't get a value
228    * from the metadata or if the type is wrong they raise Not_found.
229    *)
230   let rec get_int63 field meta =
231     match List.assoc field meta with
232     | Int i -> i
233     | _ -> raise Not_found
234   and get_int_bounded field meta max =
235     match List.assoc field meta with
236     | Int i when i >= ~^0 && i <= Int63.of_int max -> Int63.to_int i
237     | _ -> raise Not_found
238   and get_string field meta =
239     match List.assoc field meta with
240     | String s -> s
241     | _ -> raise Not_found
242   and get_meta field meta =
243     match List.assoc field meta with
244     | Metadata md -> md
245     | _ -> raise Not_found
246   and get_stripes field meta =          (* List of (string,int) pairs. *)
247     match List.assoc field meta with
248     | List xs ->
249         let rec loop = function
250           | [] -> []
251           | String pvname :: Int offset :: xs ->
252               (pvname, offset) :: loop xs
253           | _ -> raise Not_found
254         in
255         loop xs
256     | _ -> raise Not_found
257   in
258
259   (* The volume groups refer to the physical volumes using their
260    * own naming system ("pv0", "pv1", etc.) instead of PV UUIDs.
261    *
262    * Each PV also has a start (in sectors) & count (in extents)
263    * of the writable area (the bit after the superblock and metadata)
264    * which normally starts at sector 384.
265    *
266    * Create a PV device (simple offset + size) and a map from PV
267    * names to these devices.
268    *)
269   let vgs = List.map (
270     fun (vgname, (pvuuids, vgmeta)) ->
271       let pvdevs, extent_size =
272         try
273           (* NB: extent_size is in sectors here - we convert to bytes. *)
274           let extent_size =
275             get_int_bounded "extent_size" vgmeta (1024*1024) in
276           let extent_size = Int63.of_int extent_size in
277           let extent_size = extent_size *^ sector_size in
278
279           (* Get the physical_volumes section of the metadata. *)
280           let pvdevs = get_meta "physical_volumes" vgmeta in
281
282           List.filter_map (
283             function
284             | (pvname, Metadata meta) ->
285                 (* Get the UUID. *)
286                 let pvuuid = get_string "id" meta in
287                 let pvuuid = canonical_uuid pvuuid in
288
289                 (* Get the underlying physical device. *)
290                 let _, dev = List.assoc pvuuid pvs in
291
292                 (* Construct a PV device. *)
293                 let pe_start = get_int63 "pe_start" meta in
294                 let pe_start = pe_start *^ sector_size in
295                 let pe_count = get_int63 "pe_count" meta in
296                 let pe_count = pe_count *^ extent_size in
297                 let pvdev =
298                   new offset_device
299                     pvuuid (* name *)
300                     pe_start pe_count (* start, size in bytes *)
301                     (* don't really have a natural block size ... *)
302                     extent_size
303                     dev (* underlying device *) in
304
305                 Some (pvname, pvdev)
306             | _ ->
307                 None
308           ) pvdevs, extent_size
309         with
310           (* Something went wrong - just return an empty map. *)
311           Not_found -> [], ~^0 in
312       (vgname, (pvuuids, vgmeta, pvdevs, extent_size))
313   ) vgs in
314
315   (* Scan for logical volumes.  Each VG contains several LVs.
316    * This gives us a list of LVs within each VG (hence extends
317    * the vgs variable).
318    *)
319   let vgs = List.map (
320     fun (vgname, (pvuuids, vgmeta, pvdevs, extent_size)) ->
321       let lvs =
322         try
323           let lvs = get_meta "logical_volumes" vgmeta in
324           let lvs = List.filter_map (
325             function
326             | lvname, Metadata lvmeta ->
327                 (try
328                    let segment_count =
329                      get_int_bounded "segment_count" lvmeta 1024 in
330
331                    (* Get the segments for this LV. *)
332                    let segments = range 1 (segment_count+1) in
333                    let segments =
334                      List.map
335                        (fun i -> get_meta ("segment" ^ string_of_int i) lvmeta)
336                        segments in
337
338                    let segments =
339                      List.map (
340                        fun segmeta ->
341                          let start_extent =
342                            get_int63 "start_extent" segmeta in
343                          let extent_count =
344                            get_int63 "extent_count" segmeta in
345                          let segtype = get_string "type" segmeta in
346
347                          (* Can only handle striped segments at the
348                           * moment. XXX
349                           *)
350                          if segtype <> "striped" then raise Not_found;
351
352                          let stripe_count =
353                            get_int_bounded "stripe_count" segmeta 1024 in
354                          let stripes = get_stripes "stripes" segmeta in
355
356                          if List.length stripes <> stripe_count then
357                            raise Not_found;
358
359                          (* Can only handle linear striped segments at
360                           * the moment. XXX
361                           *)
362                          if stripe_count <> 1 then raise Not_found;
363                          let pvname, pvoffset = List.hd stripes in
364
365                          (start_extent, extent_count, pvname, pvoffset)
366                      ) segments in
367
368                    Some (lvname, segments)
369                  with
370                    (* Something went wrong with segments - omit this LV. *)
371                    Not_found -> None)
372             | _ -> None
373           ) lvs in
374
375           lvs
376         with
377           Not_found ->
378             (* Something went wrong - assume no LVs found. *)
379             [] in
380       (vgname, (pvuuids, vgmeta, pvdevs, extent_size, lvs))
381   ) vgs in
382
383   (* Print the LVs. *)
384   if !debug then (
385     List.iter (
386       fun (vgname, (pvuuids, vgmeta, pvdevs, extent_size, lvs)) ->
387         eprintf "VG %s: (extent_size = %s bytes)\n" vgname
388           (Int63.to_string extent_size);
389         List.iter (
390           fun (lvname, segments) ->
391             eprintf "  %s/%s:\n" vgname lvname;
392             List.iter (
393               fun (start_extent, extent_count, pvname, pvoffset) ->
394                 eprintf "    start %s count %s at %s:%s\n"
395                   (Int63.to_string start_extent)
396                   (Int63.to_string extent_count)
397                   pvname (Int63.to_string pvoffset)
398             ) segments
399         ) lvs
400     ) vgs;
401     flush stderr
402   );
403
404   (* Finally we can set up devices for the LVs. *)
405   let lvs =
406     List.map (
407       fun (vgname, (pvuuid, vgmeta, pvdevs, extent_size, lvs)) ->
408         try
409           List.map (
410             fun (lvname, segments) ->
411               let name = vgname ^ "/" ^ lvname in
412               let segments = List.map (
413                 fun (start_extent, extent_count, pvname, pvoffset) ->
414                   (* Get the PV device. *)
415                   let pvdev = List.assoc pvname pvdevs in
416
417                   (* Extents                 mapped to:             *)
418                   (start_extent, extent_count,          pvdev, pvoffset)
419               ) segments in
420
421               (* Create a linear mapping device. *)
422               let lv_dev = new linear_map_device name extent_size segments in
423
424               { lv_dev = lv_dev }
425           ) lvs
426         with
427           Not_found -> []
428     ) vgs in
429   let lvs = List.concat lvs in
430
431   (* Return the list of LV devices. *)
432   lvs