4976497570124bd2b6e5af3687191f375e58149d
[virt-df.git] / virt-df / virt_df_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 Virt_df_gettext.Gettext
27 open Virt_df
28
29 open Virt_df_lvm2_metadata
30
31 let plugin_name = "LVM2"
32
33 let sector_size = 512
34 let sector_size64 = 512L
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 0L
54       (List.map (fun (_, end_extent, _, _) -> end_extent) segments) in
55   let size = size_in_extents *^ extent_size in
56 object
57   inherit device
58   method name = name
59   method size = size
60
61   (* Read method checks which segment the request lies inside and
62    * maps it to the underlying device.  If there is no mapping then
63    * we have to return an error.
64    *
65    * The request must lie inside a single extent, otherwise this is
66    * also an error (XXX - should lift this restriction, however default
67    * extent size is 4 MB so we probably won't hit this very often).
68    *)
69   method read offset len =
70     let offset_in_extents = offset /^ extent_size in
71
72     (* Check we don't cross an extent boundary. *)
73     if (offset +^ Int64.of_int (len-1)) /^ extent_size <> offset_in_extents
74     then invalid_arg "linear_map_device: request crosses extent boundary";
75
76     if offset_in_extents < 0L || offset_in_extents >= size_in_extents then
77       invalid_arg "linear_map_device: read outside device";
78
79     let rec loop = function
80       | [] ->
81           invalid_arg "linear_map_device: offset not mapped"
82       | (start_extent, end_extent, dev, pvoffset) :: rest ->
83           if start_extent <= offset_in_extents &&
84              offset_in_extents < end_extent
85           then dev#read (offset +^ pvoffset *^ extent_size) len
86           else loop rest
87     in
88     loop segments
89 end
90
91 (*----------------------------------------------------------------------*)
92 (* Probe to see if it's an LVM2 PV. *)
93 let rec probe_pv lvm_plugin_id dev =
94   try
95     let uuid, _ = read_pv_label dev in
96     if !debug then
97       eprintf "LVM2 detected PV UUID %s\n%!" uuid;
98     { lvm_plugin_id = lvm_plugin_id; pv_uuid = uuid }
99   with exn ->
100     if !debug then prerr_endline (Printexc.to_string exn);
101     raise Not_found
102
103 and read_pv_label dev =
104   (* Load the first 8 sectors.  I found by experimentation that
105    * the second sector contains the header ("LABELONE" etc) and
106    * the nineth sector contains some additional information about
107    * the location of the current metadata.
108    *)
109   let bits = dev#read_bitstring 0L (9 * sector_size) in
110
111   (*Bitmatch.hexdump_bitstring stdout bits;*)
112
113   bitmatch bits with
114   | {
115       (* sector 0 *)
116       sector0 : sector_size*8 : bitstring;
117
118       (* sector 1 *)
119       "LABELONE" : 64 : string;         (* "LABELONE" *)
120       _ : 128 : bitstring;              (* Seems to contain something. *)
121       "LVM2 001" : 64 : string;         (* "LVM2 001" *)
122       uuid : 256 : string;              (* UUID *)
123       endsect : (sector_size-64)*8 : bitstring; (* to end of second sector *)
124
125       (* sectors 2-7 *)
126       sectors234567 : sector_size*8 * 6 : bitstring;
127
128       (* sector 8 *)
129       _ : 320 : bitstring;              (* start of sector 8 *)
130       metadata_offset : 32 : littleendian; (* metadata offset *)
131       _ : 32 : bitstring;
132       metadata_length : 32 : littleendian (* length of metadata (bytes) *)
133     } ->
134
135       (* Metadata offset is relative to end of PV label. *)
136       let metadata_offset = metadata_offset +* 0x1000_l in
137       (* Metadata length appears to include the trailing \000 which
138        * we don't want.
139        *)
140       let metadata_length = metadata_length -* 1_l in
141
142       let metadata = read_metadata dev metadata_offset metadata_length in
143
144       uuid, metadata
145
146   | { _ } ->
147       invalid_arg
148         (sprintf "LVM2: read_pv_label: %s: not an LVM2 physical volume"
149            dev#name)
150
151 and read_metadata dev offset32 len32 =
152   if !debug then
153     eprintf "metadata: offset 0x%lx len %ld bytes\n%!" offset32 len32;
154
155   (* Check the offset and length are sensible. *)
156   let offset64 =
157     if offset32 <= Int32.max_int then Int64.of_int32 offset32
158     else invalid_arg "LVM2: read_metadata: metadata offset too large" in
159   let len64 =
160     if len32 <= 2_147_483_647_l then Int64.of_int32 len32
161     else invalid_arg "LVM2: read_metadata: metadata length too large" in
162
163   if offset64 <= 0x1200L || offset64 >= dev#size
164     || len64 <= 0L || offset64 +^ len64 >= dev#size then
165       invalid_arg "LVM2: read_metadata: bad metadata offset or length";
166
167   (* If it is outside the disk boundaries, this will throw an exception,
168    * otherwise it will read and return the metadata string.
169    *)
170   dev#read offset64 (Int64.to_int len64)
171
172 (*----------------------------------------------------------------------*)
173 (* We are passed a list of devices which we previously identified
174  * as PVs belonging to us.  From these produce a list of all LVs
175  * (as devices) and return them.  Note that we don't try to detect
176  * what is on these LVs - that will be done in the main code.
177  *)
178 let rec list_lvs devs =
179   (* Read the UUID and metadata (again) from each device to end up with
180    * an assoc list of PVs, keyed on the UUID.
181    *)
182   let pvs = List.map (
183     fun dev ->
184       let uuid, metadata = read_pv_label dev in
185       (uuid, (metadata, dev))
186   ) devs in
187
188   (* Parse the metadata using the external lexer/parser. *)
189   let pvs = List.map (
190     fun (uuid, (metadata, dev)) ->
191       uuid, (Virt_df_lvm2_lexer.parse_lvm2_metadata_from_string metadata,
192              dev)
193   ) pvs in
194
195   (* Print the parsed metadata. *)
196   if !debug then
197     List.iter (
198       fun (uuid, (metadata, dev)) ->
199         eprintf "metadata for PV UUID %s on %s:\n" uuid dev#name;
200         output_metadata stderr metadata
201     ) pvs;
202
203   (* Scan for volume groups.  The first entry in the metadata
204    * appears to be the volume group name.  This gives us a
205    * list of VGs and the metadata for each underlying PV.
206    *)
207   let vgnames =
208     List.filter_map (
209       function
210       | pvuuid, (((vgname, Metadata vgmeta) :: _), dev) ->
211           Some (vgname, (pvuuid, vgmeta))
212       | _ -> None
213     ) pvs in
214
215   let cmp ((a:string),_) ((b:string),_) = compare a b in
216   let vgnames = List.sort ~cmp vgnames in
217   let vgs = group_by vgnames in
218
219   (* Note that the metadata is supposed to be duplicated
220    * identically across all PVs (for redundancy purposes).
221    * In theory we should check this and use the 'seqno'
222    * field to find the latest metadata if it doesn't match,
223    * but in fact we don't check this.
224    *)
225   let vgs = List.map (
226     fun (vgname, metas) ->
227       let pvuuids = List.map fst metas in
228       let _, vgmeta = List.hd metas in (* just pick any metadata *)
229       vgname, (pvuuids, vgmeta)) vgs in
230
231   (* Print the VGs. *)
232   if !debug then
233     List.iter (
234       fun (vgname, (pvuuids, vgmeta)) ->
235         eprintf "VG %s is on PVs: %s\n%!" vgname (String.concat "," pvuuids)
236     ) vgs;
237
238   (* Some useful getter functions.  If these can't get a value
239    * from the metadata or if the type is wrong they raise Not_found.
240    *)
241   let rec get_int64 field meta =
242     match List.assoc field meta with
243     | Int i -> i
244     | _ -> raise Not_found
245   and get_int field meta min max =
246     match List.assoc field meta with
247     | Int i when Int64.of_int min <= i && i <= Int64.of_int max ->
248         Int64.to_int i
249     | _ -> raise Not_found
250   and get_string field meta =
251     match List.assoc field meta with
252     | String s -> s
253     | _ -> raise Not_found
254   and get_meta field meta =
255     match List.assoc field meta with
256     | Metadata md -> md
257     | _ -> raise Not_found
258   and get_stripes field meta =          (* List of (string,int) pairs. *)
259     match List.assoc field meta with
260     | List xs ->
261         let rec loop = function
262           | [] -> []
263           | String pvname :: Int offset :: xs ->
264               (pvname, offset) :: loop xs
265           | _ -> raise Not_found
266         in
267         loop xs
268     | _ -> raise Not_found
269   in
270
271   (* The volume groups refer to the physical volumes using their
272    * own naming system ("pv0", "pv1", etc.) instead of PV UUIDs.
273    *
274    * Each PV also has a start (in sectors) & count (in extents)
275    * of the writable area (the bit after the superblock and metadata)
276    * which normally starts at sector 384.
277    *
278    * Create a PV device (simple offset + size) and a map from PV
279    * names to these devices.
280    *)
281   let vgs = List.map (
282     fun (vgname, (pvuuids, vgmeta)) ->
283       let pvdevs, extent_size =
284         try
285           (* NB: extent_size is in sectors here - we convert to bytes. *)
286           let extent_size = get_int "extent_size" vgmeta 0 (1024*1024) in
287           let extent_size = Int64.of_int extent_size *^ sector_size64 in
288
289           (* Get the physical_volumes section of the metadata. *)
290           let pvdevs = get_meta "physical_volumes" vgmeta in
291
292           List.filter_map (
293             function
294             | (pvname, Metadata meta) ->
295                 (* Get the UUID. *)
296                 let pvuuid = get_string "id" meta in
297                 let pvuuid = canonical_uuid pvuuid in
298
299                 (* Get the underlying physical device. *)
300                 let _, dev = List.assoc pvuuid pvs in
301
302                 (* Construct a PV device. *)
303                 let pe_start = get_int64 "pe_start" meta in
304                 let pe_start = pe_start *^ sector_size64 in
305                 let pe_count = get_int64 "pe_count" meta in
306                 let pe_count = pe_count *^ extent_size in
307                 let pvdev = new offset_device pvuuid pe_start pe_count dev in
308
309                 Some (pvname, pvdev)
310             | _ ->
311                 None
312           ) pvdevs, extent_size
313         with
314           (* Something went wrong - just return an empty map. *)
315           Not_found -> [], 0L in
316       (vgname, (pvuuids, vgmeta, pvdevs, extent_size))
317   ) vgs in
318
319   (* Scan for logical volumes.  Each VG contains several LVs.
320    * This gives us a list of LVs within each VG (hence extends
321    * the vgs variable).
322    *)
323   let vgs = List.map (
324     fun (vgname, (pvuuids, vgmeta, pvdevs, extent_size)) ->
325       let lvs =
326         try
327           let lvs = get_meta "logical_volumes" vgmeta in
328           let lvs = List.filter_map (
329             function
330             | lvname, Metadata lvmeta ->
331                 (try
332                    let segment_count = get_int "segment_count" lvmeta 0 1024 in
333
334                    (* Get the segments for this LV. *)
335                    let segments = range 1 (segment_count+1) in
336                    let segments =
337                      List.map
338                        (fun i -> get_meta ("segment" ^ string_of_int i) lvmeta)
339                        segments in
340
341                    let segments =
342                      List.map (
343                        fun segmeta ->
344                          let start_extent =
345                            get_int64 "start_extent" segmeta in
346                          let extent_count =
347                            get_int64 "extent_count" segmeta in
348                          let segtype = get_string "type" segmeta in
349
350                          (* Can only handle striped segments at the
351                           * moment. XXX
352                           *)
353                          if segtype <> "striped" then raise Not_found;
354
355                          let stripe_count =
356                            get_int "stripe_count" segmeta 0 1024 in
357                          let stripes = get_stripes "stripes" segmeta in
358
359                          if List.length stripes <> stripe_count then
360                            raise Not_found;
361
362                          (* Can only handle linear striped segments at
363                           * the moment. XXX
364                           *)
365                          if stripe_count <> 1 then raise Not_found;
366                          let pvname, pvoffset = List.hd stripes in
367
368                          (start_extent, extent_count, pvname, pvoffset)
369                      ) segments in
370
371                    Some (lvname, segments)
372                  with
373                    (* Something went wrong with segments - omit this LV. *)
374                    Not_found -> None)
375             | _ -> None
376           ) lvs in
377
378           lvs
379         with
380           Not_found ->
381             (* Something went wrong - assume no LVs found. *)
382             [] in
383       (vgname, (pvuuids, vgmeta, pvdevs, extent_size, lvs))
384   ) vgs in
385
386   (* Print the LVs. *)
387   if !debug then (
388     List.iter (
389       fun (vgname, (pvuuids, vgmeta, pvdevs, extent_size, lvs)) ->
390         eprintf "VG %s: (extent_size = %Ld bytes)\n" vgname extent_size;
391         List.iter (
392           fun (lvname, segments) ->
393             eprintf "  %s/%s:\n" vgname lvname;
394             List.iter (
395               fun (start_extent, extent_count, pvname, pvoffset) ->
396                 eprintf "    start %Ld count %Ld at %s:%Ld\n"
397                   start_extent extent_count pvname 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
433
434 (*----------------------------------------------------------------------*)
435 (* Register with main code. *)
436 let () =
437   lvm_type_register plugin_name probe_pv list_lvs