1
0
mirror of git://sourceware.org/git/lvm2.git synced 2025-08-16 05:49:28 +03:00

Compare commits

...

2673 Commits

Author SHA1 Message Date
08ce545449 pre-release 2017-06-28 16:38:46 +01:00
7ba6896962 command: we don't have all standard macros
So just quite warning
2017-06-28 15:05:16 +02:00
a533892cd3 coverity: checked_return of close
Check (or make quiet) close() ret code.
NOTE: there is another duplicated code of daemonize function which
should be converted to libdaemon.
2017-06-28 14:42:11 +02:00
b90014addc man: regenerate 2017-06-27 15:47:00 +01:00
7f1ec681d6 log: fix message prefix truncation
Restore the 29-character prefix limit that commit
e907535ab9 ("coverity: use better
function") accidentally reduced to 28 characters.
2017-06-27 12:41:59 +01:00
3fe67217d4 coverity: model few more functions
Reduce amount of FP.
2017-06-27 12:17:16 +02:00
5ff6260071 coverity: move initilization of count variable
Make code more understandble for Coverity, so it sees connection
between 'extents' and 'count' and in fact code is more readable.
2017-06-27 12:16:33 +02:00
0349b6d889 coverity: drop unneeded assigns 2017-06-27 12:15:42 +02:00
419e8284c8 coverity: validate length of renaming path
Make sure path fits into buffer on stack.
2017-06-27 12:15:42 +02:00
8e790702f1 coverity: check malloc results 2017-06-27 12:15:42 +02:00
e907535ab9 coverity: use better function 2017-06-27 12:15:42 +02:00
e9c60f874e coverity: extra check for find_pool_seg
find_pool_seg may return NULL in some internal error stats.
Handle it explicitely.
2017-06-27 12:15:15 +02:00
b939ddf80c debug: more display_lvname usage 2017-06-27 08:28:36 +02:00
275fc2d45b coverity: validate retval from get_only_segment_using_this_lv 2017-06-27 00:27:36 +02:00
664e947726 coverity: add some error path for failed allocs
Coverity reports some unchecked allocations.
2017-06-27 00:27:36 +02:00
72c5598658 debug: use display_lvname 2017-06-27 00:27:36 +02:00
a567ec65a9 debug: fix error path
Coverity:
log_error may have dereference NULL pointer - use directly
segtype string name.
2017-06-27 00:27:36 +02:00
d444accdbf debug: fail in backup is not traced nor error 2017-06-27 00:27:36 +02:00
c3e0ef1a5e debug: tracing error path 2017-06-27 00:27:36 +02:00
c440bb0742 debug: check for fail in id validation 2017-06-27 00:27:36 +02:00
3e331c8e68 cleanup: remove unused code 2017-06-27 00:27:25 +02:00
ab6f4649a0 dev_manager: add missing validation for usable target_name
Coverity shown path where target_name == NULL would be dereferenced.
2017-06-27 00:27:25 +02:00
b1e21cf9ed raid: fix write_commit_backup
With commit 41c10034aa we actually
do require LV to be used with _vg_write_lv_suspend_commit_backup().

So write a proper separte single wrapper for write && commit && backup.
2017-06-27 00:27:25 +02:00
52f4042f1a cmdline: fix missing NULL at end of array of args
lvm_run needs to place NULL as the last element into argv[].
Otherwise we get:

Conditional jump or move depends on uninitialised value(s)
 _command_required_pos_matches (lvmcmdline.c:1443)
 _find_command (lvmcmdline.c:1610)
 lvm_run_command (lvmcmdline.c:2770)
 lvm2_run (lvmcmdlib.c:91)
2017-06-26 20:07:21 +02:00
4e4067dd94 libdm: fix initialization of head for reused structure
Dmeventd reuses  'dm_task' struct for some STATUS operation, but due to
missing reinitization of dm_task target list, it has caused misprocesing
of recieved events as the parsed target has been simply added to the
list of existing status and cause multiple actions being called for
single event.
2017-06-26 19:45:11 +02:00
0cc49bda15 tests: show more debug info
Helpful for analysis (revert later).
2017-06-24 23:02:42 +02:00
1b9bf5ce9e tests: slightly longer delay
Try to avoid race with slightly longer delay.
2017-06-24 22:58:08 +02:00
c465ca6a3a raid: allow more sync action for extraction
Since we discovered status reporting from 'md' goes from large set
of weird states we can't just decided based on this word.
So let it pass for rebuild and idle as well
and check for health devices afterwards.
2017-06-24 22:28:25 +02:00
cac9e0b681 tests: correct percent values are reported 2017-06-24 17:44:42 +02:00
cefb8bcfc4 tests: unit test for percent printing 2017-06-24 17:44:42 +02:00
1bd4b0059b cleanup: use display_percent
Replace occurence of %.2f with call of display_percent function.
2017-06-24 17:44:42 +02:00
07eec06f5d display: add display_percent function
Add universal function to print dm_percent_t values via single
code path.

TODO: extend with configurale precision of printed values.
2017-06-24 17:44:42 +02:00
feed61f3fa libdm: use rounded float for percent print
Use new added  dm_percent_to_round_float to enhance print
of percentage values.
2017-06-24 17:44:42 +02:00
2ef8da61eb libdm: implement dm_percent_to_round_float
Add function to adjust printing of percent values in better way.
Rounding here is going along following rules:

0% & 100% are always clearly reported with  .0 decimal points.

Values slightly above 0% we make sure a nearest bigger
non zero value with given precission is printed
(i.e. 0.01  for  %.2f  will be shown)

For values closely approaching 100% we again detect and adjust value
that is less then 100 when printed.
(i.e. 99.99  for %.2f will be shown).

For other values we are leaving them with standard rounding mechanism
since we care mainly about corner values 0 & 100 which need to be
printed precisely.
2017-06-24 17:44:40 +02:00
0016b79c8b dmeventd: improve more raid status reporting
When we want to report primary leg failure, check for intial 'a',
since otherwice 'Aa idle' is normally visible.

Also reset array of bit flags marking dead devices, once
plugin detects raid is in sync.
2017-06-24 00:06:12 +02:00
2a50a28f3e tests: use allocate policy in raid test 2017-06-23 23:32:44 +02:00
1598bf154e tests: add transient failure test
Check raid  repairs still 'present', but failed device.

TODO: tests needs more checking about repair actually doing its work.
2017-06-23 23:32:44 +02:00
f48d1bf147 tests: require also no 'a' for in-sync
Raid easily reports  'idle' with 'a', so in this case
we will not report in-sync.
2017-06-23 23:32:44 +02:00
653bdedb83 raid: plugin does not to use --config
Functionality of ignore suspend devices is already granted by:

lvm2_disable_dmeventd_monitoring() -> init_run_by_dmeventd() ->
init_ignore_suspended_devices().

In fact plugins should never use --config because it has
some unpleasant technical issues.
2017-06-23 23:32:40 +02:00
2b18be87aa raid: recognize transient failed raid leg
When raid leg rimage device is marked as 'D'ead by mdcore,
lvm2 was not able to replace such device with allocate policy,
as device has not appared as missing.

Add detection of transiently failing devices.
2017-06-23 23:27:07 +02:00
535f7209d2 tests: request 1.12 for reshaping raid
We will need  1.12 as the kernel needs some mandatory md fixes,
otherwise random freezes may appear.
2017-06-23 18:44:01 +02:00
d0c97b4401 tests: handle su login difference
Workaround case, where it matters if 'su' was user with '-' or without.
2017-06-23 18:44:01 +02:00
cc03a872c0 cleanup: update messages 2017-06-23 18:44:01 +02:00
a7c7d53543 debug: add missing internal error message
Do not just 'return_0'  log error would need to be shown.
2017-06-23 18:44:01 +02:00
1bdcd156fd cache: restore origin only reload
Basically reverting commit 58a9f88b8c.
We can use origin_only  in case we are snapshot's origin,
as we do support this stack.

So when we are 'uncaching'  origin+snaps - we do need to reload only
origin and we do not need to play with snaps.
2017-06-23 18:44:01 +02:00
63ecbcd1b7 raid: switch message to verbose
As this is not 'error' resulting query, decrease reported level.
2017-06-23 18:44:01 +02:00
6d30350dd1 raid: improving messages for regionsize change
Handle change of 'region size' better and follow also standard rule
if the command can't success (i.e. size is already same) we return
error for all such cases.

Also log_pring more info about adjusted value (just like we
do for rounding)

Also avoid keep pointers on 'display_*' values - they are in
ringbuffer for immediate use - not to be kept across multiple calls
(as they could be already overwritten by later calls) - so dropped
seg_region_size_str
2017-06-23 18:44:00 +02:00
cb2c2484b9 tests: flushing of cache is abortable 2017-06-22 20:17:20 +02:00
7d5afcc0cb tests: check lvdisplay for cache works 2017-06-22 20:17:20 +02:00
41c10034aa debug: show message only when origin_only was set 2017-06-22 20:17:20 +02:00
58e075f5fb cache: fix lvdisplay output
Unused cache pool may have lots of fields actually undefined,
so avoid printing them, if they are not specified in metadata.
2017-06-22 20:17:18 +02:00
732928dda8 cache: fix lvdisplay --maps
'lvdisplay -m' tried to go through NULL policy settings,
when such policy was not defined for CachedLV.

Patch is fixing display of cache-pool without defined settings,
as this is now a valid pool and we mostly want users to define
these settings when actually really caching a LV.
2017-06-22 20:15:12 +02:00
58a9f88b8c cache: drop usage of origin_only
Since cache LV can be a stacked device, there is no real reason
trying to use slight optimised tree for origin_only cache reload
(it could be even wrongly implemented in this case).

We can easily go with stardard tree load here.
2017-06-22 20:14:31 +02:00
ca9e6cec61 cache: make syncing abortable by user
When user runs command like 'lvconvert --splitcache' the operation
might be actually either slow or not making any progress in kernel,
so lets give user a chance to abort such operation.

When user press 'Ctrl+C' device table is restored to pre-flushing state.
2017-06-22 20:11:43 +02:00
2df9a78684 mirror: reformat conditional 2017-06-22 00:57:16 +02:00
64fac77e8a raid: fix segfault
Add missing else clause
(already missing in initial commit fe18e5e77a).

Resolves: rhbz1463794
2017-06-22 00:49:00 +02:00
93fbfa2ed3 tests: lvresize needs --yes 2017-06-21 14:03:29 +02:00
e3f63693a4 lvresize: support passing --yes to fsadm
Since fsadm now needs --yes to pass prompting operations,
we need to pass --yes from  lvresize to fsadm.
2017-06-21 14:03:29 +02:00
48f06005ab raid: update path for repair
Updating path from commit 61980bcf06.

When repair is running, no removing PVS are given so it shall return
success in such case.
2017-06-21 14:00:50 +02:00
5f4cfa7c4a debug: missing traces 2017-06-21 12:36:01 +02:00
07fe64b473 raid: use log_error on error path
Converting log_warn to log_error since error must be logged
when tool returns error.
2017-06-21 12:35:17 +02:00
61980bcf06 raid: report error when specified devices are not contained
lvm2 always return non-zero error code when action cannot happen.
2017-06-21 12:35:17 +02:00
31d153ced0 raid: drop debug code 2017-06-21 12:35:16 +02:00
49fa2bea1c raid: more origin_only updates
Seems the code is multiplied - so keep it consistent for now.

TODO:  drop all uneeded code
2017-06-21 12:35:16 +02:00
1766eaec4b lvconvert: provide better reshape reject message for open RaidLV
On commits
5e611c700b and
601ad1c73f.

Related: rhbz1447812
2017-06-20 19:06:18 +02:00
76314183e2 raid: avoid explicit activation of SubLVs on reshape/takeover
Remove explicit activation of SubLVs and let lv_update_and_reload()
perform the proper (pre-)loading sequencing of tables.
This avoids related callback functions which are removed.

Related: rhbz1448116
Related: rhbz1461526
Related: rhbz1448123
2017-06-20 18:56:45 +02:00
0dfe1bc29d raid: provide clickable URL BZ references 2017-06-20 18:43:26 +02:00
710f51e7f2 tests: test also different lock holder 2017-06-20 18:25:10 +02:00
3d591ac376 tests: avoid double lines
Skip showing same line twice in test's verbose log.
2017-06-20 18:24:52 +02:00
1ea41b6d48 activation: fix usage of origin_only
When lock-holding LV differs from actually request locked LV,
we drop  origin_only flag as it has no use - it'd be applied
on completely different LV.

Example of problem:

Raid is  thin-pool _tdata LV.
Raid run  origin_only locking on stacked device.
As lock holder is discovered thinLV.
Whole origin_only operation is then applied only on thinLV
changing the meaning of whole operation.

NOTE: this patch does not change anything for LV that are
already top-level lock holding LVs (i.e. thinLVs, snahoshots/origins).
2017-06-20 18:23:24 +02:00
5e611c700b lvconvert: check open count to disable reshaping of open RAID LV
Also check LV open count in addition to opening the RaidLV
exclusively as of commit 601ad1c73f.

Related: rhbz1447812
2017-06-20 17:59:10 +02:00
601ad1c73f lvconvert: enhance disable reshaping of open RAID LV
Enhance commit 9e9163618a
to use dev_open_flags/dev_close API.

Related: rhbz1447812
2017-06-20 17:27:58 +02:00
31cd01c9b3 tests: check conversion of thin-pool 2017-06-19 23:30:11 +02:00
19cc03fa52 thin: restore conversion to raid
Since commit  1bc546269a we've disabled
coversion of raid. This however already got fixed, so reenable
commands like:  'lvconvert --type raid1 vg/pool_tdata'.
2017-06-19 23:30:08 +02:00
9e9163618a lvconvert: disable reshaping of open RAID LV
Disable until we have a proper fix for reshape space allocation,
switching it to begin/end of rimages and activation.

Related: rhbz1447812
2017-06-19 22:25:54 +02:00
e1a1c20e95 lvconvert: enhance message
Enhance message introduced by last
commit f342e803ba.

Related: rhbz1439399
2017-06-19 21:40:38 +02:00
f342e803ba lvconvert: disable conversion of RAID LV under snapshot
Disable until we have a proper fix for reshape space allocation,
switching it to begin/end of rimages and activation.

Related: rhbz1439399
2017-06-19 21:08:52 +02:00
fb46175ce7 lvconvert: disable reshaping of RAID LVs in the cluster
Disable until we have a proper fix for reshape space allocation,
switching it to begin/end of rimages and activation in the cluster.

Related: rhbz1448116
Related: rhbz1461526
Related: rhbz1448123
2017-06-19 21:06:53 +02:00
1c212b8a43 fsadm: restore no answer
Commit 1fe4f80e45 in current version
introduced regression for a terminal user, as he could not enter 'n'
as answer. Add missing break for this case (No whats_new).
2017-06-19 12:40:03 +02:00
915d20d0e6 test: New test file for validating kernel status during sync ops
New tests to add checking for '100%' in-sync at start of "recover"
process (it shouldn't happen, but I've seen it before).  Also,
check status over the whole cycle of various sync processes ("resync"
and "recover").
2017-06-16 10:16:07 -05:00
dd866a67f4 tests: use exclusive activation
Conversion needs exlusively active LV for clustered testing.
2017-06-16 17:04:02 +02:00
fbb3bffb22 debug: passing non-raid seg would be internal error 2017-06-16 17:04:02 +02:00
9e96f96a41 cleanup: drop unused parameter 2017-06-16 17:04:02 +02:00
cdb55c19cd cleanup: show what happens when passed prompt
When we show prompt and user passes --yes - we still
do tell user which action is going to happen.
2017-06-16 17:04:02 +02:00
14816222a1 cleanup: improve debug tracing 2017-06-16 17:04:02 +02:00
b7c9ec8a24 cleanup: use 'dm_get_status_raid'
Use single 'dm' call to parse raid status.
(Avoiding multiple parsers - even when we know it's slighly
less efficient).
2017-06-16 17:04:01 +02:00
59d646167f raid: report percent with segtype info
Enhance reporting code, so it does not need to do 'extra' ioctl to
get 'status' of normal raid and provide percentage directly.

When we have 'merging' snapshot into raid origin, we still need to get
this secondary number with extra status call - however, since  'raid'
is always a single segment LV - we may skip 'copy_percent' call as
we directly know the percent and also with better precision.

NOTE: for mirror we still base reported number on the percetage of
transferred extents which might get quite imprecisse if big size
of extent is used while volume itself is smaller as reporting jump
steps are much bigger the actual reported number provides.

2nd.NOTE: raid lvs line report already requires quite a few extra status
calls for the same device - but fix will be need slight code improval.
2017-06-16 17:04:01 +02:00
529dcaf6a3 libdm: workarounds reported raid status info
Current existing kernels reports status sometimes in weird form.

Instead of showing what is the exact progress, we need to estimate
this in-sync state from several surrounding states.

Main reason here is to never report 100% sync state for a raid device
which will be undergoing i.e. recovery.
2017-06-16 17:04:00 +02:00
40e0dcf70d raid: adjust reshape feature flag check
Relative to last comit ddf2a1d656:

adjust the dm-raid target version to 1.12.0 which shows
mandatory kernel MD deadlock fixes related to reshaping
are presant in the kernel.

Related: rhbz1443999
2017-06-16 15:58:47 +02:00
ddf2a1d656 Revert "lvconvert: reject changing number of stripes on single core
This reverts commit 3719f4bc54
to allow for single core testing on kernels with deadlock
fixes relative to rhbz1443999."
2017-06-16 15:43:23 +02:00
3592243afb test: New test file for validating kernel status during sync ops
First test in this file checks whether 'aa' is ever spotted during
a "recover" operation (it should not be).  More tests should follow
in this file to look for oddities in status output - especially as
it relates to the sync_ratio, dev_health, and sync_action fields.
2017-06-15 11:06:08 -05:00
6c4b2a6aa1 clean-up: Very picky update to comment - hopefully making it clearer 2017-06-14 15:22:04 -05:00
1f57a5263e clean-ups: remove unused var, add 'static' for local fn, adjust test
For the test clean-up, I was providing too many devices to the first
command - possibly allowing it to allocate in the wrong place.  I was
also not providing a device for the second command - virtually ensuring
the test was not performing correctly at times.
2017-06-14 14:49:42 -05:00
ddb14b6b05 lvconvert: Disallow removal of primary when up-converting (recovering)
This patch ensures that under normal conditions (i.e. not during repair
operations) that users are prevented from removing devices that would
cause data loss.

When a RAID1 is undergoing its initial sync, it is ok to remove all but
one of the images because they have all existed since creation and
contain all the data written since the array was created.  OTOH, if the
RAID1 was created as a result of an up-convert from linear, it is very
important not to let the user remove the primary image (the source of
all the data).  They should be allowed to remove any devices they want
and as many as they want as long as one original (primary) device is left
during a "recover" (aka up-convert).

This fixes bug 1461187 and includes the necessary regression tests.
2017-06-14 08:41:05 -05:00
4c0e908b0a RAID (lvconvert/dmeventd): Cleanly handle primary failure during 'recover' op
Add the checks necessary to distiguish the state of a RAID when the primary
source for syncing fails during the "recover" process.

It has been possible to hit this condition before (like when converting from
2-way RAID1 to 3-way and having the first two devices die during the "recover"
process).  However, this condition is now more likely since we treat linear ->
RAID1 conversions as "recover" now - so it is especially important we cleanly
handle this condition.
2017-06-14 08:39:50 -05:00
d34d2068dd lvconvert: Don't require a 'force' option during RAID repair.
Previously, we were treating non-RAID to RAID up-converts as a "resync"
operation.  (The most common example being 'linear -> RAID1'.)  RAID to
RAID up-converts or rebuilds of specific RAID images are properly treated
as a "recover" operation.

Since we were treating some up-convert operations as "resync", it was
possible to have scenarios where data corruption or data loss were
possibilities if the RAID hadn't been able to sync completely before a
loss of the primary source devices.  In order to ensure that the user took
the proper precautions in such scenarios, we required a '--force' option
to be present.  Unfortuneately, the force option was rendered useless
because there was no way to distiguish the failure state of a potentially
destructive repair from a nominal one - making the '--force' option a
requirement for any RAID1 repair!

We now treat non-RAID to RAID up-converts properly as "recover" operations.
This eliminates the scenarios that can potentially cause data loss or
data corruption; and this eliminates the need for the '--force' requirement.
This patch removes the requirement to specify '--force' for RAID repairs.
2017-06-14 08:39:07 -05:00
c87907dcd5 lvconvert: linear -> raid1 upconvert should cause "recover" not "resync"
Two of the sync actions performed by the kernel (aka MD runtime) are
"resync" and "recover".  The "resync" refers to when an entirely new array
is going through the process of initializing (or resynchronizing after an
unexpected shutdown).  The "recover" is the process of initializing a new
member device to the array.  So, a brand new array with all new devices
will undergo "resync".  An array with replaced or added sub-LVs will undergo
"recover".

These two states are treated very differently when failures happen.  If any
device is lost or replaced while "resync", there are no worries.  This is
because any writes created from the inception of the array have occurred to
all the devices and can be safely recovered.  Even though non-initialized
portions will still be resync'ed with uninitialized data, it is ok.  However,
if a pre-existing device is lost (aka, the original linear device in a
linear -> raid1 convert) during a "recover", data loss can be the result.
Thus, writes are errored by the kernel and recovery is halted.  The failed
device must be restored or removed.  This is the correct behavior.

Unfortunately, we were treating an up-convert from linear as a "resync"
when we should have been treating it as a "recover".  This patch
removes the special case for linear upconvert.  It allows each new image
sub-LV to be marked with a rebuild flag and treats the array as 'in-sync'.
This has the correct effect of causing the upconvert to be treated as a
"recover" rather than a "resync".  There is no need to flag these two states
differently in LVM metadata, because they are already considered differently
by the kernel RAID metadata.  (Any activation/deactivation will properly
resume the "recover" process and not a "resync" process.)

We make this behavior change based on the presense of dm-raid target
version 1.9.0+.
2017-06-14 08:35:22 -05:00
14d563accc raid: change reshape segtype flags
Commit 1c916ec5ff
missed new reshape flags.
2017-06-14 15:01:19 +02:00
08079ec420 lvconvert: fix detached SubLV deactivation in cluster
On conversion from raid10 to raid0 (takeover), all rmeta
devices and the rimage devices of mirrored stripes are
detached from the raid10 LV. The remaining rimage areas
are being shifted down into the slots of the detached
ones hence requiring renames to show proper _N suffix
sequences (e.g. 0,1,2,3 instead of 0,2,4,6).  Only the
top-level raid10 LV has a cluster lock, not the detached
SubLVs thus their deactivation is impossible and e.g the
rename from *_rimage_6 to *_rimage_3 will fail.  Fix by
activating exclusively before deactivating and removing.

Resolves: rhbz1448123
2017-06-13 23:15:51 +02:00
9a094350e0 dmfilemapd: do not wait if file has been truncated 2017-06-13 19:46:41 +01:00
0cb628dfe2 dmfilemapd: update file block count at daemon start
The file block count stored in the filemap_monitor was lazily
initialised at the time of the first check. This causes problems
in the case that the file has been truncated between this time and
the time the daemon started: the initial block count and current
block count match and the daemon fails to detect a change.

Separate the setting of the block count from the check and make a
call to update the value at the start of _dmfilemapd().
2017-06-13 19:46:41 +01:00
744f2920db libdm: allow truncated files in dm_stats_update_regions_from_fd()
It's not an error to attempt to update regions from an fd that has
been truncated (or otherwise no longer has any allocated extents):
in this case, the call should remove all regions corresponding to
the group, and return an empty region table.
2017-06-13 19:45:50 +01:00
37cd8f9678 configure: update 2017-06-09 22:52:19 +02:00
4b4a210e83 configure: search for (a possibly prefixed) ar
e.g. when cross compiling.

Signed-off-by: Heiko Becker <heirecka@exherbo.org>
2017-06-09 22:49:39 +02:00
5ef20d2168 configure: improve reporting about readline
Report real 'readline' supporting state instead of 'maybe'.
Really check for 'readline' headers.
2017-06-09 22:40:27 +02:00
358eee15f3 configure: warn about older version of cache_check
For proper usage of Cache kernel metadata format V2,
new cache_check tool is basically mandatory.

Print warning during configure time about this problem.
2017-06-09 22:32:12 +02:00
1c916ec5ff raid: add reshape segtype flag support
Prohibit activation of reshaping RaidLVs on incompatible
lvm2 runtime by storing e.g. 'raid5+RESHAPE' segment type
strings in the lvm2 metadata.  Incompatible runtime not
supporting reshaping won't be able to activate those thus
avoiding potential data corruption.

Any new non-reshaping lvconvert command will reset the
segment type string from 'raid5+RESHAPE' to 'raid5'.

See commits
0299a7af1e and
4141409eb0
for segtype flag support.
2017-06-09 22:23:04 +02:00
3055131784 indent: properly indent goto 2017-06-09 21:49:19 +02:00
57379157f4 cleanup: update message 2017-06-09 21:49:19 +02:00
db5938a4f8 cleanup: define really uses KB
Cleanup also units for DEFAULT_THIN_POOL_OPTIMAL_METADATA_SIZE define
(128MB) and update calcs for it.
2017-06-09 21:49:19 +02:00
5e7db7d85d snapshot: fix reporting for merged old snapshot
When old snapshot is merged, lvm2 still can report some data about
merged 'snapshot' - i.e. it occupied space in VG.

This patch fixes regression from commit:
6fd20be629

and resolved RHBZ: 1460161
2017-06-09 21:03:20 +02:00
b6945b8510 tests: no longer allowed too big thin-pools for small chunks 2017-06-09 13:03:42 +02:00
5017284709 configure: report yes or no for wiping and system
Avoid reporting 'checking result' as maybe - it should
clearly tell 'yes' or 'no'.

Just shuffle printed message to the place, where we
already know the 'maybe' answer.

So instead of printing 'unclear':

checking whether to enable libblkid detection of signatures when wiping... maybe
checking for BLKID... yes
checking whether to use udev-systemd protocol for jobs in background... maybe
checking for SYSTEMD... yes

show this:

checking for BLKID... yes
checking whether to enable libblkid detection of signatures when wiping... yes
checking for SYSTEMD... yes
checking whether to use udev-systemd protocol for jobs in background... yes
2017-06-09 13:02:18 +02:00
b3ef051e06 cache: lvcreate --cachepool checks for cache pool
Code path missed validation of lvcreate --cachepool argument.
If the non cache-pool LV was passed in, code has still continued
further work and failed later on internal error.  Validate this
condition at right place now.
2017-06-09 10:59:37 +02:00
f91ea96b4f tests: fix compilation of unit tests
Rule for TARGET compiling got missing and needs to be explicitely
expressed, otherwise default unsuitable rule is applied.
2017-06-08 11:59:02 +02:00
ee5ecde35e tests: check thin-pool boundary sizes 2017-06-08 11:58:36 +02:00
48ffb996c5 thin: disallow creation of too big thin pools
When a combination of thin-pool chunk size and thin-pool data size
goes beyond addressable limit, such volume creation is directly
prohibited.

Maximum usable thin-pool size is calculated with use of maximal support
metadata size (even when it's created smaller) and given chunk-size.
If the value data size is found to be too big, the command reports
error and operation fails.

Previously thin-pool was created however lots of thin-pool data LV was
not usable and this space in VG has been wasted.
2017-06-08 11:58:36 +02:00
ba3d3210d7 cleanup: use DM limit define
For calculation use already defined size in libdm, which give better
estimation of maximal size of thin pool metadata.
2017-06-08 11:07:58 +02:00
719d099693 cleanup: rename internal define
More descriptive name of #define.
2017-06-08 11:07:18 +02:00
39703cb485 lvconvert: reject RAID conversions on inactive LVs
Only support RAID conversions on active LVs.

If we'd accept e.g. upconverting linear -> raid1 on inactive
linear LVs, any LV flags passed to the kernel aren't properly
cleared thus errouneously passing them on every activation.

Add respective check to lv_raid_change_image_count() and
move existing one in lv_raid_convert() for better messages.
2017-06-07 18:37:04 +02:00
61420309ee lvmdbusd: Prevent stall when update thread gets exception
If during the process of fetching current lvm state we experience an
exception we fail to call set_result on the queued_requests we were
processing.  When this happens those threads block forever which causes
the service to stall infinitely.  Only clear the queued_requests after
we have called set_result.
2017-06-02 12:39:04 -05:00
699ccc05ca lvmdbusd: Add background command to flight recorder
We were not adding background tasks to flight recorder.  Add the meta
data to the flight recorder when we start the command and update the meta
data when the command is finished.  Locking was added to meta data to
prevent concurrent update and returning string representation as these can
happen in two different threads.
2017-06-02 12:32:51 -05:00
192d142e1c lvmdbusd: cmdhandler.py vg_reduce, remove extranous '--all'
vgreduce previously allowed --all and --removemissing together even though
it only actual did the remove missing.  The lvm dbus daemon was passing
--all anytime there was no entries in pv_object_paths.  This change supplies
--all if and only if we are not removing missing and the pv_object_paths
is empty.

Vgreduce has and continues to enforce the invalid combination of supplying a
device list when you specify --all or --removemissing so we do not need
to check for that invalid combination explicitly in the lvm dbus service as
it's already covered.

Ref: https://bugzilla.redhat.com/show_bug.cgi?id=1455471
2017-06-02 12:32:43 -05:00
3217e0cfea lvconvert: choose direct path to desired raid level
Remove superfluous raid5_n interim LV type from raid4 -> raid10 conversion.

Resolves: rhbz1458006
2017-06-02 14:30:57 +02:00
c98a25aab1 print warning about in-use orphans
Warn about a PV that has the in-use flag set, but appears in
the orphan VG (no VG was found referencing it.)

There are a number of conditions that could lead to this:

. The PV was created with no mdas and is used in a VG with
  other PVs (with metadata) that have not yet appeared on
  the system.  So, no VG metadata is found by lvm which
  references the in-use PV with no mdas.

. vgremove could have failed after clearing mdas but
  before clearing the in-use flag.  In this case, the
  in-use flag needs to be manually cleared on the PV.

. The PV may have damanged/unrecognized VG metadata
  that lvm could not read.

. The PV may have no mdas, and the PVs with the metadata
  may have damaged/unrecognized metadata.
2017-06-01 11:18:42 -05:00
f3c90e90f8 disable repairing in-use flag on orphan PVs
A PV holding VG metadata that lvm can't understand
(e.g. damaged, checksum error, unrecognized flag)
will appear as an in-use orphan, and will be cleared
by this repair code.  Disable this repair until the
code can keep track of these problematic PVs, and
distinguish them from actual in-use orphans.
2017-06-01 09:53:14 -05:00
743ffb1962 tests: longer delay
Slower sync a bit more and use bigger raid arrays to
be more sure we will catch raid being sychronized.
2017-05-31 13:59:42 +02:00
42b87c23e2 tests: add some extra udev waits
To get less random results on older systems with systemd (i.e. fc23)
put few extra udev wait operations to avoid any udev event collision.
2017-05-31 13:23:34 +02:00
091c55a13f tests: skip reshaping raid10
Needs newer target  >= 1.10.1 for reshaping of raid10 LVs.
2017-05-31 12:59:53 +02:00
3719f4bc54 lvconvert: reject changing number of stripes on single core
Reject any stripe adding/removing reshape on raid4/5/6/10 because
of related MD kernel deadlock on single core systems until
we get a proper fix in MD.

Related: rhbz1443999
2017-05-30 19:14:32 +02:00
c245996d70 tests: missed to export lvm binary for fsadm 2017-05-30 18:43:56 +02:00
b876e8c915 tests: drop extra debug vvvv
Also show output of mount so when it fails we can check the state.
2017-05-30 18:43:56 +02:00
7c84c5c421 tests: also check new flag with segtype
Make sure new unknown flag is having same behavior as old unknown segtype.
2017-05-30 18:43:56 +02:00
fb86bddda2 flags: improve unknown flags logic
Use same logic as with unknown segment type - so preserve such
name fully with all flags just with UNKNOWN segment type bits.
2017-05-30 18:43:45 +02:00
d1ac6108c3 flags: restore same logic with MISSING
Since lvmetad is using 'MISSING' in status for 'another' purpose,
we need to support ATM also flag get from this place.

Until fixed better - we accept both flags - alhough lvm2 will
only print in flags.
2017-05-30 16:16:29 +02:00
4141409eb0 flags: add segtype flag support
Switch METADATA_FORMAT flag usage to be stored via segtype
instead of 'status' flag which appeared to cause major
incompatibility troubles.

For backward compatiblity segtype flags are still accepted also
via 'status' bits which were used from version 2.02.169 so metadata
saved by this newer lvm2 version should still work nicely, although
new save version will no longer work on this older lvm2 version.
2017-05-29 14:52:56 +02:00
0299a7af1e flags: add read and print of segtype flag
Allow storing LV status bits with segment type name field.
Switching to this since this field has better support for compatibility
with older version of lvm2 - since such unknown segtype will not cause
complete invisiblity of metadata from older lvm2 code - just the
particular LV will become unusable with unknown type of segment.
2017-05-29 14:49:41 +02:00
1bb0c5197f cleanup: backtrace
Add debug backtrace.
2017-05-29 14:48:33 +02:00
966d1130db cleanup: separate type and mask
Split misused 'enum' into 2 fields - one for type
of PV, VG, LV and other for mask.
2017-05-29 14:47:26 +02:00
8e0bc73eba cleanup: bad flag is internal error here
Convert to internal error.
2017-05-29 14:47:16 +02:00
597b3576c7 tests: wait for raid in sync
Lvchange needs synchronized raid.
2017-05-29 14:41:53 +02:00
223c594f0e test: Fix dbus testing using testsuite
- Must reread all objects as PVs might be removed.
- Never consider testsuite provided PVs nested, or tearDown fails to
  remove any outstanding VGs on them.
2017-05-26 15:39:20 +02:00
7687ab82c8 test: Use _pv suffix for nested devices
Testsuite uses global_filter to accept only test devices with
suffix matching /_pv[0-9_]*$/ set by generate_config in aux.sh.
2017-05-26 08:33:39 +02:00
3745b52ed4 spec: Enable notify-dbus in builds with dbus 2017-05-26 07:40:09 +02:00
65b10281f8 Proper dm_snprintf return checks 2017-05-24 14:00:44 +02:00
3da5cdc5dc Fix typo 2017-05-24 13:47:45 +02:00
7a0f46e2f8 add comment about PV in-use repair
copied from commit message for
d97f1c89de
2017-05-23 16:59:46 -05:00
4d261cd719 man lvmsystemid: change some wording
Clarify the wording in a couple cases.
2017-05-23 10:50:41 -05:00
5e8beb4023 tests: fix test for fsadm
Avoid mountinfo
Pass 'y'  - since ATM lvresize cannot pass --yes to fsadm.
2017-05-23 14:02:43 +02:00
1fe4f80e45 fsadm: avoid hidden --yes
When 'fsadm' was running without terminal (i.e. pipe), it's been
automatically working like in '--yes'.

Detect terminal and only accept empty "" input in this mode.
2017-05-23 14:02:41 +02:00
57492a6094 raid: Drop unnecessary/incorrect use of dm_pool_free 2017-05-23 01:51:04 +01:00
fbe7464df5 metadata: Unlock VG on more _vg_make_handle error paths
Internal error: VG lock vg0 must be requested before vg3, not after.
Internal error: 3 device(s) were left open and have been closed.
2017-05-23 01:38:02 +01:00
d1ddfc4085 format_text: More internal errors if given invalid internal metadata
Three more messages to ensure each failure in out_areas() results in a
low-level message instead of sometimes just <backtrace>.
2017-05-22 23:30:34 +01:00
ca24196491 man lvmraid: add more indirect conversion info 2017-05-22 14:28:24 -05:00
3877ef0e43 tests: catch some fsadm tricky paths
When user is renaming a device, we are getting into troubles.
We needs to recognize which case is actually supportable by fsadm.
2017-05-22 15:12:31 +02:00
9e04e0483f fsadm: enhance detection of already mounted volumes
Add more validation to catch mainly renamed devices, where
filesystem utils are not able to handle devices properly,
as they are not addressed by major:minor by rather via some
symbolic path names which can change over time via rename operation.
2017-05-22 15:11:21 +02:00
2b7ac2bfb3 fsadm: always detect mounted fs with extX
Since we add more validation to 'detect_mounted' function make sure
we always use it even with 'resize' action, so numerous validations
are not skipped.
2017-05-22 15:10:16 +02:00
a29e7843b1 man lvmraid: indirect conversions
Start documenting multi-step conversions.

Don't number examples.
2017-05-18 16:47:37 -05:00
2bf01c2f37 lvconvert: fix logic in automatic settings of possible (raid) LV types
Commit 5fe07d3574 failed to set raid5 types
properly on conversions from raid6.  It always enforced raid6_ls_6
for types raid6/raid6_zr/raid6_nr/raid6_nc, thus requiring 3 conversions
instead of 2 when asking for raid5_{la,rs,ra,n}.

Related: rhbz1439403
2017-05-18 16:20:39 +02:00
8e99a46d09 lvmdbusd: Fix missed rename
Introduced By: e53454d6 (2.02.169)
Related: RHBZ#1348688
2017-05-18 12:52:46 +02:00
9c651b146e lvconvert: fix indent and typo in last commit 2017-05-18 00:43:20 +02:00
5fe07d3574 lvconvert: enhance automatic settings of possible (raid) LV types
Offer possible interim LV types and display their aliases
(e.g. raid5 and raid5_ls) for all conversions between
striped and any raid LVs in case user requests a type
not suitable to direct conversion.

E.g. running "lvconvert --type raid5 LV" on a striped
LV will replace raid5 aka raid5_ls (rotating parity)
with raid5_n (dedicated parity on last image).
User is asked to repeat the lvconvert command to get to the
requested LV type (raid5 aka raid5_ls in this example)
when such replacement occurs.

Resolves: rhbz1439403
2017-05-18 00:18:15 +02:00
16c6d9f11a lvmdbusd: Fix notify_dbus mangling config option
If config option is passed by caller, dbusd appends to the option not to
the value, and also without using delimiter.

Bug: RHBZ#1451612
2017-05-17 15:35:20 +02:00
9291fb7bf5 test: Fix condition 2017-05-17 11:43:49 +02:00
1fb13e8660 test: Fix skipped cleanup 2017-05-17 11:37:29 +02:00
48408ece6d test: add missing yes option to lvconvert stripe removal 2017-05-16 17:52:54 +02:00
f4f408610c test: Fix previous commit - skip only RAID6 part 2017-05-16 10:47:53 +02:00
cdb49216c5 test: Update condition for changing RAID regionsize
The test is failing on F23 and F25 with 1.9.1
2017-05-16 10:44:52 +02:00
5406191cb9 lvchange: allow changing properties on thin pool data lv
Add an exception to not allowing lvchange to change properties
on hidden LVs.  When a thin pool data LV is a cache LV, we
need to allow changing cache properties on the tdata sublv of
the thin pool.
2017-05-15 10:59:48 -05:00
dfc58c637b config: keep description lines under 80
As far as possible, it's nice to keep the config
description lines from going over 80 columns.
2017-05-12 09:55:16 -05:00
2583732165 lvcreate: Fix last commit for virtual sizes.
Don't stop when extents is 0 if a virtual size parameter was supplied
instead.
2017-05-12 13:16:10 +01:00
cf73f6cf61 lvcreate: Fix mirror percentage size calculations.
Trap cases where the percentage calculation currently leads to an empty
LV and the message:

  Internal error: Unable to create new logical volume with no extents

Additionally convert the calculated number of extents from physical to
logical when creating a mirror using a percentage that is based on
Physical Extents.  Otherwise a command like 'lvcreate -m3 -l80%FREE'
can never leave any free space.

This brings the behaviour closer to that of lvresize.
(A further patch is needed to cover all the raid types.)
2017-05-12 02:31:35 +01:00
d49a20b7bd man lvmcache: add info about metadata formats 2017-05-11 10:52:59 -05:00
80900dcf76 metadata: Fix metadata repair when devs still missing.
_check_reappeared_pv() incorrectly clears the MISSING_PV flags of
PVs with unknown devices.
While one caller avoids passing such PVs into the function, the other
doesn't.  Move the check inside the function so it's not forgotten.

Without this patch, if the normal VG reading code tries to repair
inconsistent metadata while there is an unknown PV, it incorrectly
considers the missing PVs no longer to be missing and produces
incorrect 'pvs' output omitting the missing PV, for example.

Easy reproducer:
Create a VG with 3 PVs pv1, pv2, pv3.
Hide pv2.
Run vgreduce --removemissing.
Reinstate the hidden PV pv2 and at the same time hide a different PV
pv3.
Run 'pvs' - incorrect output.
Run 'pvs' again - correct output.

See https://bugzilla.redhat.com/1434054
2017-05-11 02:17:34 +01:00
d45531712d vg_read: check for NULL dev to avoid segfault
There are certain situations (not fully understood)
where is_missing_pv() is false, but pv->dev is NULL,
so this adds a check for NULL pv->dev after is_missing_pv()
to avoid a segfault.
2017-05-10 10:45:41 -05:00
b817cc5746 tests: better skip 2017-05-10 15:40:32 +02:00
a1a9ae0aa5 fsadm: all path define MAJOR MINOR 2017-05-10 15:40:32 +02:00
8ea33b633a fsadm: some cleanup
Put some extra "" around vars.
Indent.
Error messages with dots.
2017-05-10 15:40:31 +02:00
1107d483a2 fsadm: fix test of subshell return value
Subshell is not returning error code value upward thus
error results in this case were actually ignored.
Also add dots to moved error messages.
2017-05-10 15:40:29 +02:00
455a4de090 dmeventd: restore multiple warnings
With recent updates for thin pool monitoring in version 169
we lost multiple WARNINGs to be printed in syslog, when
pool crossed  80%, 85%, 90%, 95%, 100%.

Restore this logic as we want to keep user informed more
then just once when 80% boundary is passed.
2017-05-10 15:39:36 +02:00
a9940d16fe dmfilemapd: always initialise 'same' local variable (Coverity)
Fix a regression introduced in 70bb726 that allows a local variable
in the monitored file checking routine to be accessed before its
assignment when the file has already been unlinked.
2017-05-08 17:10:25 +01:00
c5fee2ee6e man lvmetad: mention repair as a reason for disabling
lvconvert --repair now also disables lvmetad.
2017-05-05 10:48:58 -05:00
405a3689bc lvmdbusd: Correct PV lookups
When a user does a Manager.PvCreate they can specify the block device using a
device path that may be different than what lvm reports is the device path.  For
example a user could use:

/dev/disk/by-id/wwn-0x5002538500000000 instead of /dev/sdc

In this case the pvcreate will succeed, but when we query lvm we don't find the
newly created PV. We fail because it's device path is returned as /dev/sdc.  This
change re-uses an internal lookup which can accommodate this and correctly find
the newly created PV.

Corrects https://bugzilla.redhat.com/show_bug.cgi?id=1445654
2017-05-05 10:30:06 -05:00
fcce7e1660 lvmdbustest.py: Add PV symlink testing
We fixed this issue once before and it's back, add a test to make
sure it never comes back again!

https://bugzilla.redhat.com/show_bug.cgi?id=1318754
https://bugzilla.redhat.com/show_bug.cgi?id=1445654
2017-05-05 10:30:06 -05:00
97d5e192fe WHATS_NEW: cache pool options 2017-05-05 10:02:54 -05:00
df5fd5ae88 lvcreate: cachemode writeback and cachepolicy cleaner is invalid
Return an error if lvconvert is used to create a cache pool
with that combination.
2017-05-05 09:59:12 -05:00
7fbeea30e5 dmfilemapd: clear filemap_monitor before calling _parse_args()
If the wrong number of arguments are given, main() will attempt
to free the uninitialised pointer in fm.path.
2017-05-05 11:53:44 +01:00
c56d8535a7 man lvmconfig: add descriptions for typeconfig and ignorelocal 2017-05-04 14:04:10 -05:00
20026c9c22 man vgexport: reference to vgimport 2017-05-03 16:44:01 -05:00
f2d943a4b6 man lvm fullreport and lvpoll references
Add references to lvm-fullreport(8) and lvm-lvpoll(8).
2017-05-03 16:40:44 -05:00
1423ab93f9 man clvmd: mention lvmlockd is another option 2017-05-03 16:26:21 -05:00
a7a28bd998 man: reference other man pages with bold
There were a handful of references to other man
pages using the standard command(N) form which were
not in bold, so they were not turned into links
in html formats.
2017-05-03 16:21:01 -05:00
596fd0b106 man lvm.conf: say how to get a description of settings
Many will look in 'man lvm.conf' expecting to find a
description of the lvm.conf fields, which are not there.
State at the beginning how to get this (by running
lvmconfig.)
2017-05-03 16:01:19 -05:00
5de3870662 pvscan: define command as taking only -aay
The fact that -an and -ay are not accepted can be
stated in the command definition.
2017-05-03 15:46:49 -05:00
b869db30ac man pvscan: add description for --activate 2017-05-03 15:38:53 -05:00
892f3b1002 man vgimport: add description for --all 2017-05-03 15:19:19 -05:00
ab1de07c97 man pvchange: mention one option is required 2017-05-03 15:10:10 -05:00
2773667627 man pvchange: add description for --all 2017-05-03 15:03:14 -05:00
f7edadf870 commands: check for memory failures
just return for now
2017-05-03 14:46:43 -05:00
cb573d1ec9 man lvmlockd: minor wording updates 2017-05-03 14:45:33 -05:00
a946327bb7 post-release 2017-05-03 11:26:58 +01:00
fb4bf1f4ea pre-release 2017-05-03 11:23:31 +01:00
6bdbb283d5 man: generate 2017-05-03 11:23:15 +01:00
a0f742542f command: avoid compiler warning
man-generator.c:3243: warning: declaration of ‘stat’ shadows a global
declaration
2017-05-03 11:19:43 +01:00
e15c7c5ff9 man: references to lvm entities
Try to reference lvm(8) at the start of topical
man pages, and spell out acronyms early in the
text, descriptions of which can be found in lvm(8).
2017-05-02 16:47:02 -05:00
253bc5eb2e man lvm: define LVM and its terms
The lvm(8) man page never said what LVM is,
it never defined what the acronym LVM stands for,
it never spelled out other common acronyms VG, PV, LV,
and never described what they are.

This adds a very minimal definition which at least defines
the acronyms and entities, but it could obviously be
expanded on, either here or elsewhere.
2017-05-02 15:49:58 -05:00
882a918bef man lvmsystemid: general improvements
Mainly improve the readability/wording.
Use "system ID" instead of system_id.
A couple small additions.
2017-05-02 14:57:58 -05:00
7da13bbf7b dbus: Add --yes when --setphysicalvolumesize is used 2017-05-02 08:42:21 +02:00
15eaf703fc commands: fix memory debug for cmd defs
Clean up the handling of memory used for cmd defs
so it doesn't trip up memory debugging.

Allocate memory for commands[] from libmem.

Free temporary memory used by define_commands()
at the end of the function.

Clear all the command def state in in lvm_fin().
2017-05-01 15:27:14 -05:00
54726a4950 fix running commands from a script file
Using any arg with a command name in a script file
would cause the command to fail.

The name of the script file being executed was being passed
to lvm_register_commands() and define_commands(), which
prevented command defs from being defined (simple commands
were still being defined only by name which was enough for those
to still work when run trivially with no args).
2017-04-28 16:51:04 -05:00
c73b9f062c WHATS_NEW: pvcreate prompt 2017-04-28 09:06:41 -05:00
1764524b06 WHATS_NEW: pvcreate --setphysicalvolumesize 2017-04-28 14:34:26 +01:00
86b9c23dbe commands: improve syntax suggestion when no command is found
The logic for suggesting the nearest valid command syntax
was missing the simplest case.  If a command has only one
valid syntax, that is the one we should suggest.  (We were
suggesting nothing in this case.)
2017-04-27 14:21:01 -05:00
4f9ff14508 pvcreate: add prompt when setting dev size
If the device size does not match the size requested
by --setphysicalvolumesize, then prompt the user.

Make the pvcreate checking/prompting code handle
multiple prompts for the same device, since the
new prompt can be in addition to the existing
prompt when the PV is in a VG.
2017-04-27 13:25:41 -05:00
5cf51fb2f7 dbus: log_debug needs qualifier
Adding qualifier makes the only unqualified log_debug occurence
consistent with other uses in the same file.

Other possible ways to fix this:

- using `from .utils import log_debug`
- moving the line below `from . import utils` line
2017-04-27 18:16:17 +02:00
0e3c16af56 pvresize: Missing a message on error path. 2017-04-27 15:00:41 +01:00
33afe2ca76 test: add -y to raid1 up conversions 2017-04-27 15:56:58 +02:00
0516447978 lvconvert: preserve region size on raid1 image count changes (v2)
Unless a change of the regionsize is requested via "lvconvert -R N ...",
keep the region size when the number of images changes in a raid1 LV.

Related: rhbz1443705
2017-04-27 15:52:25 +02:00
14c84c79db test: Update pattern to match code
Fix commit a3fdc966b5
2017-04-27 15:30:03 +02:00
af47ec9f51 Revert "lvconvert: preserve region size on raid1 image count changes"
This reverts commit 8333d5a969.
2017-04-27 15:29:03 +02:00
813bcb24f0 test: Add -y to pvresize --setphysicalvolumesize 2017-04-27 02:57:59 +01:00
cbc69f8c69 pvresize: Prompt when non-default size supplied.
Seek confirmation before changing the PV size to one that differs
from the underlying block device.
2017-04-27 02:36:34 +01:00
78a0b4a08a typo: s/extends/extents/ in lvmthin man page
bug 1439905
2017-04-26 15:49:28 -05:00
0f31f10ac5 lvmdbusd: Improve error msg to include PV
Include PV device path when we believe it already exists.
2017-04-26 07:31:08 -05:00
e50fb06792 lvmdbustest.py: Add nested testing
Make sure when a LV is used as a PV the dbus service works correctly.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2017-04-26 07:30:45 -05:00
6de3a9b4d0 lvmdbustest.py: Handle nested setUp & tearDown
Handle cleaning up correctly if a LV is used as a PV.
2017-04-26 07:10:18 -05:00
e78329e281 lvmdbusd: Make sure we don't hang on lvcreate
If we happen to create a lv that has a previous signature we hang on y/n
prompt, add '--yes'.
2017-04-26 07:10:18 -05:00
a3fdc966b5 commands: improve error messages for rules
Make the error messages more consistent,
and use less code-centric wording.
2017-04-25 15:49:58 -05:00
c534a7bcc9 lvconvert: FIXME
Add FIXME to move error path processing out of tool into library.

Related: rhbz1437653
2017-04-24 18:56:36 +02:00
aa1d5d5c89 lvconvert: fix inactive mirror up converting regression
Up converting an inactive mirror with insufficient
devs results in an over concerned warning.

Resolves: rhbz1437653
2017-04-24 17:44:54 +02:00
8333d5a969 lvconvert: preserve region size on raid1 image count changes
Unless a change of the regionsize is requested via "lvconvert -R N ...",
keep the region size when the number of images changes in a raid1 LV.

Resolves: rhbz1443705
2017-04-22 02:04:49 +02:00
8f305f025e raid: handle insufficent PVs on takeover to/from raid4
Commit 7bc85177b0
felt short relative to striped/raid0* -> raid4
and raid4 -> raid6.

Related: rhbz1438013
2017-04-22 01:19:44 +02:00
97a5fa4b87 raid: avoid superfluous variable 2017-04-22 00:50:36 +02:00
effeb2b93d test: add raid4 to upconvert allocation failure tests 2017-04-22 00:43:31 +02:00
149e4fa04b test: consider changed default
commit b81b4aad24
raised the region size so demand the sizes the
test checks for.
2017-04-22 00:42:09 +02:00
7c7122a3b1 test: add upconvert allocation failure tests 2017-04-21 20:57:31 +02:00
d48b816764 test: also prevent lvconvert-raid-reshape.sh on single core 2017-04-21 02:17:55 +02:00
a004cceed2 test: Adjust previous commit
Change have_single_core to  have_multi_core and go back to || logic in related test scripts.
2017-04-21 01:21:24 +02:00
18bf954801 test: Fix skip some reshape tests that hang on single core machines
Fix commit c7fb0cb861.
2017-04-20 21:45:56 +02:00
0c2fd133d7 raid: remove double minimum area check on takeover 2017-04-20 21:35:06 +02:00
d8a63f446e raid: define return value on error paths 2017-04-20 21:32:40 +02:00
5fb5717402 raid: avoid superfluous reload on takeover
Allow any reset rebuild flags to trigger the second update on takeover.
Use descriptive callback names.
Fix typo and add comments.
2017-04-20 21:18:27 +02:00
c7fb0cb861 test: Skip some reshape tests that hang on single core machines
Skip hanging raid reshape tests until https://bugzilla.redhat.com/1443999
is fixed
2017-04-20 20:05:07 +01:00
83cdba75bd mirror/raid: display adjusted region size with units
Display adjusted region size in units (e.g. "4.00 MiB") rather than sectors.
2017-04-20 20:42:21 +02:00
b9d10857b2 man: quote the word no 2017-04-18 15:56:48 -05:00
658d524d26 configure: Fix notify-dbus and dmfilemapd options. 2017-04-18 20:37:53 +01:00
2d9097e9ca WHATS_NEW: configure option enable-lvmlockd 2017-04-18 12:58:18 -05:00
a5256d1353 spec: rename lockd to lvmlockd 2017-04-18 11:22:07 -05:00
a41a8430d6 configure: rename lockd to lvmlockd 2017-04-18 11:18:07 -05:00
aa25cfe084 test: correcting binary usage
Ensure 'test suite' run uses fsadm and dmeventd from compiled dir,
while for 'rpm' installed test use binaries installed in system.
2017-04-14 01:03:18 +02:00
15c3ad9641 lvconvert: typo in message 2017-04-13 22:19:29 +02:00
0ea9a15612 tests: use raid_region_size 512
given the new default from 5ae7a016b8
2017-04-13 14:21:34 -05:00
b81b4aad24 WHATS_NEW: raise region_size default 2017-04-13 17:49:58 +02:00
c6a6ce6cd5 conf: Remove exec_prefix from confdir.
Some distros now want to put /etc outside prefix/exec_prefix.
2017-04-13 16:21:29 +01:00
5ae7a016b8 lvcreate: raise default raid regionsize to 2MiB
Related: rhbz1392947.
2017-04-13 16:10:49 +02:00
4547218a7d conf: Add missing prefix to installation directory.
Our Makefiles also support systems that set the installation prefix
at configuration time - the use of DESTDIR is not required.
2017-04-13 02:17:27 +01:00
ae7f696d53 post-release 2017-04-13 01:47:47 +01:00
b9a16fe73b pre-release 2017-04-13 00:43:31 +01:00
9ed518f19f autoconf 2017-04-13 00:38:46 +01:00
5ac230095c make generate 2017-04-13 00:30:05 +01:00
a3e8354479 tests: use egrep to check for message
Seems we may get different '' around option on different nixes.
2017-04-12 23:05:50 +02:00
59d54d70e7 tests: aux defines fsadm path 2017-04-12 23:05:50 +02:00
1e64386dc6 raid: use log_error
Turn log_print into log_error for error path.
2017-04-12 23:05:50 +02:00
1f715ab3b2 lvconvert: return error without conversion
lvconvert parameters not causing a conversion (i.e. no type,
number of stripes, stripesize or regionsize changes) will
remove any allocated reshape space in which case the command
returns success.  If reshape space does not exist though,
return error.
2017-04-12 22:11:30 +02:00
56704383bf tests: test for new supported commands
New tests for:

lvconvert --regionsize | --swapmetadata | --startpoll |
          --mergesnapshot | mergethin
2017-04-12 21:34:08 +02:00
f8034e14e6 tests: restore some test changes
Restore existing tests and separate new tests
for new options later.

Keep coverage for existing syntax

Reverts bits from commits:

a801b92b2c.
d71aaca07b
fa2a728a39
1e2420bca8
46abc28a48
0e3e611a13
2017-04-12 21:34:08 +02:00
3018cdcaa7 fsadm: support configurable full path
Just like with other tools lvm2 is using allow to define
fully configurable path.

Default is selected by $PREFIX/sbin/fsadm
2017-04-12 21:34:08 +02:00
1095322901 thin: properly check for status for max sizes metadata
When metadata LV size was over DM_THIN_MAX_METADATA_SIZE sectors,
the info() routine was incorrectly trying to match bigger size,
while we do never pass any bigger device.

Fixing a case, where lvs should be displaying status for metadata
LV with 16GB size.
2017-04-12 21:34:08 +02:00
3503ef23e3 cmdline: ensure command struct is defined
Make it clear to Coverity cmd will be defined.
2017-04-12 21:33:47 +02:00
635e7e0c92 libdm: set min,maj
Reset derefered pointers instead of pointers.
2017-04-12 21:33:47 +02:00
3e3f2a53ea dmfilemapd: free path
Cleanup resources before exit.
2017-04-12 21:33:47 +02:00
dfc083d8d6 dmfilemapd: keep 1 byte for \0
Coverity noticed the buffer should have 1 byte for \0.
2017-04-12 21:33:47 +02:00
6c342abb7f commands: improve error message for option rules
When a cmd def RULE fails because of a disallowed
combination of options, improve the error message
to show the option combination, not just the options
that broke the rule.
2017-04-12 14:05:36 -05:00
4b121a1f6f WHATS_NEW: add items since last release 2017-04-12 13:45:37 -05:00
61cfe2d55b commands: add rule for lvconvert commands that create pools
For an lvconvert command that creates a thin pool or cache pool,
--poolmetadata cannot be used with --readahead, --stripes or --stripesize.
2017-04-12 13:33:40 -05:00
19e6c338d3 WHATS_NEW: add recent RAID entries 2017-04-12 19:41:55 +02:00
51a31dbd79 lvconvert: better message on --regionsize
Enhance message on "lvconvert --regionsize size RaidLV".
in case the regionsize does not change and return error.
2017-04-12 19:34:18 +02:00
f5b0697c05 WHATS_NEW_DM: add recent dmsetup and dmfilemapd entries 2017-04-12 17:41:29 +01:00
ba12a2e81a Typo: change loose to lose
loose (v): set free; release
lose (v) : be deprived of or cease to have or retain

We 'lose' redundancy or 'lose' meaning.
2017-04-12 10:28:19 -05:00
532388fad5 lvconvert: fix failing valid regionsize change
Reshape check failed when regionsize changed and current raid type
was provided with no other change requested (stripes or stripesize).

E.g. "lvconvert --type raid6 --regionsize 256K" on a raid6 LV
with != 256K regionsize.

Enable --type in test script.
2017-04-12 14:38:49 +02:00
01b5820d03 lvconvert: add segment type raid10_near
Introducing this alias for "raid10", avoid allocating
reshape space when converting between them.

Resolves: rhbz1441347
2017-04-12 01:28:22 +02:00
7bc85177b0 raid: handle insufficent PVs on takeover from striped/raid0
Remove any newly allocated sub LV (pair) remnants in case
allocation fails due to lag of (parallel) free PV space
and keep initial raid type.

Resolves: rhbz1438013
2017-04-12 00:27:59 +02:00
c7ecf379ab man lvmraid: wrap long lines
Break lines in examples to keep line length under 80.
2017-04-11 15:23:48 -05:00
69c3543855 raid_manip: fix typo warning message 2017-04-11 14:18:57 -05:00
1dfb4a2dae man lvmraid: fix line wrapping in examples 2017-04-11 14:17:08 -05:00
c448dcb349 man lvmraid: use same style as generated pages 2017-04-11 13:20:54 -05:00
04d7444afa lvconvert: require different LV for pool
When convering an LV to a cache or thin LV, require
that an LV being converted to cache pool or thin pool
at the same time be a different LV.
2017-04-11 12:17:14 -05:00
a96c8b46b6 lvconvert: prevent duplicate use of metadata lv
The LV being processed cannot be used as the
pool metadata LV.
2017-04-11 12:11:00 -05:00
e0c169f8b7 man lvmraid: improve text layout 2017-04-11 10:55:02 -05:00
2fd9ae0703 lvconvert: validate vg name prefix for pool metadata name 2017-04-11 10:40:08 -05:00
21da004e58 man lvcreate/lvconvert: minor clean up rewording 2017-04-11 10:21:36 -05:00
a4f07b701a commands: check required option value when matching command
A command def can include a specific constant option value,
but the value was not being checked for optional opts.

e.g. this is an incorrect command and does not match any
command defs:

lvconvert --type cache --cachepool vg/lv

However, it was mistakely being matched to this cmd def,
where the required options match, but the optional options
do not:

lonvert --cachepool LV_linear_striped_raid_cachepool
OO: --type cache-pool, ...

The optional options were mistakely considered matching
because 'cache' and 'cache-pool' were not being compared.
2017-04-10 13:41:47 -05:00
a14a8cef2f signals: fix comparison flaw
commit 9a689fb8f0
fixed SIGINT blocking but introduced a comparision
flaw to sigint_restore().

Related: rhbz1440766
2017-04-10 18:41:28 +02:00
9a689fb8f0 signals: fix SIGINT blocking flaw causing inconsistent metadata
SIGINT isn't blocked properly after a sigint_allow(),
sigint_restore() cycle leading to illicit interruptable
metadata updates.  These can leave corrupted metadata behind.

Issues addressed in this commit:

sigint_allow() fails to set _oldmasked[] members properly due
to an offset by one bug on indexing the members of the array.

It bails out prematurely comparing to MAX_SIGINTS causing nesting
depths to be one less than MAX_SIGINTS.  Fix the comparision.

Correct the related comparison flaw in sigint_restore().

Initialize all sig_atomic_t variables consequently.

Resolves: rhbz1440766
2017-04-10 18:16:09 +02:00
ef3e1013aa lvconvert: cleanup prompting 2017-04-06 19:59:57 +02:00
eb6302c8cb lvconvert: fixe conversion message
When selecting a convenience RAID type only display
the selected type when it changed.  Display proper
current raid type when prompting.
2017-04-06 19:28:32 +02:00
653bca6811 lvconvert: raid1 -> linear prompt
Avoid 2 prompts when downconverting raid1 to linear
(related commit 0f65d7ec3a).
2017-04-06 19:24:11 +02:00
3b1a96b9b3 lvconvert: avoid error message on raid1 -> raid4 conversion
Avoid error message
"Logical Volume *_rimage_0 already exists in volume group,,,"
on takeover conversion from a 2-legged raid1 to raid4
(aiming to reshape it adding images).

Resolves: rhbz1439398
2017-04-06 19:09:05 +02:00
0f65d7ec3a lvconvert: prompt on raid1 image changes
Don't change resilience of raid1 LVs without --yes.

Adjust respective tests.
2017-04-06 18:47:41 +02:00
e350b83d50 raid: reload on removing images
Requesting _raid_remove_images() to commit the
metadata missed to reload the origin causing a
kernel takeover error converting a 2-legged raid1
(with previously removed images) to raid5.
2017-04-06 00:47:34 +02:00
a8d5ada452 man: lvmraid.7 raid6_n_6 fix 2017-04-06 00:35:12 +02:00
d23cad16c9 raid: tidying 2017-04-06 00:06:52 +02:00
1ef1bdab27 lvconvert: allow --type with --regionsize
Allow the combination of both arguments keeping
the raid level but changing the regionssize
(e.g. "lvconvert --type raid1 --regionsize 1M RaidLV"
 on an existing raid1 LV).

Resolves: rhbz1438396
2017-04-06 00:03:16 +02:00
7ccb4825c7 lvchange/lvconvert: fix missing lvmlockd LV locks
lvchange/lvconvert operations that do not require the LV
to already be active need to acquire a transient LV lock
before changing/converting the LV to ensure the LV is not
active on another host.  If the LV is already active,
a persistent LV lock already exists on the host and the
transient LV lock request is a no-op.

Some lvmlockd locks in lvchange were lost in the cmd def
changes.  The lvmlockd locks in lvconvert seem to have
been missed from the start.
2017-04-05 16:46:38 -05:00
c9bc1c1c8c lvchange: tidy switch code in _lvchange_properties_single() 2017-04-05 17:29:31 +02:00
6fdc391bae lvchange: fix missing return value
A return value from lvchange_persistent_cmd() was missed
in commit 1c41898c07
2017-04-05 10:08:01 -05:00
448bf9491a lvmconf: fix systemd unit existence check for lvmconf --services --startstopservices
We have to unset the LoadState variable from previous use when we check
for systemd unit state. We use this variable to check if systemd services
are loaded or not and if it is loaded, we issue systemctl commands to
enable/disable and start/stop the service. We don't issue these commands
if the unit is not loaded to avoid error messages which may confuse users.
2017-04-05 11:06:56 +02:00
afa844817a commands: fix misspelling of option value
(The cmd def parser really needs to catch mistakes
like this as it did when it was external.)
2017-04-04 17:09:35 -05:00
a7d4156a9a lvchange: fix --poll value when set from option
The actual value specified by the --poll y|n option was not
being used.  The way the --poll value is used is hidden
through an indirection where the value is stored in a
global variable at the start of the command, and then the
value is read from there later.  Setting the global
variable early in the command had been lost with the
cmd def changes.
2017-04-04 17:04:45 -05:00
1c41898c07 vgchange/lvchange: fix poll and monitor use
Fill in some gaps where old versions of lvm allowed
--poll and --monitor in combination with other operations,
but those combinations had been lost since the cmd def work.
(The new cmd def code also added some combinations that
had been missed by the old code.)

Changes:

lvchange --activate: add poll and monitor options, and
                     add calls to them in implementation.

lvchange --refresh: add monitor option (poll already there),
                    and call to monitor in implementation.

lvchange <metadata ops>: add poll and monitor options, and
                         add calls to them in implementation.

vgchange <metadata ops>: add poll option (call to poll
                         already in implementation).

vgchange --refresh: remove monitor option (not used by code)

lvchange --persistent y: add poll and monitor options, and
                         add calls to them, and to activate
                         in the implementation. (Making it
                         match the main lvchange metadata
                         command.)

Summary of current usage:

lvchange --activate: monitor, poll
vgchange --activate: monitor, poll

lvchange --refresh: monitor, poll
vgchange --refresh: poll

lvchange --monitor: ok
lvchange --poll: ok
lvchange --monitor --poll: ok
vgchange --monitor: ok
vgchange --poll: ok
vgchange --monitor --poll: ok

lvchange <metadata ops>: monitor, poll
vgchange <metadata ops>: poll
2017-04-04 17:04:45 -05:00
a12b3af033 lvchange: enhance avoiding multiple metadata updates/reloads/backups
Enhance commit 25b5915c9b
to process options requiring immediate metadata commits
and reloads after those we can group together doing just
one commit and an optional reload for the whole group.

Backup metadata after processing options successfully.

Related: rhbz1437611
2017-04-04 23:53:55 +02:00
e7ec9aab8a man: '-pool' regexp 2017-04-04 23:53:28 +02:00
76b70d5058 lvconvert: fix converting hidden lv to pool
A hidden LV can not be converted to a thin pool or cache pool.
2017-04-04 16:47:47 -05:00
b951d04337 help: print all options in abbreviated help output
Don't abbreviate the --help output quite as much
when there are many command defs.  Print all the
options in the cmd defs that are shown.  --longhelp
output is unchanged and includes everything.
2017-04-03 16:36:04 -05:00
29161a145e commands: missing comma in cmd def option list
Does not affect parsing, but keep it consistent.
2017-04-03 16:20:55 -05:00
db579b9e93 help: include cmd def info in verbose output
It can sometimes be important to correlate a
command with its cmd def entry, so include
the cross reference info in help -vv output.
2017-04-03 16:17:37 -05:00
dece723dc7 commands: recognize ignored options 2017-04-03 15:49:24 -05:00
162272e5a5 commands: ignore partial option in most cases
These days --partial is only used with activation in
lvchange/vgchange.  It probably had another meaning
at some point in history which is no longer used,
so ignore it in those cases.

When included in the OO list, the option is advertised in
help/man output, implying it is meaningful to the command,
when in fact the command never uses it.
The IO list means the option won't cause an error if it's
used, but is not displayed as an valid option for the command.
If the option is not included in either OO or IO lists,
using the option would cause a command error, which would cause
problems for anyone is using the option for historical reasons.
2017-04-03 15:43:04 -05:00
51ff707ac8 man: fix description of --partial option 2017-04-03 14:15:29 -05:00
e0f284d372 lvchange: refresh command missing activationmode option 2017-04-03 13:44:35 -05:00
25b5915c9b lvchange: avoid multiple metadata updates/reloads/backups
_lvchange_properties_single() processes multiple command
line arguments in a loop causing metadata updates and/or
backups per argument.

Optimize to only perform one update and/or backup
(but necessary interim ones; e.g. for --resync)
per command run.

Related: rhbz1437611
2017-04-01 02:38:48 +02:00
fb1f38a6f6 tests: fix LD_LIBRARY_PATH
Use only selected paths for finding .so in builddir.
So if builddir constains some embeded subdirs with some more
occurences of project (i.e.  'make rpm' build subdir)
those library paths will not get into list.
2017-03-31 17:12:00 +02:00
970df59f91 cache: scan kallsyms for kernel symbols
With monolithic kernels we can't actually modprobe
for cache modules as they are already compiled-in
and policy modules do not export version symbol.

Reported issue on list:
https://www.redhat.com/archives/dm-devel/2017-March/msg00061.html

Fix will try to look for explicit kernel symbols first before
calling modprobe.
2017-03-31 17:12:00 +02:00
13ca11cc14 lvchange: persistent major/minor processing regression
Optimized change.

Resolves: rhbz1437611
2017-03-31 17:09:33 +02:00
d6ddacf6a1 lvchange: persistent major/minor processing regression
Fix a regression introduced by new command line processing
(see starting commit 1e2420bca8)
causing activation to be rejected in combination with setting
persistent minor device numbers.

Resolves: rhbz1437611
2017-03-31 13:51:39 +02:00
0ed087aae5 man: pregen file change 2017-03-30 20:48:53 +02:00
92ac1da16a man-generator: shutdown stdout buffer
Flush stdout and switch it back to line buffering before exit.
2017-03-30 20:40:44 +02:00
2c4e8254de man-generator: enhance performance
Set block buffering on stdout to
save ~30% time generating manuals.
2017-03-30 19:55:50 +02:00
0da040b1eb man-generator: don't ignore description file errors
In case we provide a description file it has to
succeed opening and reading.  Dynamically allocate
buffer space for it whilst on it.
2017-03-30 19:51:35 +02:00
980e4f673e raid: more coverity issues 2017-03-30 18:39:04 +02:00
c34ab29ec6 raid: favour dm_list_first() 2017-03-30 18:13:27 +02:00
2d75ef3b05 raid: address coverity issues 2017-03-30 18:09:06 +02:00
b3854155d9 man-generator: add '.' to all messages 2017-03-30 17:54:36 +02:00
99dc49c7dd man: add minor regexp 2017-03-30 17:54:02 +02:00
2b46fe5843 dmsetup: replace (f)printf("\n") with putchar/putc 2017-03-30 16:30:50 +01:00
febda60f3d libdm: use correct FMTu32 format specifier for uint32_t 2017-03-30 16:17:19 +01:00
e8d5e05ff5 libdm: fix incorrect format specifier in _stats_resize_group()
The bitmap size in dm_bitset_t[0] is a uint32_t, not uint64_t: use
%u instead of FMTu64.
2017-03-30 10:31:36 +01:00
b8b2b1efd8 dmsetup: Flush ouptut when using --interval 2017-03-30 10:17:32 +01:00
c7e4b97abc libdm: use uint64_t where possible in filemap routines
Use uint64_t where possible and explicit casts elsewhere to avoid
compiler warnings when converting between int, int64_t and
uint64_t.
2017-03-30 10:02:54 +01:00
b823646ace libdm: use size_t for buflen in _stats_group_file_regions() 2017-03-30 10:02:45 +01:00
833b02106d libdm: make _stats_resize_group() num_regions argument uint64_t 2017-03-30 10:02:39 +01:00
722542fabb libdm: make _find_extent() nr_extents argument uint64_t 2017-03-30 10:02:35 +01:00
5e74e43896 dmfilemapd: cast return value of strto* functions when needed 2017-03-30 10:02:31 +01:00
834574cc27 dmfilemapd: use log_sys_error in _filemap_monitor_set_notify
Since _filemap_monitor_set_notify() is only called after daemon
start up it should not use the _early_log() macros. Instead, use
log_sys_error to log errors from the two syscalls in the function.
2017-03-30 10:01:57 +01:00
bfc880994c dmfilemapd: cast sysconf() return value to int 2017-03-30 09:57:58 +01:00
76b6cbea60 dmfilemapd: fix len type in _filemap_monitor_check_file_unlinked()
Make 'len' a size_t to match the return type of readlink(2).
2017-03-30 09:57:58 +01:00
660bd4fe3e dmfilemapd: make filemap_monitor->nr_regions uint64_t 2017-03-30 09:57:58 +01:00
ac6089ee8d libdm: use DM_STATS_GROUP_* constants in dm_stats_create_regions_from_fd 2017-03-30 09:57:58 +01:00
fe0922b8a6 dmsetup: simplify branching in _stats_update_file()
The fallback branch in _stats_update_file() is redundant (since the
branch taken when the daemon starts successfully must jump to the
'out' label anyway): remove it and re-order the conditions to
improve readability.
2017-03-30 09:57:58 +01:00
803b1775ba man: raid cleanup 2017-03-30 00:44:35 +02:00
b6724fa423 man: Copyright 2017-03-30 00:44:35 +02:00
e9921ffd33 man: use variable in Makefile / regexp 2017-03-30 00:44:35 +02:00
2f1fd1584e man-generator: catch missing command name 2017-03-30 00:44:34 +02:00
df86ee8c21 tests: fix typo in makefile
Use properly $(SORT)
2017-03-30 00:38:41 +02:00
a66411bd7a man: fix type
With commit 4af09a94bd unwanted rename  of
target happened - restore it.
2017-03-30 00:38:41 +02:00
dfdd6ccf3b vgrename: use long enough buffer for path
Use PATH_MAX when creating buffers for rename.
2017-03-30 00:38:41 +02:00
4b3d71212f libdm: use log_sys_error if dmfilemapd exec fails
Use log_sys_error rather than log_error if execvp() fails:

  /mnt/redhat/xdoio.13752.XIORQ: Created new group with 2 region(s) as group ID 0.
  # execvp() failed.

vs:

  /var/lib/libvirt/images/rhel7-vm1.qcow2: Created new group with 884 region(s) as group ID 0.
  dmfilemapd: execvp failed: No such file or directory
2017-03-29 21:38:15 +01:00
5994ed9df2 dmsetup: always close fd when leaving _stats_update_file() (coverity) 2017-03-29 18:34:57 +01:00
11749e7adb dmsetup: do not start dmfilemapd if region creation fails (coverity) 2017-03-29 18:34:51 +01:00
6740eb1c2b libdm: do not attempt filemap cleanup if dm_stats_list() fails (coverity) 2017-03-29 18:34:43 +01:00
f86c1f5d0a libdm: abort filemap update if pool allocation fails (coverity) 2017-03-29 18:34:38 +01:00
bc5d67884f libdm: do not leak FIEMAP extent buffer if pool allocation fails (coverity) 2017-03-29 18:34:30 +01:00
13426092e9 dmfilemapd: free region table at end of _update_regions() (coverity) 2017-03-29 18:34:24 +01:00
f66bc3dab0 dmfilemapd: fix off-by-one in fd comparison (coverity)
The function _filemap_monitor_check_file_unlinked() attempts to
test whether a fd value should be closed by comparison to zero:

        if ((fd > 0) && close(fd))
                log_error("Error closing fd %d", fd);

The test should be '>=' since 0 is a valid file descriptor.
2017-03-29 18:34:19 +01:00
8658bbe3ee dmfilemapd: always close link check file descriptor (coverity)
Similar to 40fb91a, but for the file descriptor opened using the
link path reported by /proc/<self>/fd/<fd>.

The daemon opens a new file descriptor from /proc/<self>/fd when
checking for an unlinked file with mode=inode. Ensure that it is
always closed even if the same file test fails.
2017-03-29 18:34:11 +01:00
7db51a6bed dmfilemapd: always terminate link buffer after readlink(2) (coverity) 2017-03-29 18:34:05 +01:00
70bb726678 dmfilemapd: always close check file descriptor (coverity)
The daemon opens a new file descriptor from fm->path when checking
for an unlinked file with mode=inode. Ensure that it is always
closed even if the same file test fails.
2017-03-29 18:33:53 +01:00
43fdbb8aeb dmfilemapd: use *argv[0] when testing for absolute path (coverity)
The path argument check in dmfilemapd incorrectly tests for:

  if (argv[0] == '/')

Rather than testing the 1st character in the string pointed to by
argv[0].
2017-03-29 18:33:42 +01:00
b5252a51a5 dmfilemapd: pass correct dirp to closedir() 2017-03-29 16:54:44 +01:00
481a522dd7 dmfilemapd: do not closdir(pid_d) unless it is open 2017-03-29 16:48:32 +01:00
d71071a1af dmfilemapd: log closedir errors with log_sys_error() 2017-03-29 16:04:15 +01:00
5dfd35f2f8 dmstats: Fix path to static dmstats 2017-03-29 09:04:56 +02:00
5012be326d man: ranges/LV names/symbolic use regexp 2017-03-29 02:27:10 +02:00
4af09a94bd man: simplify by avoiding different headers on de-duplication of lvmconfig, lvm-config and lvm-dumpconfig 2017-03-29 01:44:09 +02:00
6742137964 man: de-duplicate lvmconfig, lvm-config and lvm-dumpconfig manuals 2017-03-29 00:22:15 +02:00
162552041f spec: Add dmfilemapd 2017-03-28 21:52:50 +02:00
a41d5b6491 dmfilemapd: Fix install target 2017-03-28 21:52:30 +02:00
3aab873199 man: regexp readability / use $(SED) 2017-03-28 17:51:22 +02:00
0c2f7ed49a post-release 2017-03-28 16:14:03 +01:00
396377bc03 pre-release
Removing some unused new lines and changing some incorrect "can't
release until this is fixed" comments.  Rename license.txt to make
it clear its merely an included file, not itself a licence.
2017-03-28 16:11:35 +01:00
b9399f2148 man: pre-generated files weren't committed 2017-03-28 01:32:59 +01:00
19a72e601f man: fix / typo 2017-03-28 00:27:04 +02:00
7f31261844 man: enhance man postprocessing regexp 2017-03-28 00:17:43 +02:00
88e408b8ed tests: update to better fit
Die is automatic on 'error' result
Cleanup everything on 'regular' code path.
2017-03-27 20:50:19 +02:00
e3a3cf01eb cleanup: use more common FMTd64 type
We use 'd' for plain singed integers.
2017-03-27 20:50:19 +02:00
78d004efa8 build: fix x32 arch
This patch fixed lvm2 compilation running on x32 arch.
(Using 64bit x86 cpu features but running on 32b address space,
so consuming less mem in VM).

On x32 arch 'time_t' is 64bit while 'long' is 32bit.
2017-03-27 20:50:19 +02:00
36cac41115 man-generator/man/help: simplify hyphen escaping
Commits a29bb6a14b
    ... 5c199d99f4
narrowed down on addressing the escaping of hyphens
in the dynamic creation of manuals whilst avoiding
them in creating help texts.  This lead to a sequence
of slipping through hyphens adrressed by additional
patches in aforementioned commit series.

On the other hand, postprocessing dynamically man-generator
created and statically provided manuals catches all hyphens
in need of escaping.

Changes:
- revert the above commits whilst keeping man-generator
  streamlining and the detection of any '\' when generating
  help texts in order to avoid escapes to slip in

- Dynamically escape hyphens in manaual pages using sed(1)
  in the respective Makefile targets

- remove any manually added escaping on hyphens from any
  static manual sources or headers
2017-03-27 16:49:39 +02:00
6165e09221 lvchange: reject setting all raid1 images to writemostly
raid1 doesn't allow to set all images to writemostly because at
least one image is required to receive any written data immediately.

The dm-raid target will detect such invalid request and
fail it iwith a kernel error message.

Reject such request in uspace displaying a respective error message.
2017-03-26 20:28:04 +02:00
5c199d99f4 man: a few more missed '-' to escape 2017-03-25 03:40:02 +01:00
66b2084b96 man-generator: more escaped '-' 2017-03-24 18:57:45 +01:00
d823c65d50 man-generator: fix buffer length calculation 2017-03-24 18:33:03 +01:00
25c841af00 make: Don't hard-code SHELL as /bin/sh 2017-03-24 15:29:17 +00:00
4046f9bd95 man/help: avoid escaping of '-' with --help 2017-03-24 15:14:21 +01:00
e9433a9de9 WHATS_NEW: man-generator escape '-' 2017-03-24 14:31:19 +01:00
9354ce6045 man-generator: cleanup escape '-' 2017-03-24 14:27:59 +01:00
10e0a5066e man-generator: emit escaped '-' 2017-03-24 04:00:47 +01:00
5eec3de41f man: escape all single '-' 2017-03-24 02:46:11 +01:00
93467f0d9f man: revert erouneous '-' escapes in Makefine.in 2017-03-24 01:39:50 +01:00
a29bb6a14b man: escape all double '-' 2017-03-24 01:03:58 +01:00
2eaca7ab63 tools: Reinstate lvm script processing.
We check for a script if the command isn't recognised (ENO_SUCH_CMD).
(Also added a few comments and fixed some whitespace.)
2017-03-23 23:20:53 +00:00
fe3b9bb7d4 libdm: typo 2017-03-24 00:12:41 +01:00
6471bb2c41 commands: improve error message for unknown command
when running "lvm foo".
2017-03-23 03:35:06 -05:00
0dabe7237c commands: fix commands with run with path basename
The recent command definitions commit took the command
name from argv[0] without applying basename to the value,
so a pathname, e.g. /usr/sbin, would cause lvm to not
recognize the command name.
2017-03-23 03:06:07 -05:00
e8362b4cb7 tools: Show configuration command line in lvm version.
Also update configure.in with some items recently added to the tree.
2017-03-23 01:01:35 +00:00
b84bf3e8cd raid: adjust to misordered raid table line output
This commit supersedes reverted 1e4462dbfb
to avoid changes to liblvm and the libdm API completely.

The libdevmapper interface compares existing table line retrieved from
the kernel to new table line created to decide if it can suppress a reload.
Any difference between input and output of the table line is taken to be a
change thus causing a table reload.

The dm-raid target started to misorder the raid parameters (e.g. 'raid10_copies')
starting with dm-raid target version 1.9.0 up to (excluding) 1.11.0.  This causes
runtime failures (limited to raid10 as of tests) and needs to be reversed to allow
e.g. old lvm2 uspace to run properly.

Check for the aforementioned version range in libdm and adjust creation of the table line
to the respective (mis)ordered sequence inside and correct order outside the range
(as described for the raid target in the kernels Documentation/device-mapper/dm-raid.txt).
2017-03-23 01:20:00 +01:00
1bf90dac77 Revert "raid: adjust to misordered raid table line output"
This reverts commit 1e4462dbfb
in favour of an enhanced solution avoiding changes in liblvm
completetly by checking the target versions in libdm and emitting
the respective parameter lines.
2017-03-23 01:19:41 +01:00
14c4d32247 commands: fix combined thin pool and vol create defs
Fixes command defs related to creating a new thin pool and
then a new thin lv in the new pool.

1. lvcreate --size --virtualsize --thinpool
   Needs a cmd def, it was missing.
   The def is unique by the three required
   options: size, virtualsize and thinpool.

2. lvcreate --size --virtualsize --thinpool VG
   Needs a cmd def, it was missing.
   The def is unique by the three required
   options: size, virtualsize and thinpool,
   and one required positional arg: VG.

3. lvcreate --thin --virtualsize --size LV_new|VG
   This existing def should not accept an optional
   --type thin, which if used makes it indistinct
   from another def.

4. lvcreate --size --virtualsize VG
   This existing def should not accept an optional
   --type thin or --thin, which if used makes it
   indistinct from other defs (e.g. 3)
2017-03-21 22:04:01 -05:00
3be2e61c9f Revert "lvcreate: continue to accept --thinpool with -L and -V but not -T"
This reverts commit 642d682d8d.

Using the thinpool option with this cmd def makes it
indistinct from other cmd defs where thinpool is a
required option.
2017-03-21 22:01:19 -05:00
7126fb13e7 metadata: cleanup flags definition to be consistent
Use shift bitops throughout segtype.h.
2017-03-22 00:29:49 +01:00
1810162b51 WHATS_NEW: adjust to misordered raid parameters 2017-03-21 18:18:58 +01:00
1e4462dbfb raid: adjust to misordered raid table line output
The libdevmapper interface compares existing table line retrieved from
the kernel to new table line created to decide if it can suppress a reload.
Any difference between input and output of the table line is taken to be a
change thus causing a table reload.

The dm-raid target started to misorder the raid parameters (e.g. 'raid10_copies')
starting with dm-raid target version 1.9.0 up to (excluding) 1.11.0.  This causes
runtime failures (limited to raid10 as of tests) and needs to be reversed to allow
e.g. old lvm2 uspace to run properly.

Check for the aforementioned version range and adjust creation of the table line
to the respective (mis)ordered sequence inside and correct order outside the range
(as described for the raid target in the kernels Documentation/device-mapper/dm-raid.txt).
2017-03-21 18:17:42 +01:00
642d682d8d lvcreate: continue to accept --thinpool with -L and -V but not -T
lvcreate --thinpool POOL1 -L 100M --virtualsize 100M snapper_thinp

https://bugzilla.redhat.com/1434027

(The general rule is that a command is accepted if it is unambiguous.
The combination -L -V --thinpool uniquely identifies the operation.)
2017-03-20 22:04:37 +00:00
b3e833c777 man-generator: Remove unused variable.
man-generator.c:2976:6: warning: variable "sep" set but not used
2017-03-20 16:55:30 +00:00
862ca6e8b7 lvmdbusd: Rename ee to got_external_event
This variable is global, make it more descriptive.
2017-03-20 10:08:39 -05:00
b65a9230a3 lvmdbusd: Update state during pv move
Periodically update the state during pv move so that all the different
dbus objects reflect something close to reality during the process.
2017-03-20 10:08:39 -05:00
3ead4fb7ac lvmdbusd: Limit state refreshes for udev events
Udev events can come in like a flood when something changes.  It really
doesn't do us any good to refresh the state of the service numerous times
when 1 would suffice.  We had something like this before, but it was
removed when we added the refresh thread.  However, we have since learned
that we need to sequence events in the correct order and block dbus
operations if we believe the state has been affected, thus udev events are
being processed on the main work queue.  This change limits spurious
work items from getting to the queue.
2017-03-20 10:08:39 -05:00
7eeb093fdd lvmdbusd: Call add_no_notify for *move commands
Missed this in change when "add_no_notify" was added.  This was causing
extra external events to process when we did moves.
2017-03-20 10:08:38 -05:00
2dc71fc291 lvmdbusd: Only disable notify_dbus after getting external event
If we always disable the sending of notify dbus events then in the case
where all the users are lvm dbus users we will be in udev handling mode
until at least 1 external lvm command occurs.  Instead we will not disable
notify dbus until after we get at least 1 external event.  This makes the
service get into the correct mode of operation faster.
2017-03-20 10:08:38 -05:00
17b56a4aed tests: early detect leaking error dev
lvconvert should not leak 'error' device.

(This patch is not fix the problem, just makes it more easily visible
instead of more confusing 'clvmd' trace).
2017-03-20 14:18:50 +01:00
07040942ed man: advise against mirrored mirror log 2017-03-17 11:54:39 -05:00
8d7be8f5df help: align option list in pv/lv/vgchange cases
Align one-required options like is done for
optional options.
2017-03-17 11:23:38 -05:00
fec2ea76cf raid: check target version for shrink support
Starting with dm-raid target version 1.9.0 shrinking of mapped devices is supported.
Check for support being present in lvresize and lvreduce.

Related: rhbz1394048
2017-03-17 16:46:33 +01:00
17a8f3d6f0 raid: conditionally reject convert to striped/raid; fix
Fix a logic flaw introduced in commit 17bee733d1
preventing e.g. striped -> raid5 conversions.

Related: rhbz1191935
Related: rhbz1366296
2017-03-17 16:03:35 +01:00
6ebf39da91 WHATS_NEW: conditionally reject raid convert 2017-03-17 14:51:10 +01:00
76709aaf39 raid: cleanup; remove unused function
Remove unused function (lv_has_constant_stripes() is used instead).
2017-03-17 14:24:44 +01:00
07ea9887d3 tests: raise min dm cache version
Since we want to test different cache policies with profiles mq&smq
raise version to 1.8.

TODO: maybe split in more tests so older targets can test here as well.
N.B.: passthrough is also not supported with version 1.3
2017-03-17 14:22:33 +01:00
4a271e7ee7 properties: only thin-pool provides discards
Quering non-thin-pool segment for discard property may lead
to intenal error if the segment had set 'out-of-range' value,
so only thin-pool is allowed, for other it returns NULL.
2017-03-17 14:22:33 +01:00
d211c98581 lvm2app: correct internal API changes
Internal library gets more strict about setting discard and
zero_new_blocks parameter.
2017-03-17 14:22:33 +01:00
e0ea569045 raid: cleanup
Move function _raid45_to_raid54_wrapper() to avoid superfluous declaration.
2017-03-17 14:14:42 +01:00
1520fec3e8 raid: name variables consistently
Related: rhbz1191935
Related: rhbz1366296
2017-03-17 14:04:03 +01:00
17bee733d1 raid: conditionally reject convert to striped/raid0*
If SubLVs to be removed still exist after an image removing
conversion (i.e. "lvconvert --yes --force --stripes N "
with N < total stripes) any request to convert to a different
striped/raid* level has to be rejected until after those freed
SubLVs got removed by running the aforementioned lvconvert again.

Add tests to check conversion to striped/raid* gets rejected.
Enhance a test comment.

Related: rhbz1191935
Related: rhbz1366296
2017-03-17 13:58:54 +01:00
5e7bc8d854 man: Build man-generator in tools dir.
Use ln to make a copy of command.c for compilation with different DEFS
then handle dependencies the normal way.
2017-03-16 23:10:40 +00:00
270ed9bc90 man: Preserve template variables in pre-generated pages. 2017-03-16 23:08:59 +00:00
0c74afa1c6 make.tmpl: Support per-object DEFS.
Same as CFLAGS.
2017-03-16 23:03:03 +00:00
2d00767394 tools: Avoid man-generator compilation warnings.
Unused variables and make fns with missing prototypes static.
2017-03-16 22:39:04 +00:00
ad4158bac7 man: lvmraid(7) clarifications 2017-03-16 23:10:57 +01:00
4a3e30d102 WHATS_NEW: ensure raid6 upconversion restrictions 2017-03-16 22:33:08 +01:00
b917b12e2c WHATS_NEW: adjust mirror+raid DSOs to lvconvert --repair 2017-03-16 22:27:30 +01:00
b0336e8b3c lvconvert: ensure upconversion restrictions
Ensure minimum number of 3 data stripes on conversions to raid6.

Add test for it.

Resolves: rhbz1432675
2017-03-16 22:10:32 +01:00
76b843a4bf test: adjust to proper dm-raid target version
Adjust to final target version 1.10.1 supporting reshape
properly and to recently changed report field specifications
(e.g. rehape_len_le) to allow these tests to run.

Lower mirror region size to suite the tiny test VG.
2017-03-16 21:17:58 +01:00
a37bb7b2a5 dmeventd: adjust mirror/raid DSOs to new repair design
Previous commit 506d88a2ec introduced disabling lvmetad on repairs.

Avoid calling lvscan and use of any --config options altogether
in the mirror and raid DSOs.

Related: rhbz1380521
2017-03-16 21:05:05 +01:00
73d028023a lvmetad: fix bug in snprintf of disable reason 2017-03-16 12:15:40 -05:00
c8719d4e94 WHATS_NEW: disable lvmetad for repair 2017-03-16 11:56:19 -05:00
506d88a2ec lvconvert: disable lvmetad for repair
Repairing missing devices does not work reliably
with lvmetad, so disable lvmetad before repair.
A standard lvmetad refresh (pvscan --cache) will
enable lvmetad again.
2017-03-16 11:50:36 -05:00
e5b6f2685a dmeventd: reintroduce fix mirror DSO to work with lvmetad
Commit 07ded8059c assumed that the mirror is blocked which is not the case.

It is accessible, degraded and in need of repair because some of its legs
(partially) failed.  Any auto-repair via dmeventd fails though because
of lvmetad not providing proper data about the failed PV(s).  That's why
this workaround got introduced in commit 76f6951c3e until we get to
the lvmetad interaction core issue.

Mind any mirror auto-repair failure is caused by such lvmetad interaction
problems not yet solved so disabling lvmetad works as a resort as elaborated
on in the related bz.

Reintroducing the interim solution.

Resolves: rhbz1380521
2017-03-16 14:19:06 +01:00
a87715b6fd spec: Disable sanlock only, keep lockd_dlm enabled 2017-03-16 13:03:25 +01:00
19b65a3d76 spec: Replace remaining %define by %global 2017-03-16 13:03:24 +01:00
7067514c9b spec: Use %global instead of %define for constants
Using %define is now discouraged by Fedora Packaging Guidelines
2017-03-16 13:03:24 +01:00
5ba82a16db spec: Update requirements for lockd
lockd requires sanlock >= 3.3.0
2017-03-16 13:03:24 +01:00
cf0bf4b314 spec: Profiles are not %config(noreplace)
These files are just examples and should not be edited by user.
2017-03-16 13:02:24 +01:00
a4a6a7a526 man: Make dmfilemapd.8 optional 2017-03-16 12:26:51 +01:00
2fd5c8e908 spec: lvmchange is built-in command 2017-03-16 11:44:10 +01:00
affe055462 man: Handle empty MAN8GENERATED 2017-03-16 11:35:08 +01:00
51b9de7249 tests: better disk delay
Delay only writable extents.
Skip zeroing for earlier lvcreate finish.
2017-03-16 08:49:52 +01:00
7fa08ae4e8 tests: add missing --yes 2017-03-16 08:44:44 +01:00
e9b5a455e1 tools: Drop unused e2fsadm refs (replaced by fsadm). 2017-03-16 02:24:39 +00:00
8ef93c756e man: Include lvmchange/lvmsar/lvmsadc content in lvm.8
Remove separate lvmchange man page as the external command has also been
removed.
2017-03-16 02:09:51 +00:00
b0430b975b man: Reinstate previous lvmsar and lvmsadc pages.
Avoid listing all the common options for obsolete commands.
2017-03-16 01:49:40 +00:00
1cdaa8144d lvmsar/lvmsadc: Mention dmstats when run. 2017-03-16 01:36:02 +00:00
4f86519845 lvmchange: Move to a built-in command.
Has been obsolete since LVM1 and it's clear we'll never implement this.
2017-03-16 01:09:29 +00:00
9729fc4f8c man: Remove blank lines from pregenerated files 2017-03-16 00:50:27 +00:00
6d6ab310e5 man: reinstate lvmchange man page for now 2017-03-16 00:46:35 +00:00
07ded8059c mirror: revert 76f6951c3e
Effectively revert whole  76f6951c3e.
We need to figure out some other solution.

At this moment usage of --config  with 'repair' of blocked mirror
is 'freezing' combination.
2017-03-16 01:17:57 +01:00
4a727a3ccd raid: use 64bit arithmetic
Coverity - keep  multiplication for size cals in 64bit
(otherwise it's just 32b x 32b)
2017-03-16 01:02:10 +01:00
e3a51537c5 coverity: make sure segtype pointer is valid 2017-03-16 01:02:10 +01:00
42b970d4f3 libdm: fix endless loop
Coverity noticed endless loop (i not being changed).

TODO: test coverage
2017-03-16 01:02:10 +01:00
2a139993b4 thin: remove unneeed test for NULL
In this API NULL is not valid parameter so do not check for it.
2017-03-16 01:02:10 +01:00
0dcb928d1e coverity: update models
Latest versions do get quite  strange - so let's use suggestions
from their authors...
2017-03-16 01:02:10 +01:00
115fd205de mirror: avoid scanning
While mirror is blocked we can't try to scan device.
Regression introduce by previous commit
76f6951c3e.
2017-03-16 01:02:10 +01:00
849ab38e3c man: Minor clarifications and grammar corrections for lvmraid.7 2017-03-15 18:19:29 -05:00
7b6ee130cc man: remove blank lines from end/des files
which produce unwanted blank lines in some output
formats.
2017-03-15 15:59:43 -05:00
5c5df43ea3 help: fix missing newlines
Recent commits to remove newlines from man output
accidentally removed some newlines from help output.
2017-03-15 11:40:59 -05:00
60eb74a27a man: remove blank lines in included files 2017-03-15 11:30:34 -05:00
7e9bc77865 man: remove blank lines
Blank lines in the man source sometimes appear as extra
blank lines in the output, so remove them.
2017-03-15 11:05:31 -05:00
f536c53aee man: specify man-generator path 2017-03-15 01:36:12 +00:00
1dc1a1cedb make: Support for 'make -R'.
Aim to be self-sufficient.
2017-03-15 01:31:11 +00:00
531d7c97e7 man: remove more unnecessary line breaks
in case they cause extra blank lines in some output formats.
2017-03-14 16:28:20 -05:00
23d59c6fc1 man: remove redundant line breaks
unecessary .br and .P
2017-03-14 15:04:58 -05:00
5942fd18db args: clarify repeated --options lists 2017-03-14 13:52:09 -05:00
88b05391ff man clvmd: mention attempt for deactivate
attempt is always the case, but mention it again
2017-03-14 10:17:46 -05:00
c891918174 man: Adjust some wording and update examples style. 2017-03-14 14:55:36 +00:00
ca905681cc man: Revise internal man page generation process.
For each section 8 man page, a .8_gen file is created from one of:
  .8_main            - Old-style man page - content used directly
  .8_des and .8_end  - Description and end section of a generated page
  .8_pregen	     - Pre-generated page used if the generator fails

Other man sections are not generated and use the suffix .5_main or .7_main.

Developers should use 'make generate' to regenerate the .8_pregen files.
2017-03-14 00:47:46 +00:00
38292ca1d0 commands: fix command matching for unused options
When a given command:

- matches command definition A based on required options,
  but uses optional options that are not accepted by A.

- matches command definition B based on required options,
  (but fewer required items than A), and uses no
  unaccepted optional options.

then B is the correct choice.  Command A would fail because
of the unaccepted optional options.  The logic was mistakenly
letting A win because it had a greater number of required option
matches, without accounting for the optional option mismatches.
2017-03-13 13:37:07 -05:00
49cd54fc3a commands: fix lvcreate mirrors/stripes options
Systematically outline every combination of:
--type striped, --type mirror, --type raid, --mirrors, --stripes
and make sure each is assigned to one specific cmd def.

This revealed that a new command def is needed for
lvcreate that uses both --mirrors and --stripes
but no --type option.

The use of LVCREATE_RAID shortcut for an option set
resulted in mirrors/stripes being included in optional
opts set when they were already in the required list.
2017-03-13 13:37:07 -05:00
46b735c937 lvmetad: fix segfault on i386
Sending %d as format argument in lvmetad_vg_remove_pending() will cause
segfaults in config_make_nodes_v() when va_arg() casts to int64_t. Also, it is
clearly advertised in the lvm source code that using plain %d is prohibited, so
let's switch to FMTd64.

Signed-off-by: Christian Brauner <christian.brauner@ubuntu.com>
2017-03-13 13:37:07 -05:00
5f2c942000 raid: check more cautious on region size changes
Add additional checks to avoid calling _region_size_change_requested()
with bogus actual arguments.
2017-03-13 17:46:56 +01:00
77a7ed065f dmfilemapd: ensure path argument is absolute
Require that the path argument to dmfilemapd be an absolute path
and document this in tool output, libdevmapper.h and dmfilemapd.8.

The check is also enforced by dm_stats_start_filemapd() to avoid
forking a new process with an invalid path argument.
2017-03-13 11:44:05 +00:00
9b0aba5fe9 dmfilemapd: return error for wrong number of args
The initial check on argc incorrectly returns 1 when the wrong
number of arguments are present, causing a segfault in main()
when no arguments are given:

  # dmfilemapd
  Wrong number of arguments.
  usage: dmfilemapd <fd> <group_id> <path> <mode> [<foreground>[<log_level>]]
  Segmentation fault (core dumped)
2017-03-13 11:09:11 +00:00
66760f9673 man: fix typo 2017-03-10 22:48:16 +01:00
09ad36fb9b report: fix lv_size with reshape space allocated
Commit f4b30b0dae was about displaying visible LV size
when reshape space is allocated.  Take parity devices
into account when displaying the user visible LV size.
2017-03-10 22:46:20 +01:00
c8671f6f79 commands: use correct relative signs with mirror option
As was recently done with relative signes for sizes/extents,
limit the signs used with the mirrors option, e.g.
lvcreate --mirrors now does not accept or advertise an
optional minus sign with the value.  lvconvert --mirrors
accepts +|-.
2017-03-10 15:41:29 -06:00
164d4a309c man: add more info/examples to lvmraid(7)
Add a warning about maximum supported numbers of stripes
with striped LVs realtive to RAID conversions.

Add examples for a more elaborate, multi-step conversion
from linear to striped (and vice versa).

Shrink lvs examples output.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-10 22:40:22 +01:00
15682270f4 commands: fix lvconvert options for mirrors/stripes
The LVCONVERT_RAID shortcut for including options ended
up including mirrors/stripes as optional opts in defs where
they were already required, or in defs where they would
not be used.  Remove the option set and specify in each
case only the options wanted.
2017-03-10 14:05:15 -06:00
5d3e870946 raid: fix compile time warning 2017-03-10 20:38:16 +01:00
53f5cf0af0 tests: cache profile and metadata2
New tests trying to cover support syntax variants.
A lot it still missing...
2017-03-10 19:33:02 +01:00
a11b875074 cleanup: use FMTu
Replace some PRIu with FMTu for formating strings.
2017-03-10 19:33:01 +01:00
d11b8eef89 cleanup: easier code 2017-03-10 19:33:01 +01:00
52935b5834 cache: enhance lvdisplay for cache volumes
Better support for lvdisplay.
By default info about running (in kernel) cache status is printed.
To get 'segtype' info, user runs: 'lvdisplay -m',  example:

  --- Logical volume ---
  LV Path                /dev/vg/lvol0
  LV Name                lvol0
  VG Name                vg
  LV UUID                Y4uWuN-TBGk-duer-aPWl-yBWn-iFFR-RU1gg1
  LV Write Access        read/write
  LV Creation host, time linux, 2017-03-01 20:52:39 +0100
  LV Cache pool name     lvol2
  LV Cache origin name   lvol0_corig
  LV Status              available
  # open                 0
  LV Size                12,00 MiB
  Cache used blocks      10,42%
  Cache metadata blocks  0,49%
  Cache dirty blocks     0,00%
  Cache read hits/misses 112 / 34
  Cache wrt hits/misses  133 / 0
  Cache demotions        0
  Cache promotions       20
  Current LE             3
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           253:0

  --- Segments ---
  Logical extents 0 to 2:
    Type		cache
    Chunk size		64,00 KiB
    Metadata format	1
    Mode		writethrough
    Policy		smq
      Setting		migration_threshold=100000
2017-03-10 19:33:01 +01:00
4d2b1a0660 cache: enable usage of --cachemetadataformat
lvcreate and lvconvert may select cache metadata format when caching LV.
By default lvm2 picks best available format.
2017-03-10 19:33:01 +01:00
7b748b7cb8 cache: allow to specify cachemetadataformat
OO_LVCREATE_CACHE accepts --cachemetadataformat.

Support new option --cachemetadataformat auto|1|2 for caching.
Word 'auto' can be also be given as '0'.
2017-03-10 19:33:01 +01:00
0a9b52f7a4 cache: reporting cache metadata format
Report CMFmt column with cache metadata format version.

Report KMFmt column with 'kernel cache metadata format version' for device.
(a value reported from status).

(Update 'CacheMode' to name 'Cache' as primary segtype).
2017-03-10 19:33:01 +01:00
64d3f05aa1 cache: validation for cache_metadata_format
Only  cache-pool segtype may store cache_metadata_format.
Only supported values are 0,1,2
Format 2 requires LV status uses LV_METADATA_FORMAT.
Format 0 (unselected) or 1 shall not set this 'incompatible' status.
2017-03-10 19:33:01 +01:00
825c16e57e cache: use DM_CACHE_FEATURE_METADATA2 with libdm
Call libdm  with new feature flag when metadata format 2 is selected
and available in kernel cache target.
2017-03-10 19:33:01 +01:00
518b814cdb cache: LV supports cache segs with metadata format
Cache pool read/writes metadata_format within its segment type..

For CachePoolLV unselected metadata format is NOT stored in metadata.

For CacheLV when metadata format is not present/selected in lvm2 metadata,
it's automatically assumed to be the version 1 (backward compatible).

To ensure older lvm2 will not 'miss-read' metadata with new version 2,
such LV is marked with METADATA_FORMAT status flag (segment is
specifying metadata format). So when cache uses metadata format 2,
it will become inaccesible on older system without such support.
(kernel dm cache < 1.10,  lvm2 < 2.02.169).
2017-03-10 19:33:01 +01:00
4a394f410d cache: introduce allocation/cache_metadata_format
Add new profilable configation setting to let user select
which metadata format of a created cache pool he wish to use.

By default the 'best' available format is autodetected at runtime,
but user may enforce format 1 or 2 ATM.

Code also detects availability for metadata2 supporting cache target.

In case of troubles user may easily Disable usage of this feature
by placing 'metadata2' into global/cache_disabled_features list.
2017-03-10 19:33:01 +01:00
bb20fac4ab libdm: maintain binary interface for new FEATURE flag
Older library version was not detecting unknown 'feature' bits
and could let start target without needed option.

New versioned symbol now checks for supported feature bits.
_Base version keeps accepting only previously known features and
mask/ignores unknown bits.

NB: if the older binary passed in 'random' bits, it will not get
metadata2 by chance. New linked binary get new validation function.
Library user is required to not pass 'trash' for unsupported bits,
as such calls will be rejected.
2017-03-10 19:33:01 +01:00
ddd5a76801 libdm: support cache metadata2 feature flag
Dm cache target version 1.10 introduces new cache metadata format
(upstream kernel >=4.11).

New format is enable by passing new target feature flag metadata2.
Interace side on libdm uses DM_CACHE_FEATURE_METADATA2.
This feature bit is now also recognized on status
and set in 'feature_flags' field of dm_status_cache structure.

Code also adds check for 'highest' supported feature flag bit.
So it rejects properly any 'unknown' feature bit set by application.
2017-03-10 19:33:01 +01:00
bf79fb1a33 libdm: better code to enforce writethrough
Better code to enforce writethrough caching for cleaner policy.
Only check for cleaner when DM_CACHE_FEATURE_PASSTHROUGH or
DM_CACHE_FEATURE_WRITEBACK is set.
2017-03-10 19:33:01 +01:00
edf5e43f9a libdm: passthrough checks traling space char
When checking for passthrough length, check also for extra ' ' char
just like with other feature strings.
2017-03-10 19:33:01 +01:00
c717011f8e tests: use LVM_SYSTEM_DIR for etc
Instead of hardcoding etc/ dir  use $LVM_SYSTEM_DIR.
2017-03-10 19:33:01 +01:00
a9b78d26b1 cleanup: minor cosmetics
Update some return value to match return type.
Drop unused function and declaration.
2017-03-10 19:33:01 +01:00
21c265adcf cache: improve profile support for cache_set_policy 2017-03-10 19:33:01 +01:00
4d0793f0ec pool: rework handling of passed args
As now we can properly recognize all paramerters for pool creation,
we may drop PASS_ARG_  defines and rely on '_UNSELECTED' or 0 entries
as being those without user given args.

When setting are not given on command line - 'update' function
fill them from profiles or configuration. For this  'profile' arg
was needed to be passed around and since  'VG' itself is not needed,
it's been all replaced with 'cmd, profile, extents_size' args.
2017-03-10 19:33:01 +01:00
7c52d550e9 thin: single formula for estimation
Share the same formula for estimation chunk size or metadata size.
Use uint32_t matching type.
2017-03-10 19:33:00 +01:00
1cfc1be85d parser: enable --metadataprofile for pool lvconvert
Lvconvert can use values from profile when caching.
2017-03-10 19:33:00 +01:00
07c24736e0 parser: allow --zero for pool conversion 2017-03-10 19:33:00 +01:00
46820bfff3 lvconvert: share function for cache params
Reuse same code for getting/setting cache parameters with lvcreate.

So there is single one place how to get vars from profiles and configs.

Variables declarations are moved to start of function and
there is no need to initialize them as they are always
defined by functions get_cache_params() and get_pool_params().
2017-03-10 19:33:00 +01:00
298d12c459 lvcreate: do not round cache volumes on cache chunks
Since cache chunk might be huge and there is no technical need
to enforce rounding and there is actually more 'real' VG space
used then necessary - keep rounding on 'chunk' bounrary only
for thin volumes - where it's the space used anyway.

NB: we support conversion of any-size 'existing' LV into cached LV.
2017-03-10 19:33:00 +01:00
f24a1f06b2 lvcreate: respecting profile settings 2017-03-10 19:33:00 +01:00
36003df7e3 cache: extend usability of cache_set_params
Fix missing reset of '*settings' pointer when no args were given.

Handle cache_chunk settings like all other settings, so it is properly
updated only with non-zero settings and the existing cache-pool
chunk_size is not being reconfigured.
2017-03-10 19:33:00 +01:00
dcf038c7a6 cache: improve support for profile for cache settings
User can specify metadata profile which stores important cache
geometry data for easy configuration.

Fix missing support for getting chunk_size, cache_mode, cache_policy
for a cache/cache pools volumes from configuration or metadata profile.
2017-03-10 19:33:00 +01:00
c598e65de9 cache: get and set cache params 2017-03-10 19:33:00 +01:00
861992d874 lvconvert: replacing with goto
Split-off patch that just replaces returns with 'goto bad'
so there is single place to release  policy_settings.

In the next patch we will start to use some shared
function call between lvconvert and lvcreate
(effectively restoring previous logic which has got lost).
2017-03-10 19:33:00 +01:00
2d11fc695e cache: set chunk_size as first param 2017-03-10 19:33:00 +01:00
4184331965 cache: use UNSELECTED enum
Switch from _UNDEFINED to _UNSELECTED which is more describing
its value 0, while value -1 is better match for UNDEFINED.
2017-03-10 19:33:00 +01:00
b8cd0f4808 thin: add new ZERO/DISCARDS_UNSELECTED
To more easily recognize unselected state from select '0' state
add new 'THIN_ZERO_UNSELECTED' enum.
Same applies to THIN_DISCARDS_UNSELECTED.

For those we no longer need to use PASS_ARG_ZERO or PASS_ARG_DISCARDS.
2017-03-10 19:33:00 +01:00
8c72878cf2 pool: drop duplicated sign test
Avoid duplicate testing of '-' sign.
Already checked with arg_from_list_is_negative().
2017-03-10 19:33:00 +01:00
acfc82ae29 pool: split chunk size validation
Move cache and thin bits into their respective manipulation files.
When possible directly call respective chunk_size validator.
2017-03-10 19:33:00 +01:00
375e4bb3da thin: getting default chunk_size from single place
Basically code moving operation to have a single place resolving
thin_pool_chunk_size_policy.

Supported are generic & performance profiles.

Function is now shared between thin manipulation code and configuration
_CFG logic to obtain defaults and handle correct reporting upward coding
stack.
2017-03-10 19:33:00 +01:00
50441f2433 cache: properly translate DM_THIN_DISCARDS
DM status uses DM defines which need to be translated to LVM enum.
2017-03-10 19:33:00 +01:00
f221ba97c9 lvcreate: avoid rejecting --metadataprofile
Likely user normaly have used 'shortcut' --profile option which
is (for lvcreate) decoded as metadataprofile.

However full option was rejected.
2017-03-10 19:33:00 +01:00
fb38426d28 lvconvert: validate name before prompt
Before prompting make sure name fits.
2017-03-10 19:33:00 +01:00
7ad57d55af lvconvert: indent and code simplification
Simple modifications to existing  _lvconvert_to_pool().
2017-03-10 19:33:00 +01:00
dd2881f277 raid: enhance lv_raid_convert() header relative to reshaping 2017-03-10 19:26:02 +01:00
2fcbe34fe8 lvcreate: fix "striped" limit
Fix regression limiting number of stripes to 8.
Raise back to 128 as before.

Resolves: rhbz1389546
2017-03-10 18:57:06 +01:00
43388f1220 commands: fix missing skip condition in coverity fixes
Fix for commit 5e6ea4b7
2017-03-10 11:50:00 -06:00
a9341b18ef daemons: use DEFAULT_PROC_DIR in dmfilemapd
Include defaults.h and use it to obtain the default procfs mount
point in dmfilemapd.
2017-03-10 17:26:47 +00:00
b17eb054cd daemons: cleanup dmeventd references from dmfilemapd/Makefile.in 2017-03-10 17:26:47 +00:00
5e6ea4b784 commands: coverity fixes 2017-03-10 10:54:42 -06:00
8c6b8e90e3 libdm: use correct value for NR_FILEMAPD_ARGS
The argument count for the file mapping daemon needs to account
for the program's name in argv[0] to avoid indexing off the end
of the argument array.
2017-03-10 16:52:27 +00:00
c713745314 dmsetup: always initialise 'dms' in _stats_update_file() 2017-03-10 16:44:08 +00:00
d28a50ec76 libdm: make dm_stats_destroy(NULL) a no-op
Test for NULL in dm_stats_destroy() and return immediately if
the struct dm_stats pointer is NULL (similar to free(NULL)).

This simplifies cleanup code which otherwise needs to:

  out:
    if (dms)
        dm_stats_destroy(dms);
    return;
2017-03-10 16:41:28 +00:00
93644be44b libdm: dm_stats_start_filemapd() mode can never be < 0 2017-03-10 14:42:23 +00:00
bc3bec6c54 raid: fix compile time warning 2017-03-10 14:43:37 +01:00
59e57be54f man: add man-generator and build artefacts to .gitignore 2017-03-10 13:14:02 +00:00
1f7ac54bc4 tools: add generated headers to .gitignore 2017-03-10 13:13:41 +00:00
6a0f597727 dmsetup: always initialise 'mode' in filemap create functions
Older compilers cannot tell that the 'mode' variable is only
used in branches in which it is assigned:

dmsetup.c:5651: warning: "mode" may be used uninitialized in this function
dmsetup.c:5023: warning: "mode" may be used uninitialized in this function

Avoid this by always assigning the variable a value.
2017-03-10 12:17:25 +00:00
146b2582b0 libdm: move initialisation of group_id in _aggregate_histogram()
Older compilers are not able to determine that although group_id
is only assigned in one branch of a conditional, it is never used
used when the other branch is taken:

  libdm-stats.c:3319: warning: "group_id" may be used uninitialized in this function

Avoid this by always initialising the variable when it is
declared.
2017-03-10 11:45:08 +00:00
97b6486b27 lvmdbustest.py: Correct debug & assert order
If we do the assert first we won't get to the print statement.
2017-03-09 16:39:47 -06:00
ee7946ed82 lvmdbustest.py: Correct call_lvm doc 2017-03-09 16:39:47 -06:00
957e283de8 lvmdbusd: Simplify add_no_notify for loop 2017-03-09 16:39:47 -06:00
075f8e658c lvmdbusd: Correct utils.add_no_notify doc 2017-03-09 16:39:47 -06:00
00143753ee lvmdbusd: Add debug message to lvm ID lookup 2017-03-09 16:39:47 -06:00
28754145d8 lvmdbustest.py: Add unit test for external PV create
Ensure a PV created outside of the dbus service is immediately found by
service user.
2017-03-09 16:39:47 -06:00
e06e4d9355 lvmdbustest.py: Add unit test for external LV create
Ensure a LV created outside of the dbus service is immediately found by
service user.
2017-03-09 16:39:47 -06:00
43d0fbeba2 lvmdbustest.py: Add unit test for external VG create
Ensure a VG created outside of the dbus service is immediately found by
service user.
2017-03-09 16:39:47 -06:00
92b7c329ee lvmdbustest.py: Remove un-used import time 2017-03-09 16:39:47 -06:00
0c0002d765 lvmdbusd: Correct src doc for Manager.UseLvmShell
It returns a boolean.
2017-03-09 16:39:47 -06:00
11cfc58976 lvmdbusd: Disable notify_dbus for service command use
Utilizing the --config option  we will utilize global/notify_dbus=0 so
that the service itself doesn't generate change events which it then needs to
process.
2017-03-09 16:39:47 -06:00
e53454d6de lvmdbusd: Use work queue for queries too
We need to place query operations in the queue to prevent the case where
a client knows of something before the service does.  For example if a
client creates a PV/VG/LV outside of the dbus API and then immediately
tries to lookup and use that resource in the lvm dbus service it should
be present.  By placing the queries in the work queue any previous
refresh operation will complete before we process the query.
2017-03-09 16:39:47 -06:00
470a1f1c50 lvmdbusd: Add FlightRecorderDump
Diagnostic method for dumping flight recorder to syslog.
2017-03-09 16:39:47 -06:00
f2d7a48418 lvconvert: add raid1 <-> raid4 conversion
In addition to the already supported conversion between 2-legged
raid1 and raid5, raid1 and raid4 can be also converted into each
other with 2 legs (raid4/5 are limited to map a 2-legged raid1).

This patch supports the missing raid4 conversion in the sequence
linear -> 2-legged raid1 -> raid4/5, then restripe to more than one
data stripes for performance and resilience reasons and optionally
convert to striped/raid0.

The other conversion sequence is also possible by converting N-way
striped/raid0 to raid4/5, then restripe to 2 legs followed by a
conversion to raid1 and optionally to linear (loosing all resilience).
2017-03-09 23:18:13 +01:00
d2aae8cff4 man: add more examples to lvmraid(7)
Add examples for reshaping number of stripes
and converting from raid6 to striped to raid10.

Remove trailing spaces.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-09 23:18:13 +01:00
1ba11aa7ee dmfilemapd: always set the program_id after listing regions
The filemap daemon takes its program_id from the regions it is
managing: use DM_STATS_ALL_PROGRAMS when retrieving an initial
listing and then obtain the correct program_id from the group
leader.
2017-03-09 21:20:27 +00:00
0104fd6c66 libdm: don't nest FIEMAP and DMFILEMAPD ifdefs 2017-03-09 21:20:27 +00:00
af7a11bc57 configure: make --enable-dmfilemapd require fiemap.h 2017-03-09 21:20:27 +00:00
66fff1d774 raid: add missing lv_merge_segments() call
On conversion from striped to raid0, data LVs are created
and all segments and their respective areas of the striped
LV are moved across to new segments allocated for the raid0
image LVs.  This can cause non-canonical segments to be added
to the image LVs.

Add a call to lv_merge_segments() once all segments have been
added to an image LV to compensate for that.  This avoids
unsafe table loads on activation.

Fix comments.
2017-03-09 22:18:34 +01:00
76f6951c3e dmeventd: (workaround) fix mirror DSO to work with lvmetad
Automatic dmeventd repair of mirrors with active lvmetad configured
(mirror_image_fault_policy = "allocate") fails because the lvscan
run before the repair in the mirror DSO does not update the
lvmetad cache properly thus "lvconvert --repair ..." fails.

Need to scan the mirror LV before and after the repair
to have proper cache content after the repair finished.
The cache can't be relied on or the repair will fail.

Resolves: rhbz1380521
2017-03-09 20:41:07 +01:00
67ddc0c292 man: add FILE MAPPING section to dmstats.8.in
Add a section to explain file mapping, outside of the individual
command descriptions, and to describe the limitations of the
current update strategy.
2017-03-09 18:50:15 +00:00
b5c8accdf2 man: add dmfilemapd options to dmstats.8.in
Add descriptions of --follow and --nomonitor, and the behaviour
of create and update_filemap when starting dmfilemapd.
2017-03-09 18:50:15 +00:00
baa8a9be4a dmstats: start dmfilemapd when creating or updating file maps
Launch an instance of the filemap monitoring daemon when creating,
or updating, a file mapped group, unless the --nomonitor switch is
given.

Unless --foreground is given the daemon will detach from the
terminal and run in the background until it is signaled or the
daemon termination conditions are met.

The --follow={inode|path} switch is added to control the daemon
behaviour when files are moved, unlinked, or renamed while they
are being monitored.

The daemon runs with the same verbosity as the dmstats command
that starts it.
2017-03-09 18:50:15 +00:00
044f92e466 man: add dmfilemapd.8 2017-03-09 18:50:15 +00:00
8b78982297 daemons: add dmfilemapd
Add a daemon that can be launched to monitor a group of regions
corresponding to the extents of a file, and to update the regions as the
file's allocation changes.

The daemon is intended to be started from a library interface, but can
also be run from the command line:

  dmfilemapd <fd> <group_id> <path> <mode> [<foreground>[<log_level>]]

Where fd is a file descriptor open on the mapped file, group_id is the
group identifier of the mapped group and mode is either "inode" or
"path". E.g.:

  # dmfilemapd 3 0 vm.img inode 1 3 3<vm.img
  ...

If foreground is non-zero, the daemon will not fork to run in the
background. If verbose is non-zero, libdm and daemon log messages will
be printed.

It is possible for the group identifier to change when regions are
re-mapped: this occurs when the group leader is deleted (regroup=1 in
dm_stats_update_regions_from_fd()), and another region is created before
the daemon has a chance to recreate the leader region.

The operation is inherently racey since there is currently no way to
atomically move or resize a dm_stats region while retaining its
region_id.

Detect this condition and update the group_id value stored in the
filemap monitor.

A function is also provided in the the stats API to launch the filemap
monitoring daemon:

  int dm_stats_start_filemapd(int fd, uint64_t group_id, const char *path,
                              dm_filemapd_mode_t mode, unsigned foreground,
                              unsigned verbose);

This carries out the first fork and execs dmfilemapd with the arguments
specified.

A dm_filemapd_mode_t value is specified by the mode argument: either
DM_FILEMAPD_FOLLOW_INODE, or DM_FILEMAPD_FOLLOW_PATH. A helper function,
dm_filemapd_mode_from_string(), is provided to parse a string containing
a valid mode name into the appropriate dm_filemapd_mode_t value.
2017-03-09 18:50:15 +00:00
c98868181f libdm: remove unnecessary backtrace in _stats_group_id_present()
It's not an error to call dm_stats_group_present() on a handle
that contains no regions.

This causes dmfilemap to log a false backtrace during shutdown
if all regions are removed from the corresponding device:

  exiting _filemap_monitor_get_events() with deleted=0, check=0
  waiting for FILEMAPD_WAIT
  dm message   (253:1) [ opencount flush ]  @stats_list dmstats [32768] (*1)
  <backtrace>
  Filemap group removed: exiting.

Change this to only emit a backtrace if the handle is NULL.
2017-03-09 17:53:15 +00:00
fab088cbc7 man lvmraid: remove fixmes, use consistent example name 2017-03-09 11:48:30 -06:00
716c345334 tests relative-sign-options: only skip thin part 2017-03-09 11:29:54 -06:00
43bcd7393c tests relative-sign-options.sh: skip without thin 2017-03-09 10:43:41 -06:00
aa31272223 lvresize: poolmetadatasize cannot use minus 2017-03-09 09:51:24 -06:00
6dfe1ce251 lvconvert: prompt when splitting off LV of a 2-legged raid1 LV
Splitting off an image LV of a 2-legged
raid1 LV causes loss of resilience.

Ask user to avoid uninformed loss of all resilience.

Don't ask for N > 2 legged raid1 LVs.

Adjust tests.
2017-03-09 13:59:47 +01:00
6b1b66c266 test: raid1 down convert to linear
Missed one test in last commit.
2017-03-09 13:21:21 +01:00
4b0ae266c2 test: raid1 down convert to linear
Add/adjust more tests for commit 7fbe6ef16b.
2017-03-09 13:16:08 +01:00
413164765f lvconvert: remove superfluous compile time conditonal code 2017-03-09 12:16:11 +01:00
3d1df10af3 test: raid1 down convert to linear / split and track tests
Add/adjust tests for commits d250aa7208 and 7fbe6ef16b.
2017-03-09 04:01:47 +01:00
d250aa7208 lvconvert: prompt when splitting off a tracked LV of a 2-legged raid1 LV
Splitting off an image LV of a 2-legged raid1 LV tracking changes
causes loosing partial resilience for any newly written data set.
Full resilience will be provided again after the split off image LV
got merged back in and the new data set got fully synchronized.
Reason being that the data is only stored on the remaining single
writable image during the split.

Ask user to avoid uninformed loss of such partial resilience.

Don't ask for N > 2 legged raid1 LVs.
2017-03-09 03:22:55 +01:00
7fbe6ef16b lvconvert: prompt when converting raid1 to linear
Ask user when converting raid1 to linear to avoid
uninformed loss of all resilience.
2017-03-09 02:39:49 +01:00
8daad11666 test: "lvconvert --repair" after vgreduce
Add test for commit 921b496fff.
2017-03-09 02:35:57 +01:00
90ed3d5e8c raid: fix function description 2017-03-09 02:16:03 +01:00
921b496fff lvconvert: fix --repair after vgreduce
In case N images fail (N <= parity chunks) _and_
a "vgreduce --removemissing --force VG" was applied
a following repair of the RaidLV fails:

  Unable to remove N images:  Only 0 devices given.
  Failed to remove the specified images from tb/r.
  Failed to replace faulty devices in tb/r.

Fix as of this commit results in correct repair:

  Faulty devices in tb/r successfully replaced.
2017-03-09 02:11:52 +01:00
00b8c2bebc test: Copyright 2017-03-09 00:10:55 +01:00
b4e78b26f5 help: fix missing required option
Fix for previous commit 4d0172ff15.
2017-03-08 15:00:27 -06:00
4d0172ff15 man/help: use order of required options from cmd def
Follow the same as written in command-lines.in
2017-03-08 14:51:08 -06:00
3d5182c819 man: add more references to topical man pages 2017-03-08 14:43:30 -06:00
14c7912f45 tests: add test for relative option values
Combinations of: lvcreate/lvresize/lvextend/lvreduce,
--size/--extents/--poolmetadatasize, +/-/nosign.
2017-03-08 13:51:33 -06:00
a6a2788e7c commands: clean up and unify signed option value handling
Add new values for different sign variations, resulting in:

size_VAL      no sign accepted
ssize_VAL     accepts + or -
psize_VAL     accepts +
nsize_VAL     accpets -

extents_VAL   no sign accepted
sextents_VAL  accepts + or -
pextents_VAL  accepts +
nextents_VAL  accepts -

Depending on the command being run, change the option
values for --size, --extents, --poolmetadatasize to
use the appropriate value from above.

lvcreate uses no sign (but accepts + and ignores it).
lvresize accepts +|- for a relative change.
lvextend accepts + for a relative change.
lvreduce accepts - for a relative change.
2017-03-08 12:54:43 -06:00
7f25fbe154 report: fix segfault
Commit f4b30b0dae which was about displaying visible
LV size when reshape space is allocated did not account
for undefined first lv segment.
2017-03-08 18:32:01 +01:00
11f1556d5d commands: combine duplicate arrays for lv types and props
Like opt and val arrays in previous commit, combine duplicate
arrays for lv types and props in command.c and lvmcmdline.c.
Also move the command_names array to be defined in command.c
so it's consistent with the others.
2017-03-08 11:03:02 -06:00
690f604733 commands: combine duplicate arrays for opt and val
command.c and lvmcmdline.c each had a full array defining
all options and values.  This duplication was not removed
when the command.c code was merged into the run time.
2017-03-08 11:03:02 -06:00
f48e6b2690 help: avoid end notes repetition in lvm help all 2017-03-08 11:03:02 -06:00
ed58672029 metadata: comments
log_count,nosync,stripes,stripe_size,,...  are also used for raid.
2017-03-08 15:13:59 +01:00
3a5561e5ab raid: define seg->extents_copied
seg->extents_copied has to be defined properly on reducing
the size of a raid LV or conversion from raid5 with 1 stripe
to raid1 will fail.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-07 23:28:09 +01:00
aedac100f9 report: correct lv_size for 2-legged raid5
Reshaping a raid5 LV to one stripe aiming to convert it to
raid1 (and optionally to linear) reports the wrong LV size
when still having reshape space allocated.
2017-03-07 22:36:50 +01:00
18bbeec825 raid: fix raid LV resizing
The lv_extend/_lv_reduce API doesn't cope with resizing RaidLVs
with allocated reshape space and ongoing conversions.  Prohibit
resizing during conversions and remove the reshape space before
processing resize.  Add missing seg->data_copies initialisation.

Fix typo/comment.
2017-03-07 22:05:23 +01:00
9ed11e9191 raid: cleanup _lv_set_image_lvs_start_les()
Avoid second loop.
2017-03-07 21:55:19 +01:00
05aceaffbd lvconvert: adjust --stripes on raid10 convert
For the time being raid10 is limited to even number of total stripes
as is and 2 data copies.  The number of stripes provided on creation
of a raid10(_near) LV with -i/--stripes gets doubled to define
that even total number of stripes (i.e. images).

Apply the same on disk adding conversions (reshapes) with
"lvconvert --stripes RaidLV" (e.g. 2 stripes = 4 images
total converted to 3 stripes = 6 images total).

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-07 21:36:03 +01:00
f4b30b0dae report: display proper LV size for reshapable RaidLVs
Subtract reshape space when reporting visible lv_size on RaidLV.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-07 18:47:20 +01:00
43fb4aa69b test: add delay to lvchange-raid1-writemostly.sh
Commit 8ab0725077 introduced this new test.

Add a read delay to the PVs to avoid a race
in the script causing the test to fail.

Correct comment.
2017-03-07 15:18:13 +01:00
872932a0fb man lvs: describe new 'R' volume health character 2017-03-06 19:33:10 +01:00
0b019c5406 man/help: improve stripes option wording 2017-03-06 12:20:33 -06:00
ef97360866 man lvextend: mention segment type 2017-03-06 11:27:56 -06:00
17838e6439 test: fix typo 2017-03-03 23:22:29 +01:00
11589891d7 man: move the full UNIT description
Part of the UNIT description was still living in the
--size description.  Move it to the Size[UNIT] description
since it is used by other options, not just --size.
2017-03-03 16:12:02 -06:00
b6c4b7cfb0 man/help: poolmetadatasize option can take relative value
In lvcreate/lvconvert, --poolmetdatasize can only be an
absolute value, but in lvresize/lvextend, --poolmetadatasize
can be given a + relative value.

The val types only currently support relative values that
go in both directions +|-.  Further work is needed to add
val types that can be relative in only one direction, and
switching various option values to one those depending on
the command name.  Then poolmetdatasize will not appear
with a +|- option in lvcreate/lvconvert, and will
appear with only the + option in lvresize/lvextend.
2017-03-03 16:12:02 -06:00
c5b6c9ad44 report: raid enhancements for --select
Enhance the raid report functions for the recently added LV fields
reshape_len, reshape_len_le, data_offset, new_data_offset, data_copies,
data_stripes and parity_chunks to cope with "lvs --select".

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-03 22:29:50 +01:00
6dea1ed5ae man: fix term in lvmraid(7)
Adjust commit af7c8e7106 to use "image/leg".

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-03 22:24:53 +01:00
e4ef3d04ad help: show short opt with long opt
e.g. show -n|--name instead of just --name
2017-03-03 15:14:18 -06:00
547bdb63e1 dev_manager: remove reshape message
The dm-raid target doesn't support a "reshape" message.
2017-03-03 22:10:21 +01:00
9a50df291a man/help: rework extents and size output
Clean up and correct the details around --extents and --size.

lvcreate/lvresize/lvreduce/lvextend all now display the
extents option in usages.

The Size and Number value variables for --size and --extents
are now displayed without the [+|-] prefix for lvcreate.
2017-03-03 14:23:50 -06:00
e7ee89d80b man/help: improve the PV range description 2017-03-03 11:15:27 -06:00
2a5e24580a args: in cachemode option fix passthrough value 2017-03-03 10:53:18 -06:00
191a2517be args: update select description
mention --select help and --options help.
2017-03-03 09:53:11 -06:00
1a0d57f895 man lvcreate: show extents option
Display --extents as an option in each cmd def,
in addition to the special notes about how
--size and --extents are alternatives.
2017-03-02 16:58:19 -06:00
9a62767f2d man lvcreate: remove the extents prefix
This applies the same hack to --extents (dropping
the [+|-] prefix), as commit b7831fc14a did for --size.
2017-03-02 16:58:19 -06:00
5d39927f22 help: show extents option for lvcreate
A special case is needed to display
--extents for lvcreate since the cmd defs
treat --extents as an automatic alternative
to --size (to avoid duplicating every cmd def).
2017-03-02 16:58:19 -06:00
9b23d9bfe4 help: print info about special options and variables
when --longhelp is used
2017-03-02 16:58:19 -06:00
f350283398 lvcreate: munge size value in help output
Add hack to omit the [+|-] from the --size
value.  Same hack exists in man generator.
2017-03-02 16:58:19 -06:00
af7c8e7106 man: cover reshaping
Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-02 22:24:19 +01:00
ca859b5149 lvs: enhance stripes and region size field descriptions
Now that we got the "data_stripes" field key, adjust the "stripes" field description.
Enhance the "regionsize" field description to cover raids as well.
2017-03-02 22:22:16 +01:00
d3bcec5993 man: change the synopsis option style
Remove the required/optional words because it
should already be evident from the use of [ ].
2017-03-02 14:08:59 -06:00
910918d1c2 lvcreate: allow chunksize option when creating cache 2017-03-02 13:58:27 -06:00
6360ba3d2d commands: handle including an optional opt multiple times
When a cmd def includes multiple sets of options (OO_FOO),
allow multiple OO_FOO sets to contain the same option and
avoid repeating it in the cmd def.
2017-03-02 13:52:06 -06:00
b7831fc14a lvcreate/lvresize: the --size option accepts signed values
There was confusion in the code about whether or not the
--size option accepted a sign.  Make it consistent and clear
that it does.

This exposes a new problem in that an option can only
accept one value type, e.g. --size can only accept a
signed number, it cannot accept a positive or negative
number for some commands and reject negative numbers for
others.

In practice, lvcreate accepts only positive --size
values and lvresize accepts positive or negative --size
values.  There is currently no way to encode this
difference.  Until that is fixed, the man page output
is hacked to avoid printing the [+|-] prefix for sizes
in lvcreate.
2017-03-02 12:53:01 -06:00
70c1fa3764 tools: Fix overriding of current_settings.
Settings specified in other command line args take precedence over
profiles and --config, which takes precedence over settings in actual
config files.

Since commit 1e2420bca8 ('commands: new
method for defining commands') commands like this:
  lvchange --config 'global/test=1' -ay vg
have been printing the 'TEST MODE' message, but nevertheless making
real changes.
2017-03-02 16:41:41 +00:00
8df3f300ba commands: adjust syntax error message 2017-03-02 09:46:41 -06:00
b76852bf35 man lvchange: mention special activation vals
used by lvmlockd and clvmd.
2017-03-02 09:31:06 -06:00
26ca308ba9 lvmdbustest.py: Remove un-used variable
Not needed with new validation function.
2017-03-01 17:47:04 -06:00
7b0371e74e lvmdbustest.py: Validate LV lookups
Ensure that the LV lookups work as expected for newly created LVs.
2017-03-01 17:47:04 -06:00
83249f3327 lvmdbustest.py: Validate PV device
Validate device lookup after PV creation.
2017-03-01 17:47:04 -06:00
4c89d3794c lvmdbustest.py: Re-name validation function
Make this name generic as we can use for different types.
2017-03-01 17:47:04 -06:00
10c3d94159 lvmdbustest.py: Verify lookups work immediately after vg create 2017-03-01 17:47:04 -06:00
157948b5a5 lvmdbustest.py: Use _lookup function
Be consistent in using this helper function for dbus object lookups.
2017-03-01 17:47:04 -06:00
c25b95e2ef man: fix typo 2017-03-01 16:59:51 -06:00
51dfbf1fb3 commands: tweak some descriptions 2017-03-01 16:59:51 -06:00
daf1d4cadc lvconvert: add new reporting fields for reshaping
Commit 48778bc503 introduced new RAID reshaping related report fields.

The inclusioon of segtype.h in properties.c isn't mandatory, remove it.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-01 19:30:52 +01:00
fb42874a4f lvconvert: libdm RAID API compatibility versioning; remove new function
Commit 80a6de616a versioned the dm_tree_node_add_raid_target_with_params()
and dm_tree_node_add_raid_target() APIs for compatibility reasons.

There's no user of the latter function, remove it.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-01 18:58:48 +01:00
48778bc503 lvconvert: add new reporting fields for reshaping
During an ongoing reshape, the MD kernel runtime reads stripes relative
to data_offset and starts storing the reshaped stripes (with new raid
layout and/or new stripesize  and/or new number of stripes) relative
to new_data_offset.  This is to avoid writing over any data in place
which is non-atomic by nature and thus be recoverable without data loss
in the transition.  MD uses the term out-of-place reshaping for it.

There's 2 other areas we don't have report capability for:
- number of data stripes vs. total stripes
  (e.g. raid6 with 7 stripes toal has 5 data stripes)
- number of (rotating) parity/syndrome chunks
  (e.g. raid6 with 7 stripes toal has 2 parity chunks; one
   per stripe for P-Syndrome and another one for Q-Syndrome)

Thus, add the following reportable keys:

- reshape_len      (in current units)
- reshape_len_le   (in logical extents)
- data_offset      (in sectors)
- new_data_offset  (     "    )
- data_stripes
- parity_chunks

Enhance lvchange-raid.sh, lvconvert-raid-reshape-linear_to_striped.sh,
lvconvert-raid-reshape-striped_to_linear.sh, lvconvert-raid-reshape.sh
and lvconvert-raid-takeover.sh to make use of new keys.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-01 18:50:35 +01:00
62abae1525 man: put some commands into advanced usage section
and separate commands with --
2017-03-01 10:22:48 -06:00
eb9586bd3b commands: SECONDARY flag changes in cmd defs
Add/remove the SECONDARY_SYNTAX flag to cmd defs.
cmd defs with this flag will be listed under the
ADVANCED USAGE man page section, so that the main
USAGE section contains the most common commands
without distraction.

- When multiple cmd defs do the same thing, one variant
  can be displayed in the first list.
- Very advanced, unusual or uncommon commands should be
  in the second list.
2017-03-01 10:22:48 -06:00
d6dd700bf7 raid: rework _raid_target_present()
Recently added check for reshaping in this function called for
a cleanup to avoid proliferating it with more explicit conditionals.

Base the reshaping check on the given _features array.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-03-01 14:52:23 +01:00
7a064303fe lvconvert: add missing reshape_len initialization
An initialization was missing when converting striped to raid0(_meta)
causing unitialized reshape_len in the new component LVs first segment.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-28 23:29:03 +01:00
964114950c lvconvert: adjust mininum region size check
The imposed minimum region size can cause rejection on
disk removing reshapes.  Lower it to avoid that.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-28 23:10:37 +01:00
1828822bd8 help: print full usage for lvm help all 2017-02-28 15:58:14 -06:00
ce1e5b9991 lvconvert: adjust reshaping check to target version
https://git.kernel.org/cgit/linux/kernel/git/device-mapper/linux-dm.git/commit/?h=dm-4.11&id=b08c6076782
sets the dm-raid target version to 1.10.1.

Adjust the condition to set RAID_RESHAPE_FEATURE to it.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-28 22:46:25 +01:00
80a6de616a lvconvert: libdm RAID API compatibility versioning
Commit 27384c52cf lowered the maximum number of devices
back to 64 for compatibility.

Because more members have been added to the API in
'struct dm_tree_node_raid_params *', we have to version
the public libdm RAID API to not break any existing users.

Changes:

- keep the previous 'struct dm_tree_node_raid_params' and
  dm_tree_node_add_raid_target_with_params()/dm_tree_node_add_raid_target()
  in order to expose the already released public RAID API

- introduce 'struct dm_tree_node_raid_params_v2' and additional functions
  dm_tree_node_add_raid_target_with_params_v2()/dm_tree_node_add_raid_target_v2()
  to be used by the new lvm2 lib reshape extentions

With this new API, the bitfields for rebuild/writemostly legs in
'struct dm_tree_node_raid_params_v2' can be raised to 256 bits
again (253 legs maximum supported in MD kernel).

Mind that we can limit the maximum usable number via the
DEFAULT_RAID{1}_MAX_IMAGES definition in defaults.h.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-28 22:34:00 +01:00
21456dcf7f commands: include lvconvert cache options as group 2017-02-28 13:47:46 -06:00
89661981e8 man: fix syntax for PV ranges 2017-02-28 12:22:12 -06:00
4a14617dc4 commands: remove lvconvert raid rule
A raid0 LV also needs to be converted to other
raid levels, so this rule should be removed entirely.
2017-02-27 17:06:08 -06:00
f9d28f1aec man: mention regionsize default is in lvm.conf 2017-02-27 17:05:20 -06:00
998151e83e commands: fix lvconvert raid rule
Recent rule change was incorrect.
We want to allow 'lvconvert --type raid' on raid1 LVs.
2017-02-27 16:33:38 -06:00
8d0df0c011 commands: fixes for recent raid changes
- Combine the equivalent lvconvert --type raid defs.
  (Two cmd defs must be different without relying
  on LV type, which are not known at the time the
  cmd def is matched.)

- Remove unused optional options from lvconvert --stripes,
  and lvconvert --stripesize.

- Use Number for --stripes_long val type.

- Combine the cmd def for raid reshape cleanup into the
  existing start_poll cmd def (they were duplicate defs).
  Calls into the raid code from a poll opertion will be
  added.
2017-02-27 14:44:00 -06:00
27384c52cf lvconvert: limit libdm to maximum of 64 RAID devices
Commit 64a2fad5d6 raised the maximum number of RAID devices to 64.

Commit e2354ea344 introduced RAID_BITMAP_SIZE as 4 to have
256 bits (4 * 64 bit array members), thus changing the libdm API
unnecessarilly for the time being.

To not change the API, reduce RAID_BITMAP_SIZE to 1.
Remove an unneeded definition of it from libdm-common.h.

If we ever decide to raise past 64, we'll version the API.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-27 21:42:15 +01:00
c41e999488 git: Upstream repository moved to sourceware.org
The fedorahosted git repository shuts down tomorrow:
  https://communityblog.fedoraproject.org/fedorahosted-sunset-2017-02-28/

Our upstream git repository has moved back to sourceware.org.
Mailing list hosting is not changing.

Gitweb:
  https://www.sourceware.org/git/?p=lvm2

Git:
  git://sourceware.org/git/lvm2.git
  ssh://sourceware.org/git/lvm2.git
  http://sourceware.org/git/lvm2.git

Example command to change the origin of a repository clone:
  Public:
    git remote set-url origin git://sourceware.org/git/lvm2.git
  Committers:
    git remote set-url origin git+ssh://sourceware.org/git/lvm2.git
2017-02-27 14:05:50 +00:00
4f7631b4ad man: change option sorting in synopsis
The options list was sorted as:
- options with both long and short forms, alphabetically
- options with only long form, alphabetically

This was done only for the visual effect.  Change to
sort alphabetically by long opt, without regard to
short forms.
2017-02-24 15:11:18 -06:00
5f6bdf707d man: add ENVIRONMENT VARIABLES section 2017-02-24 15:05:17 -06:00
84cceaf9b9 lvconvert: fix handling args in combining snapshots
Fixes commit 286d39ee3c, which was correct except
for a reversed strstr.  Now uses strchr, and modifies
a copy of the name so the original argv is preserved.
2017-02-24 14:17:58 -06:00
74ba326007 man: use Size variable for a number with unit
Define a separate variable type Size to represent
a number that takes an optional UNIT.
2017-02-24 13:44:05 -06:00
189fa64793 lvconvert: impose region size constraints
When requesting a regionsize change during conversions, check
for constraints or the command may fail in the kernel n case
the region size is too smalle or too large thus leaving any
new SubLVs behind.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 07:27:43 +01:00
3bdc4045c2 lvconvert: fix 2 issues identified in intesting
Allow regionsize on upconvert from linear:
fix related commit 2574d3257a to actually work

Related: rhbz1394427

Remove setting raid5_n on conversions from raid1
as of commit 932db3db53 because any raid5 mapping
may be requested.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:58:45 +01:00
d768fbe010 WHATS_NEW: add entry 2017-02-24 05:24:59 +01:00
76f60cc430 lvconvert: add missed new test scripts for reshaping
Add aforementioned but forgotten new test scripts
lvconvert-raid-reshape-linear_to_striped.sh,
lvconvert-raid-reshape-striped_to_linear.sh and
lvconvert-raid-reshape.sh

Those presume dm-raid target version 1.10.2
provided by a following kernel patch.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:59 +01:00
2574d3257a lvconvert: allow regionsize on upconvert from linear
Allow to provide regionsize with "lvconvert -m1 -R N " on
upconverts from linear and on N -> M raid1 leg conversions.

Resolves: rhbz1394427
2017-02-24 05:20:58 +01:00
64a2fad5d6 lvconvert/lvcreate: raise maximum number of raid images
Because of contraints in renaming shifted rimage/rmeta LV names
the current RaidLV limit is a maximum of 10 SubLV pairs.

With the previous introduction of reshaping infratructure that
constriant got removed.

Kernel supports 253 since dm-raid target 1.9.0, older kernels 64.

Raise the maximum number of RaidLV rimage/rmeta pairs to 64.
If we want to raise past 64, we have to introdce a check for
the kernel supporting it in lvcreate/lvconvert.

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
34caf83172 lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces the changes to call the reshaping infratructure
from lv_raid_convert().

Changes:
- add reshaping calls from lv_raid_convert()
- add command definitons for reshaping to tools/command-lines.in
- fix raid_rimage_extents()
- add 2 new test scripts lvconvert-raid-reshape-linear_to_striped.sh
  and lvconvert-raid-reshape-striped_to_linear.sh to test
  the linear <-> striped multi-step conversions
- add lvconvert-raid-reshape.sh reshaping tests
- enhance lvconvert-raid-takeover.sh with new raid10 tests

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
f79bd30a8b lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Change:
- allow raid_rimage_extents() to calculate raid10
- remove an __unused__ attribute

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
1784cc990e lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Change:
- add missing raid1 <-> raid5 conversions to support
  linear <-> raid5 <-> raid0(_meta)/striped conversions
- rename related new takeover functions to
  _takeover_from_raid1_to_raid5 and _takeover_from_raid5_to_raid1,
  because a reshape to > 2 legs is only possible with
  raid5 layout

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
2d74de3f05 lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Change:
- enhance _clear_meta_lvs() to support raid0 allowing
  raid0_meta -> raid10 conversions to succeed by clearing
  the raid0 rmeta images or the kernel will fail because
  of discovering reordered raid devices

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
34a8d3c2fd lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Changes:
- enhance _raid45610_to_raid0_or_striped_wrapper() to support
  raid5_n with 2 areas to raid1 conversion to allow for
  striped/raid0(_meta)/raid4/5/6 -> raid1/linear conversions;
  rename it to _takeover_downconvert_wrapper to discontinue the
  illegible function name
- enhance _striped_or_raid0_to_raid45610_wrapper()  to support
  raid1 with 2 areas to raid5* conversions to allow for
  linear/raid1 -> striped/raid0(_meta)/raid4/5/6 conversions;
  rename it to _takeover_upconvert_wrapper for the same reason

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
932db3db53 lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Changes:
- add missing possible reshape conversions and conversion options
  to allow/prohibit changing stripesize or number fo stripes
- enhance setting convenient riad types in reshape conversions
  (e.g. raid1 with 2 legs -> radi5_n)

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
fe18e5e77a lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Changes:
- add _raid_reshape() using the pre/post callbacks and
  the stripes add/remove reshape functions introduced before
- and _reshape_requested function checking if a reshape
  was requested

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
929cf4b73c lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Changes:
- add vg metadata update functions
- add pre and post activation callback functions for
  proper sequencing of sub lv activations during reshaping
- move and enhance _lv_update_reload_fns_reset_eliminate_lvs()
  to support pre and post activation callbacks
- add _reset_flags_passed_to_kernel() which resets anyxi
  rebuild/reshape flags after they have been passed into the kernel
  and sets the SubLV remove after reshape flags on legs to be removed

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
4de0e692db lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Changes:
- add function to support disk adding reshapes
- add function to support disk removing reshapes
- add function to support layout (e.g. raid5ls -> raid5_rs)
  or stripesize reshaping

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
7d39b4d5e7 lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Changes:
- add function providing state of a reshaped RaidLV
- add function to adjust the size of a RaidLV was
  reshaped to add/remove stripes

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
92691e345d lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces more local infrastructure to raid_manip.c
used by followup patches.

Changes:
- add lv_raid_data_copies returning raid type specific number;
  needed for raid10 with more than 2 data copies
- remove _shift_and_rename_image_components() constraint
  to support more than 10 raid legs
- add function to calculate total rimage length used by out-of-place
  reshape space allocation
- add out-of-place reshape space alloc/relocate/free functions
- move _data_rimages_count() used by reshape space alloc/realocate functions

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
c1865b0a86 raid: typo 2017-02-24 05:20:58 +01:00
b499d96215 lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces local infrastructure to raid_manip.c
used by followup patches.

Add functions:
- to check reshaping is supported in target attibute
- to return device health string needed to check
  the raid device is ready to reshape

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
e2354ea344 lvconvert: add infrastructure for RaidLV reshaping support
In order to support striped raid5/6/10 LV reshaping (change
of LV type, stripesize or number of legs), this patch
introduces infrastructure prerequisites to be used
by raid_manip.c extensions in followup patches.

This base is needed for allocation of out-of-place
reshape space required by the MD raid personalities to
avoid writing over data in-place when reading off the
current RAID layout or number of legs and writing out
the new layout or to a different number of legs
(i.e. restripe)

Changes:
- add members reshape_len to 'struct lv_segment' to store
  out-of-place reshape length per component rimage
- add member data_copies to struct lv_segment
  to support more than 2 raid10 data copies
- make alloc_lv_segment() aware of both reshape_len and data_copies
- adjust all alloc_lv_segment() callers to the new API
- add functions to retrieve the current data offset (needed for
  out-of-place reshaping space allocation) and the devices count
  from the kernel
- make libdm deptree code aware of reshape_len
- add LV flags for disk add/remove reshaping
- support import/export of the new 'struct lv_segment' members
- enhance lv_extend/_lv_reduce to cope with reshape_len
- add seg_is_*/segtype_is_* macros related to reshaping
- add target version check for reshaping
- grow rebuilds/writemostly bitmaps to 246 bit to support kernel maximal
- enhance libdm deptree code to support data_offset (out-of-place reshaping)
  and delta_disk (legs add/remove reshaping) target arguments

Related: rhbz834579
Related: rhbz1191935
Related: rhbz1191978
2017-02-24 05:20:58 +01:00
ffe3ca26e0 man: improve line breaks
Borrow tricks from dmsetup man page to improve
the line break and indentation using .ad l, .ad b,
and soft break \%.
2017-02-23 17:06:42 -06:00
3fd3c9430d man/help: change syntax to UNIT
(Change to recent commit 3f4ecaf8c2.)

Use --foo Number[k|UNIT] to indicate that
the default units of the number is k, but other
units listed below are also accepted.

Previously, underlined/italic Unit was used,
like other of variables, but this UNIT is more
like a shortcut than an actual variable.
2017-02-23 14:24:28 -06:00
8ab0725077 lvchange: reject writemostly/writebehind on raid1 during resync
The MD kernel raid1 personality does no use any writemostly leg as the primary.

In case a previous linear LV holding data gets upconverted to
raid1 it becomes the primary leg of the new raid1 LV and a full
resynchronization is started to update the new legs.

No writemostly and/or writebehind setting may be allowed during
this initial, full synchronization period of this new raid1 LV
(using the lvchange(8) command), because that would change the
primary (i.e the previous linear LV) thus causing data loss.

lvchange has a bug not preventing this scenario.

Fix rejects setting writemostly and/or writebehind on resychronizing raid1 LVs.

Once we have status in the lvm2 metadata about the linear -> raid upconversion,
we may relax this constraint for other types of resynchronization
(e.g. for user requested "lvchange --resync ").

New lvchange-raid1-writemostly.sh test is added to the test suite.

Resolves: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=855895
2017-02-23 15:09:29 +01:00
3f4ecaf8c2 man/help: improve the style of units indicator
We use --foo Number[k|Units] to indicate that
the default units of the number is k, but other
units listed below are also accepted.

Capitalize and underline Units so it is consistent
with other variables, and reference it at the end.

Technically, the k should be bold, but this
tends to make the text visually hard to read
because of the excessive highlights scattered
everywhere.  So it's left normal text for now
(it's unlikely to confuse anyone.)
2017-02-22 16:50:30 -06:00
da634bfc89 man: indicate repeatable options
Print ... after a repeatable option in the OPTIONS section.
An alternative would be to just mention in the text description
that the option is repeatable.
2017-02-22 16:38:54 -06:00
1eb1869626 man: improve writemostly PV arg 2017-02-22 15:20:44 -06:00
aa72caca5a tests: support zero_dev
When the test would need to try to write some large amount of data
we can give it 'zero' segments - for obvious reason such written data
can't be verified but in some test cases it doesn't really matter.

Usage follows  'error_dev' style.

For now test suite is not supporting any combination of
error/delay/zero segments so only 1 type could be used per PV.
2017-02-22 15:40:59 +01:00
f44e69f9fc tests: not slowing work with metadata
Slows only data extents on a PV.
2017-02-22 15:40:28 +01:00
9712995edd snapshot: improve removal of active origin volume
Previously when lvremove tried to remove 'active' origin,
it had been asking for every 'snapshot' LV separately
and doing individual single snapshot removals first.

To be faster it now deactivates origin before removal
all connected snapshots.

This avoids multiple reloads of dm table for origin volume
which were unnecessary as origin was meant to be removed as well.
2017-02-22 15:35:04 +01:00
6716f5a2f4 WHATS_NEW: add entry 2017-02-22 15:20:52 +01:00
263050bc07 man/help: enclose each option in brackets
Placing [] around each individual option is the most
common style, and it improves the readability.
2017-02-21 14:59:52 -06:00
c1ce371b59 man/help: use separate common option lists
There are two kinds of common options:
1. options common to all variants of a given command name
2. options common to all lvm commands

Previously, both kinds of common options were listed together
under "Common options".  Now the first are printed under
"Common options for command" (when needed), and the second
are printed under "Common options for lvm" (always).
2017-02-21 14:32:54 -06:00
b7ae57c6a6 man: teaking output format 2017-02-21 12:27:51 -06:00
21fc35dd1b commands: adjust default help output
Remove the "usage notes" which should just
live in the man pages.

When there are 3 or more variants of a command,
print all the options produces a lot of output,
so require --longhelp to print all the options
in these cases.
2017-02-21 12:27:51 -06:00
7e411b111f man lvm: update see also list
add several missing references
remove references to lvmdiskscan lvmchange
2017-02-21 12:27:51 -06:00
f80d373753 man: expand type option description 2017-02-21 12:27:51 -06:00
d2dbe71fb3 dmsetup: Indicate device repetition in usage summaries. 2017-02-21 11:25:18 +00:00
1c1ce2739e tests: some debug code
Checking if --deferred would make it any faster - but it's as slow
as without this new optional flag anyway (4.10).
2017-02-21 09:40:21 +01:00
2a65e2d49e tests: ensure first call is version test
Check 'dmsetup version'  is called before starting any more
advanced logic in $DM_DEV_DIR.

Call also replaces mkdir as it creates needed path with control node.
2017-02-21 09:38:49 +01:00
7c14004f69 tests: make sure which PV is used for allocation 2017-02-21 09:38:04 +01:00
d409fec079 tests: paralelize creation and teardown
To speedup initial construction and destruction of test devices
(mainly in case more then 1 is needed)  call dmsetup
in parallel.
2017-02-21 00:52:05 +01:00
921d5972e8 tests: use exclusive activation for mirror
Test suite does not support clustered mirroring.
2017-02-21 00:52:05 +01:00
86a660be7b man: use .HP instead of .TP 2017-02-20 17:10:11 -06:00
e13639053b man/help: print general raid type as "raid"
Instead of printing "raid*".  There are already
notes mentioning that "raid" refers to "raid<N>"
2017-02-20 15:41:24 -06:00
d22cccdf63 man vgchange/lvchange: note special option usage 2017-02-20 15:36:30 -06:00
a2d2cd8777 man lvcreate: add special option notes at the start
The --name, --size, --extents options deserve a special
note at the start of the man page, before appearing in
the usage section.
2017-02-20 15:36:30 -06:00
2396c50689 man: add variables descriptions
Add a section describing variables.

In the full options list, include common
options in the alphabetical listing instead
of at the end.
2017-02-20 15:36:10 -06:00
4d29d9afb2 lvresize/lvextend: accept type option
The --type option has previously been accepted for
lvresize/lvextend.  Using it did not affect the operation
of the command.  The value was simply verified as matching
the current seg type of the LV.
2017-02-20 11:23:46 -06:00
5f2639d01d tests: update lvresize testing
Add missing tests for some lvresize acceptable options.
2017-02-20 00:44:12 +01:00
13dd1ca757 cleanup: simplier code
Already know string is 'lvm-' so use name[3].
2017-02-20 00:43:40 +01:00
2260c6d1e6 cleanup: same sign for compare 2017-02-20 00:43:40 +01:00
d8514b24e1 cleanup: use multiline string 2017-02-20 00:43:40 +01:00
aff62c74b7 cleanup: use const 2017-02-20 00:43:40 +01:00
f16ad760cb man: thin dmeventd plugin update
Document new dmeventd/thin_command lvm.conf configurable.
2017-02-20 00:43:12 +01:00
cd24e6de89 man: dmstats update
Fixing colorization bugs
2017-02-19 22:59:43 +01:00
665479b818 man: dmsetup update 2017-02-19 22:59:43 +01:00
2a21a19d90 commands: fix memleak
Keep all allocations 'mempool' allocated for simple cleanup.
2017-02-19 22:59:43 +01:00
87c89ac279 lvresize: fix regressiong on accepting args
Commit f45b689406 caused regression
of lvresize -m and --type  parameter

After fix this sequence may work when we also fix syntax description:

lvcreate -l1 -m1 -n lv1 vg
lvextend --type mirror -m1 -l+1 vg/lv1
2017-02-19 22:59:43 +01:00
13944738d4 man/help: fix description of r|R unit 2017-02-17 15:44:26 -06:00
fab0d63121 man: print space before built-in name
print 'lvm config' not 'lvm-config'
2017-02-17 15:33:35 -06:00
87fe9328d3 man pvmove: move details to notes 2017-02-17 15:28:00 -06:00
6064b0359a man: mention force behavior in various places 2017-02-17 15:11:19 -06:00
50e0345f9d man lvmconfig: refer to typeconfig option name 2017-02-17 14:46:10 -06:00
10cb8e0ec0 man/help: show recently added r|R unit 2017-02-17 14:44:11 -06:00
3cf3943898 args: in yes option mention qq for auto-no 2017-02-17 14:44:11 -06:00
f88ce5fb99 lvconvert: include swap behavior in generic pool syntax
For this syntax:
lvconvert --thinpool LV1 --poolmetadata LV2
lvconvert --cachepool LV1 --poolmetadata LV2

Restore the metadata swapping behavior in addition to
the pool creation behavior.  When LV1 is already a pool,
the metadata LV will be swapped with LV2.
When LV1 is not a pool, it will be converted to a
pool using the specified LV for metadata.

This syntax is no longer advertised because of the
ambiguous behavior.  The primary syntaxes for pool
creation and metadata swapping will be the advertised
methods.
2017-02-17 13:20:15 -06:00
56deed9d54 commands: compensate --uuid
As we now user binary search - it's nondeterministict
which of the same 'args' will be give - so duplicates
need 'extra' care.

So provide same hack for output for --uuidstr_ARG as
for input.

Solves 'pvscan -u'.
2017-02-17 13:57:59 +01:00
00f299b932 commands: some more dm wrappers
As man-generator is not liked with libdm as of now - some more wrappers.
2017-02-17 13:36:57 +01:00
238a79aac4 cleanup: unused uninit vars 2017-02-17 13:20:55 +01:00
995f7aa92f cleanup: use strchr for 1-byte lookup 2017-02-17 13:20:55 +01:00
46d6c7d3ad cleanup: add comment for longer macro 2017-02-17 13:20:55 +01:00
772834e40a commands: optimize binary search
Since there is a lot of options and lot of searches,
use binary search to keep strcmp at minimum.

The interesting part is - alphabetically sorted array contains
duplicates and some of them are not the 'right anwer', so
after we find matching string but not matching long_ARG,
we may need to check if the surrouding strings are the right matching
one.

The single loops is used also for strictly define --foo_long
(i.e. --stripes)  and just differs at final part.

TODO1: replace strstr call with some flag (just like short_opt).
TODO2: drop '--' from being stored and tests by strcmp.
2017-02-17 13:20:55 +01:00
582a272b3f commands: use dm_strncpy
Easier code using dm_strncpy() an dm_snprintf().
2017-02-17 13:11:33 +01:00
80b717af0c commands: cheap optimisation for parser
Some low-hanging fruits to cut of signification number of strcmp calls.
2017-02-17 13:00:05 +01:00
298b11aed1 commands: track errors in command def parsing
When parsing command defs, track and report all
errors that are found.  Add an error return case
from define_commands so the standard error exit
path is used.
2017-02-16 15:26:42 -06:00
1cb95fa5a0 commands: initialize commands[] once
When using liblvm2cmd, a process can do multiple
init/exit calls, i.e.

lvm2_init(); lvm2_run(); lvm2_exit();
lvm2_init(); lvm2_run(); lvm2_exit();
...

define_commands() needs to set up the global commands[]
definitions only the first time.
2017-02-16 13:59:52 -06:00
15f51bc421 commands: avoid factoring options until needed 2017-02-16 09:37:28 -06:00
22bee4fbdb help/man: remove commas from list of options
Using commas between options does not seem to
be done anywhere else, so remove them.
2017-02-15 15:51:46 -06:00
81c0ed9fc6 commands: use dm wrappers for malloc/free 2017-02-15 15:49:18 -06:00
6a5c9ba349 commands: use existing vg/lv name parsing functions
inside the new lv arg parsing function.

This includes getting the VG name from the env var,
and some added checks on the format of the vg/lv string.
2017-02-15 15:28:54 -06:00
2556498ee1 lvcreate: fix LVM_VG_NAME detection
Commit d3af0e7528 was
not quite right in testing if the env var was set.
2017-02-15 14:10:46 -06:00
4a30f5f9b0 toollib: skip dev prefix from lv names
_get_arg_lvnames_using_options() was missing skip_dev_dir()
2017-02-15 13:42:35 -06:00
286d39ee3c lvconvert: handle old arg quirk when combining snapshot
The old ad hoc arg parsing when combining a split snapshot
allowed the first lv to have a vgname, but not the second.
Since lvconvert now uses the standard arg parsing in
process_each_lv(), the old one-off behavior requires a
work around.
2017-02-15 12:40:35 -06:00
d3af0e7528 lvcreate: LVM_VG_NAME applies even without name arg
There was a small flaw in the logic regarding when LVM_VG_NAME
can replace a VG position arg.
2017-02-15 12:07:51 -06:00
7417c8acfa Revert "lvconvert: enable previous syntax to swap metadata"
This reverts commit 717363bb94.

These alternate forms for swapping metadata cannot be
distinguished from the command for creating a pool.
If we were to add these alternate forms for swapping
metadata, we would need to overload the pool creation
command defs, making those definitions ambiguous.
2017-02-14 16:02:54 -06:00
d2c5bb5c70 coverity cleanups 2017-02-14 15:53:29 -06:00
1236e0ed29 man-generator: fix compiler warnings 2017-02-14 10:28:52 -06:00
1dddb068c9 man/help: use separator in units list
h|H|b|B|... instead of hHbB...
2017-02-14 10:21:39 -06:00
c0f2a59993 commands: skip parsing command defs for other command names
The base command name can be used to skip parsing
command defs that will not be needed.
2017-02-14 10:16:13 -06:00
f46b28bdb6 commands: improve help/usage output
Replace --help --help with --long-help.
Some blank lines were needed.
Add 'lvm help all' to print help for all commands.
2017-02-14 09:52:09 -06:00
c868562a79 Makefile: all_man also requires man-generator now 2017-02-14 13:24:31 +00:00
22457ed4d9 makefiles: missing deps 2017-02-14 10:24:56 +01:00
fc0e49297d makefiles: use configure vars
Use binaries found in configure.
2017-02-14 10:24:56 +01:00
3350eb67cc libdm: move code for _stats_resize_group
Code is only needed when "fiemap.h" so keep it under single #ifdef.
2017-02-14 10:24:56 +01:00
6118b0fb93 configure: update 2017-02-14 00:05:04 +01:00
65b82a8072 activation: trust 'pending' status reported by dmeventd
Only usleep when dmeventd reports 'pending' otherwise trust reported
state.
2017-02-14 00:04:26 +01:00
05dd566a52 dmeventd: unify error handling
Always make sure the 'status' is release on 'error' path (thin pluging missed)
Make code looking same across all plugins.
2017-02-14 00:03:34 +01:00
5a87d8667d coverity cleanups for recent command defs commits 2017-02-13 16:11:04 -06:00
5ab051df7a WHATS_NEW: changes for recent command defs 2017-02-13 15:36:17 -06:00
c816e8b636 WHATS_NEW: items from command definitions patch set 2017-02-13 15:22:26 -06:00
717363bb94 lvconvert: enable previous syntax to swap metadata 2017-02-13 14:41:54 -06:00
b2fd5b31d3 commands: suggest --help if command doesn't match 2017-02-13 13:46:17 -06:00
698abdde16 generate man pages 2017-02-13 10:31:23 -06:00
13a6368522 args: use arg parsing function for region size
Consolidate the validation of the region size arg
in a new arg parsing function.
2017-02-13 08:21:58 -06:00
a1386dcca0 lvconvert: remove code for changing region size
from the generic raid type conversion code.
2017-02-13 08:21:58 -06:00
46abc28a48 lvconvert: add command to change region size of a raid LV 2017-02-13 08:21:58 -06:00
8152e4a99e vgchange: fix uint32 parsing of logicalvolume arg 2017-02-13 08:20:10 -06:00
2224b6a701 commands: recognize raid variations 2017-02-13 08:20:10 -06:00
c3faa5816d commands: move command def parsing into lvm binary
It was previously done at build time by the ccmd binary.
2017-02-13 08:20:10 -06:00
942dc07402 lvconvert: remove unused code
For "split" which is not an alias for splitmirrors.
2017-02-13 08:20:10 -06:00
f067c0ad78 args: split is a synonym for splitcache
also tidy the other synonyms
2017-02-13 08:20:10 -06:00
c3e1838382 man: lvmthin updates
Some minor changes to some of the command syntaxes
to use more standard forms.
2017-02-13 08:20:10 -06:00
15d9f2850e ccmd: split into multiple files 2017-02-13 08:20:10 -06:00
013c080756 command struct: remove command name refs
Change run time access to the command_name struct
cmd->cname instead of indirectly through
cmd->command->cname. This removes the two run time
fields from struct command.
2017-02-13 08:20:10 -06:00
d9d5b8414b command.h comment tidying 2017-02-13 08:20:10 -06:00
9a0f0c70bf lvm shell: clear argv for each command 2017-02-13 08:20:10 -06:00
23a1ced439 help: accept positional args
lvm help <commandname> ...
2017-02-13 08:20:10 -06:00
3642deb4f3 fix lvmcmdline warning
declaration of ‘usage’ shadows a globa
2017-02-13 08:20:10 -06:00
4d2c3502e7 man lvm: remove options
all options are now included in commands
2017-02-13 08:20:10 -06:00
5c779b3231 args: add man page descriptions 2017-02-13 08:20:10 -06:00
db26a82f2f args: use uint32 arg for maxphysicalvolumes 2017-02-13 08:20:10 -06:00
041c2fef88 lvconvert: remove unused code 2017-02-13 08:20:10 -06:00
46b2599d5c lvconvert: use command defs for raid/mirror types
All lvconvert functionality has been moved out of the
previous monolithic lvconvert code, except conversions
related to raid/mirror/striped/linear.  This switches
that remaining code to be based on command defs, and
standard process_each_lv arg processing.  This final
switch results in quite a bit of dead code that is
also removed.
2017-02-13 08:20:10 -06:00
a801b92b2c tests: use swapmetadata
and some other pool/cache/thin related changes
2017-02-13 08:20:10 -06:00
86d8ab493b lvconvert: use command defs for mergemirrors
and route the generic --merge to one of the
specific merge functions
2017-02-13 08:20:10 -06:00
95e38607ec toollib: find VG name in option values when needed 2017-02-13 08:20:10 -06:00
0e3e611a13 lvconvert: use command defs for thin/cache/pool creation
Everything related to thin and cache.
2017-02-13 08:20:10 -06:00
d71aaca07b lvconvert: add startpoll command using command def
This is a new explicit version of 'lvconvert LV'
which has been an obscure way of triggering polling
to be restarted on an LV that was previously converted.
2017-02-13 08:20:10 -06:00
fa2a728a39 lvconvert: snapshot: use command definitions
Lift all the snapshot utilities (merge, split, combine)
out of the monolithic lvconvert implementation, using
the command definitions.  The old code associated with
these commands is now unused and will be removed separately.
2017-02-13 08:20:10 -06:00
254bffb95d lvconvert: remove unused calls for repair and replace
repair and replace are no longer called from the
monolithic lvconvert code, so remove the unused code.
2017-02-13 08:20:10 -06:00
35b9d4d6e9 lvconvert: repair and replace: use command definitions
This lifts the lvconvert --repair and --replace commands
out of the monolithic lvconvert implementation.  The
previous calls into repair/replace can no longer be
reached and will be removed in a separate commit.
2017-02-13 08:20:10 -06:00
52c60b7e7b lvchange: make use of command definitions
Reorganize the lvchange code to take advantage of
the command definition, and remove the validation
that is done by the command definintion rules.
2017-02-13 08:20:10 -06:00
9c6c55c314 process_each_lv: add check_single_lv function
The new check_single_lv() function is called prior to the
existing process_single_lv().  If the check function returns 0,
the LV will not be processed.

The check_single_lv function is meant to be a standard method
to validate the combination of specific command + specific LV,
and decide if the combination is allowed.  The check_single
function can be used by anything that calls process_each_lv.

As commands are migrated to take advantage of command
definitions, each command definition gets its own entry
point which calls process_each for itself, passing a
pair of check_single/process_single functions which can
be specific to the narrowly defined command def.
2017-02-13 08:20:10 -06:00
1e2420bca8 commands: new method for defining commands
. Define a prototype for every lvm command.
. Match every user command with one definition.
. Generate help text and man pages from them.

The new file command-lines.in defines a prototype for every
unique lvm command.  A unique lvm command is a unique
combination of: command name + required option args +
required positional args.  Each of these prototypes also
includes the optional option args and optional positional
args that the command will accept, a description, and a
unique string ID for the definition.  Any valid command
will match one of the prototypes.

Here's an example of the lvresize command definitions from
command-lines.in, there are three unique lvresize commands:

lvresize --size SizeMB LV
OO: --alloc Alloc, --autobackup Bool, --force,
--nofsck, --nosync, --noudevsync, --reportformat String, --resizefs,
--stripes Number, --stripesize SizeKB, --poolmetadatasize SizeMB
OP: PV ...
ID: lvresize_by_size
DESC: Resize an LV by a specified size.

lvresize LV PV ...
OO: --alloc Alloc, --autobackup Bool, --force,
--nofsck, --nosync, --noudevsync,
--reportformat String, --resizefs, --stripes Number, --stripesize SizeKB
ID: lvresize_by_pv
DESC: Resize an LV by specified PV extents.
FLAGS: SECONDARY_SYNTAX

lvresize --poolmetadatasize SizeMB LV_thinpool
OO: --alloc Alloc, --autobackup Bool, --force,
--nofsck, --nosync, --noudevsync,
--reportformat String, --stripes Number, --stripesize SizeKB
OP: PV ...
ID: lvresize_pool_metadata_by_size
DESC: Resize a pool metadata SubLV by a specified size.

The three commands have separate definitions because they have
different required parameters.  Required parameters are specified
on the first line of the definition.  Optional options are
listed after OO, and optional positional args are listed after OP.

This data is used to generate corresponding command definition
structures for lvm in command-lines.h.  usage/help output is also
auto generated, so it is always in sync with the definitions.

Every user-entered command is compared against the set of
command structures, and matched with one.  An error is
reported if an entered command does not have the required
parameters for any definition.  The closest match is printed
as a suggestion, and running lvresize --help will display
the usage for each possible lvresize command.

The prototype syntax used for help/man output includes
required --option and positional args on the first line,
and optional --option and positional args enclosed in [ ]
on subsequent lines.

  command_name <required_opt_args> <required_pos_args>
          [ <optional_opt_args> ]
          [ <optional_pos_args> ]

Command definitions that are not to be advertised/suggested
have the flag SECONDARY_SYNTAX.  These commands will not be
printed in the normal help output.

Man page prototypes are also generated from the same original
command definitions, and are always in sync with the code
and help text.

Very early in command execution, a matching command definition
is found.  lvm then knows the operation being done, and that
the provided args conform to the definition.  This will allow
lots of ad hoc checking/validation to be removed throughout
the code.

Each command definition can also be routed to a specific
function to implement it.  The function is associated with
an enum value for the command definition (generated from
the ID string.)  These per-command-definition implementation
functions have not yet been created, so all commands
currently fall back to the existing per-command-name
implementation functions.

Using per-command-definition functions will allow lots of
code to be removed which tries to figure out what the
command is meant to do.  This is currently based on ad hoc
and complicated option analysis.  When using the new
functions, what the command is doing is already known
from the associated command definition.
2017-02-13 08:20:10 -06:00
19267fa6aa lvmlockd: test mode doesn't work
The --test option is not yet compatible with shared VGs
because changes are made in lvmlockd that cannot be
reversed or faked.
2017-02-13 08:20:10 -06:00
2923d9e47d tests: update 2017-02-13 10:06:19 +01:00
c3b1f1a07a tests: fix dev path
Use proper device path for test devices.
Use mkfs.ext4 and drop  'echo y|' to it.
Use smaller device size to consume less memory and CPU time.
2017-02-13 10:06:19 +01:00
a3579aafc5 cleanup: use matching signed number comparation 2017-02-13 10:06:19 +01:00
7cbee8f31a cleanup: use matching const type 2017-02-13 10:06:18 +01:00
b6301aa977 cleanup: use fall through
gcc gets 'selective' on having commented fall through case.
2017-02-13 10:06:18 +01:00
a39c828c01 cleanup: fix warning about shadowed declaration
Avoid shadowing lv_size as lv_size() is already defined function in lv.h
2017-02-13 10:06:18 +01:00
717d0c6b94 cleanup: use proper printf specifier 2017-02-13 10:06:18 +01:00
b185a3e333 config: update doc 2017-02-13 10:06:07 +01:00
aa0c735e2c dmeventd: limit thin_command usage
Require usable command string to begining with '/'
So 'thin_command = "/some/path/command"' is the only supported variant
to internal 'lvm' command.
2017-02-13 09:43:53 +01:00
416f951283 coverity: fix double free
Do not try to free hist_arg twice.
2017-02-12 17:28:44 +01:00
a7d2ee4bc2 coverity: fix mem leak on error path in dm stats
Free allocated resouces on error path.
2017-02-12 17:28:13 +01:00
0844b20f98 coverity: remove unneeded header files 2017-02-11 21:17:27 +01:00
375e38709c cleanup: drop double const specifier
Remove duplicated 'const' specifier.
Reindent.
2017-02-11 20:30:16 +01:00
2a9eda1229 mem: add extra mem pages for pthread stack
Some archs can use even 64K pages and then lvm2 runs into trouble if
the stack is 'too small' to fit extra page capturing stack overwrite.

So when lvm2 limits stack - add extra mem page - be it 4K or 64K.

Relates to ppc64le bug: https://bugzilla.redhat.com/1387279
2017-02-11 18:23:15 +01:00
8296b99a89 lvconvert: remove test code
Remove allocate_pvs from raid_manip.c:_region_size_change_request() API
and lv_extend() using it added for temporary test purpose.

Related: rhbz1366296
2017-02-10 23:44:27 +01:00
28ea66d46d lvconvert: add region size checks
Add:
- region size checks to raid_manip.c types array and supporting functions
- tests to lvconvert-raid-takeover.sh to check bogus
  "lvconvert --type  --regionsize N " requests

Related: rhbz1366296
2017-02-10 23:37:08 +01:00
caa2094e33 test: lvresize-raid.sh missing conditional
Test missed to check for raid0 present in the kernel.

Related: rhbz1366296
2017-02-10 21:22:38 +01:00
c908a8b131 libdm: avoid resume if preloaded device is smaller
When we preload device with smaller size, we avoid its resume,
so later suspend/resume of full device tree my process all
existing in flight bios.

Also update comment and avoid using confusing opposite meaning.
2017-02-10 20:29:11 +01:00
035c614c19 dmsetup: do not suppress kernel key descriptions in tables
Kernel 4.10 (dm-crypt v1.15.0) and later supports loading device
tables with crypt segment having key in kernel keyring retention
service.

dmsetup hid key section of tables output. With this patch dmsetup
no longer hides key section if it detects kernel key description
instead of hex byte representation of key itself.
2017-02-10 19:18:49 +01:00
baba3f8e2a lvconvert: add conversion from/to raid10
Add:
- conversion support from striped/raid0/raid0_meta to/from raid10;
  raid10 goes by the near format (same as used in creation of
  raid10 LVs), which groups data copies together with their original
  blocks (e.g. 3-way striped, 2 data copies resulting in 112233 in the
  first stripe followed by 445566 in the second etc.) and is limited
  to even numbers of legs for now
- related tests to lvconvert-raid-takeover.sh
- typo

Related: rhbz1366296
2017-02-10 19:13:02 +01:00
68ec6940e6 man: mention dmstats in lvmsar and lvmsadc man pages 2017-02-10 17:09:17 +00:00
55eaabd118 lvreduce/lvresize: add ability to reduce the size of a RaidLV
- support shrinking of raid0/1/4/5/6/10 LVs
- enhance lvresize-raid.sh tests: add raid0* and raid10
- fix have_raid4 in aux.sh to allow lv_resize-raid.sh
  and other scripts to test raid4

Resolves: rhbz1394048
2017-02-09 22:42:03 +01:00
79f31008fa lvconvert: add support to change RAID region size (fixup)
Commit cfb6ef654d introduced
support to change RAID region size.

Fix:
- don't change region_size until after prompting the user
- use log_print_unless_silent() instead of log_warn()
- avoid superfluous sigint() calls which are already
  covered in yes_no_prompt()
- typo

Related: rhbz1392947
2017-02-07 19:05:01 +01:00
69fe8729f3 lvconvert: avoid setting segment flag
Fix:
- don't set SEG_RAID in _convert_mirror_to_raid1() errounously

Related: rhbz1366296
2017-02-07 17:48:17 +01:00
46a772fbc4 lvconvert: add support to change RAID region size (fixup)
Commit cfb6ef654d introduced
support to change RAID region size.

Add:
- missing conditions to support any types to function with
  it in lv_raid_convert();  temporary workaround used until
  cli validation patches get merged
- tests requesting "-R " to lvconvert-raid-takeover.sh
  involving a cleanup of the script

Related: rhbz1392947
2017-02-07 16:52:04 +01:00
91c4bd14d0 lvconvert: add segtype raid5_n and conversions to/from it (cleanup)
Cleanups as of Jons review:
- enhance comment about mandatory raid4 <-> raid5_n activation w/o metadata SubLVs
- remove bogus segment flag setting
- fix to sync related comments on conversions to raid0/striped and amongst raid4/5
- add missing error message for non-synced conversion to raid0/striped

Related: rhbz1366296
2017-02-07 12:25:26 +01:00
cfb6ef654d lvconvert: add support to change RAID region size
Add:
- support to change region size of existing RaidLVs
  (all RAID LV types but raid0/raid0_meta)
- lvconvert-raid-regionsize.sh with test variations
  for different RAID types and region sizes

Resolves: rhbz1392947
2017-02-07 01:01:19 +01:00
51d03acb1c tests: drop zeroing
Well waiting for zeroing may take enough time to finish 'raid' sync.
So make the test running faster without zeroing and better avoid race
to have chance to happen (i.e. lvcreate is finished after array
gets already in sync).
2017-02-06 13:15:39 +01:00
48abbdf452 tests: drop /tmp polution
Drop forgotten extra metadata debug.
2017-02-06 11:43:07 +01:00
811d137d3f cleanup: hide gcc warning
Gcc is not clever enough to see these vars are actually initialize in
given code path so let's just make sure it has a value.
2017-02-06 11:43:07 +01:00
9fe8c2da36 debug: add space before uuid
With commit 8853462528 we added
uuid right after device name. Add space between them.
(Also fix some indenting)
2017-02-05 17:55:37 +01:00
12bbfbe89d comment: update
Fix can -> cannot.
2017-02-05 17:55:37 +01:00
fb3f4ed72d cleanup: rename to use track_ prefix
Since we use 'track_' prefix for other deps tracking,
convert skip_external_lv to use same logical meaning.
(just converts  1->0  0->1)
2017-02-05 17:55:37 +01:00
dae4f53acb clvmd: add mutex protection for cpg_ call
The library for corosync multicasting is not supporting multithread
usage - add local mutex to avoid parallel call of cpg_mcast_joined().
2017-02-05 17:55:37 +01:00
a4bbaa3b89 lvconvert: add segtypes raid6_{ls,rs,la,ra}_6 and conversions to/from it
Add:
- support for segment types raid6_{ls,rs,la,ra}_6
  (striped raid with dedicated last Q-Syndrome SubLVs)
- conversion support from raid5_{ls,rs,la,ra} to/from raid6_{ls,rs,la,ra}_6
- setting convenient segtypes on conversions from/to raid4/5/6
- related tests to lvconvert-raid-takeover.sh factoring
  out _lvcreate,_lvconvert funxtions

Related: rhbz1366296
2017-02-05 00:56:27 +01:00
d8568552e4 WHATS_NEW: New segment type raid6_n_6 2017-02-04 14:09:26 +01:00
3673ce48e0 lvconvert: add segtype raid6_n_6 and conversions to/from it
Add:
- support for segment type raid6_n_6 (striped raid with dedicated last parity/Q-Syndrome SubLVs)
- conversion support from striped/raid0/raid0_meta/raid4 to/from raid6_n_6
- related tests to lvconvert-raid-takeover.sh

Related: rhbz1366296
2017-02-04 01:42:21 +01:00
96f331fe05 WHATS_NEW: New segment type raid5_n 2017-02-03 23:41:48 +01:00
7e92535d47 lvconvert: add segtype raid5_n and conversions to/from it
Change:
- missed a return_0
- use lvseg_name() rather than my own function

Related: rhbz1366296
2017-02-03 22:16:35 +01:00
60ddd05f16 lvconvert: add segtype raid5_n and conversions to/from it
Add:
- support for segment type raid5_n (striped raid with dedicated last parity SubLVs)
- conversion support from striped/raid0/raid0_meta/raid4 to/from raid5_n
- related tests to lvconvert-raid-takeover.sh

Related: rhbz1366296
2017-02-03 20:40:26 +01:00
875ce04c61 lvmdbusd: cmdhandler.py, remove duplicate code
Move similar code to common functions, less is more!
2017-02-01 19:05:41 -06:00
3eccbb4b47 lvmdbusd: manager.py, remove duplicate code
Move similar code to common functions, less is more!
2017-02-01 18:57:01 -06:00
945842fa68 lvmdbusd: lvmdb.py, remove duplicate code
Move similar code to common functions, less is more!
2017-02-01 18:56:39 -06:00
681d69c70a lvmdbusd: pv.py, remove duplicate code
Move similar code to common functions, less is more!
2017-02-01 16:51:00 -06:00
a010cede6e lvmdbusd: vg.py, remove duplicate code
Move similar code to common functions, less is more!
2017-02-01 16:37:03 -06:00
83a1907586 lvmdbusd: lv.py, remove duplicate code
Move similar code to common functions, less is more!
2017-02-01 15:38:55 -06:00
2350ea0060 man: add update_filemap to dmstats.8.in 2017-01-25 16:15:21 +00:00
b999d5f501 dmstats: allow --filemap groups to be updated
Add a new update_filemap command to dmstats that allows a filemap
group to be updated:

  # dmstats update_filemap --groupid 0 vm.img
  /var/lib/libvirt/images/vm.img: Updated group ID 0 with 137 region(s).

This will update the set of regions mapped to the file to reflect
the current file system allocation.

Currently this needs to be run manually - a future update will add
support for monitoring file maps via a daemon, allowing them to be
automatically updated when the underlying file is modified.
2017-01-25 16:15:21 +00:00
e0d19feb85 libdm: add dm_stats_update_regions_from_fd()
Add a call to update the regions corresponding to a file mapped
group of regions. The regions to be updated must be grouped, to
allow us to correctly identify extents that have been deallocated
since the map was created.

Tables are built of the file extents, and the extents currently
mapped to dmstats regions: if a region no longer has a matching
file extent, it is deleted, and new regions are created for any
file extents without a matching region.

The FIEMAP call returns extents that are currently in-memory (or
journaled) and awaiting allocation in the file system. These have
the FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_DELALLOC flag bits set
in the fe_flags field - these extents are skipped until they
have a known disk location.

Since it is possile for the 0th extent of the file to have been
deallocated this must also handle the possible deletion and
re-creation of the group leader: if no other region allocation
is taking place the group identifier will not change.
2017-01-25 16:15:21 +00:00
1c00bb5da3 libdm: test for DM_STATS_GROUP_NOT_PRESENT in _stats_group_id_present
If the group_id passed to _stats_group_id_present is equal to the
special value DM_STATS_GROUP_NOT_PRESENT there is no need to perform
any further tests: return false immediately.
2017-01-25 15:29:35 +00:00
ca427a711a libdm: fix stats comment formatting in libdevmapper.h 2017-01-24 09:29:31 +00:00
ec93f37b86 toolcontext: action for LVM_RUN_BY_DMEVENTD env var
When LVM_RUN_BY_DMEVENTD is set to 1, ensure there will
be no interaction with dmeventd.
2017-01-23 14:55:47 +01:00
836eb122ce dmeventd_thind: set LVM_RUN_BY_DMEVENTD
Set LVM_RUN_BY_DMEVENTD envvar to expose the command is runing from
dmeventd environment.
2017-01-23 14:55:47 +01:00
4a7f2155c1 clean: move code to lib part
Move actual processing part of the lvm2_disable_dmeventd_monitoring()
into a /lib part so we can reuse the code later for other cases.
2017-01-23 14:55:28 +01:00
2d48317d3a tests: umount when above 95
Add code to check if resulting data or metadata remained over 95%
and in such case invoke umount.
2017-01-21 22:53:57 +01:00
e2fa90bf38 tests: properly quote heredoc
Prepend \$ for vars which should remain in script.
Also drop --lazy umount.
Move inittest call up, so mntdir and mntusedir have proper full path.
2017-01-21 19:28:06 +01:00
1a2b88516b tests: implement umount in script
Since dmeventd no longer umounts thin devices, such logic
needs to be implemented by external script.
Add some very simple one for the start.
2017-01-21 17:42:19 +01:00
47c11c7b1c tests: enusure units in TiB 2017-01-21 17:42:19 +01:00
2e0605d6db dmeventd_thin: internal command without lvm prefix
Internal command processing needs to go without 'lvm ' prefix.
2017-01-21 17:42:19 +01:00
85dab3963f dmeventd_thin: enable support for external command
With this commit we start to support configurable action
from thin-pool monitoring via  'dmeventd/thin_command'
2017-01-21 00:01:05 +01:00
8c4f3633ac dmeventd_thin: new logic for calling commands
For more advanced support we need to ensure better logic for calling
external much more advanced script for maintanance of thin-pool.

So this new code ensures:

When thin-pool data or metadata is bigger then 50%,
then with each 5% increment, action is called.
This is independent from autoextend_threshold.
This action always happens when thin-pool is over threshold,
(so no action when it's exactly i.e. 60%).
The only exception is 100% full thin-pool - which invokes 'last'
action.

Since thin-pool occupancy may change also downward, code needs
to also handle possibly reduction of occupancy  of thin-pool.
So when usage drop from 90% to 50%, thin-pool will start to call
again action when it will pass 55% threshold.

This give external commands lot of option i.e. to call 'fstrim'
before actual resize is needed.
2017-01-20 23:58:56 +01:00
8b95551ade dmeventd_thin: drop umounting on error path
Default internal logic will stop trying to do any 'rescue' action
when executed command fails.
This will be now fully in hands of external script if such
behaviour is needed.
2017-01-20 23:58:56 +01:00
43e3268ada dmeventd_thin: rework failure handling
Instead of stopping monitoring after couple failing retries,
keep monitoring forever, just make larger delays between command
retries (ATM upto ~42 minutes).

So syslog is not spammed too often, yet commands have a chance to
be retried and succeed eventually...
2017-01-20 23:56:39 +01:00
46c23dfb87 dmeventd_thin: SIGCHLD handler
To improve reaction time on when child is finished,
lets handle SIGCHLD in particular thread.
Let's hope kernel will route SIGCHLD to matching thread.
2017-01-20 23:55:51 +01:00
bc7a1d70d4 dmeventd_thin: init command
When dmeventd configured command does not start with 'lvm ' prefix,
it's going to be an 'external' command.
In this case we split command by spaces to argv strings.
2017-01-20 23:55:50 +01:00
14746a6c00 dmeventd_thin: add wait_pid
Add support handling command exit.
2017-01-20 23:55:50 +01:00
2e935c0967 dmeventd_thin: add run_command
Implement forking of executable command.
When command is forked, dmeventd may continue monitor device.
2017-01-20 23:55:50 +01:00
e5bef50827 dmeventd_thin: better warning logic
When fullness is passing WARN_THRESHOLD, print warning,
when it drops bellow and crossed again, we should print
warning again, but always only once.
2017-01-20 23:55:50 +01:00
0d945ddbad dmeventd_thin: switch to struct percent
Later we can use stored percent values to pass them
to executed commands.
2017-01-20 23:55:50 +01:00
eca964b554 dmeventd_thin: handling of internal command 2017-01-20 23:55:50 +01:00
d80f9a107f lvmcmd2lib: support new command
Internal command which reads lvm.conf settins and passes it
via envvar to dmeventd monitoring thread.
2017-01-20 23:55:07 +01:00
04a9cad499 config: new option dmeventd/thin_command
This setting will allowing configuring which command gets executed
when thin-pool fullness goes from 50%..100%
2017-01-20 23:53:26 +01:00
ee754500db cleanup: update config doc 2017-01-20 23:52:40 +01:00
f8234d6e5f libdm: add human R|readable units
When showing sizes with 'H|human' units we do use standard rounding.
This however is confusing users from time to time,
when the printed number uses some biger units i.e. GiB and there is just
tiny fraction of space missing.

So here is some real-life example with new 'r' unit.

$lvs

  LV    VG Attr       LSize  Pool Origin
  lvol0 vg -wi-a-----  1.99g
  lvol1 vg -wi-a----- <2.00g
  lvol2 vg -wi-a----- <2.01g

Meaning is - lvol1 has 'slightly' less then 2.00g - from sign '<' user
can be aware the LV doesn't have full 2.00GiB in size so he
will be less surpriced allocation of 2G volume will not succeed.

$ vgs
  VG #PV #LV #SN Attr   VSize  VFree
  vg   2   2   0 wz--n- <6,00g <2,01g

For uses needing  'old'  undecorated human unit simply will continue
to use 'H|h' units.

The new R|r  may further change when we would recongnize some
other way how to improve readability.
2017-01-20 23:52:17 +01:00
6a20b22151 devices: Recognise Veritas Dynamic Multipathing
VxDMP doesn't interact very well with udev so always set
  devices/obtain_device_list_from_udev = 0
in lvm.conf on these systems.
2017-01-10 22:23:23 +00:00
15e657f110 tests: ignore racy test failure
When test fails here, make it just warning instead of failing whole
test.
2017-01-06 23:39:53 +01:00
d757b2431a tests: make test more race immune
Add more delay and increase raid size.
Speedup volume during wait for sync.
Drop --yes from lvcreate.
2017-01-06 23:39:53 +01:00
a4be2be5a4 raid: postpone archiving until metadata are changed
Avoid archiving of lvm2 metadata when there is call of 'lvconvert --repair'
on healthy raid LV.
2017-01-06 23:39:04 +01:00
0d2a9ebec6 vgchange: also -l is uint32 2017-01-06 21:51:36 +01:00
8a93cde75e mirror: relax internal error for a while
With recent commit d6a74025df using
INTERNAL_ERROR while cheking layer LV - it's been noticed mirror
logic currently doesn't do a correct thing during upconversion and
does a full-try instead of checking only allocator capabilities.
This leads to invalid usage of layer.

To keep existing code running before providing a fix, relax
INTERNAL_ERROR just an error and keep the 'code' running.

Once mirror code is fixed, these all check should be switched
to internal errors.
2017-01-06 12:45:07 +01:00
d90320f4f1 blkdeactivate: also unmount mount point on top of MD device if using blkdeactivate -u
The blkdeactivate script processes MD devices too so we should unmount
any mount point on top of an MD device if blkdeactivate -u|--umount is
called.

Diagnosed and reported by: Rick Warner <rick@microway.com>
See also https://bugzilla.redhat.com/show_bug.cgi?id=1410585.
2017-01-06 11:16:07 +01:00
b92a9c3e1a tests: slow down devs for raid more
Since we still experience occasiaonal test failure - slow
things down even more to avoid race.

Add support for 'quick' table changes between normal & delayed tables.
2017-01-05 15:54:14 +01:00
c64f4447d9 tests: drop FIXME
Since we fixed core trouble with sequence of
suspend/resume/suspend without udev wait
we can drop 'should' and expect volume is still mounted.
2017-01-05 15:54:14 +01:00
74969c9a38 report: report merged state for inactive LV
This was missing piece in 77997c7673.
When merging origin is inactive (while driver is loaded) we
could already report merge in progress values as there is
no way to activate 'old state' now.
2017-01-05 15:54:14 +01:00
d6a74025df debug: show proper error message for layer mismatch
Show proper internal error for failing command when there are some
inconsitencies in sizes of LV and its layer instead of rather
meaningless error code 5.

(Could be hit i.e. if user tried to 'resize' cached LV and then
uncache such LV.)
2017-01-05 15:54:14 +01:00
3e9c03cbbc cache: resize is still unsupported
During rework of resize code this validation check
has been lost (in my resize branch). Upstream
is still not supporting resize of any cache type LV
so needs to be prevented.
2017-01-05 15:34:22 +01:00
1f5dde38a7 cleanup: more use of lvseg_name
Use existing function lvseg_name().
2017-01-03 14:55:16 +01:00
dc5bb12956 cleanup: use macros 2017-01-03 14:55:16 +01:00
ee784fd28f cleanup: defines 2017-01-03 14:55:16 +01:00
377288fe03 cleanup: reuse existing code 2017-01-03 14:55:16 +01:00
95d5877f7a cache: add missing udev wait
When we need to clear dirty cache content of cached LV, there
is table reload which usually is shortly followed by next metadata
change.  However  udev  can't (as of now)  process   udev event
while device is 'suspended'.

So whenever sequence of  'suspend/resume/suspend' is needed,
we need to wait first for finishing of 'resume' processing before
starting next 'suspend'. Otherwise there is  'race' danger of triggering
unwantend umount by systemd as  such event will trigger
SYSTEMD_READY=0 state for a moment for such changed device.

Such race is pretty ugly to trace so we may need to review more
sequencies for missing 'sync'.

(Other option is to enhnace 'udev' rules processing to avoid
such dramatic actions to be happening for suspended devices).
2017-01-03 14:55:16 +01:00
4fd41cf67f vgchange: max_pv limited to uint32
Solves: https://bugzilla.redhat.com/1280496

The only reasonable behaviour here is to error on
any number out of accepted range (i.e. now numbers
wrapping around with some hidden logic).

As this is plain bug there is no support for
backward compatibility since noone should
set numbers >UINT32_MAX and expect 0 or error
depending on how big number was used....

TODO: more fields might need to be converted.
2017-01-03 14:55:16 +01:00
9f65a3f0c5 lvmcmdline: support uint32
Add simple function to wrap usage for only uint32 numbers.
Unlike  'int_arg'  which accepts full range of 64bit number
this function will error on numbers out of this range:

   <0, UINT32_MAX>
2017-01-03 14:55:16 +01:00
e75f0b7c77 man: fix name of 'write_time' field in dmstats.8.in 2016-12-25 17:36:35 +00:00
96a1943fb8 tests: update test
lvm2 now correctly reports thin_id  after action of merged thin,
but before physical metadata update as we know the merge has happened.
2016-12-23 13:16:35 +01:00
14902d1739 validation: temporarily let pass linear with chunk_size
Old pool format seems to be setting chunk_size.
For now let validation pass with this.
2016-12-23 13:16:06 +01:00
95d68f1d0e lvchange: allow a transiently failed RaidLV to be refreshed
Add to commits 87117c2b25 and 0b8bf73a63 to avoid refreshing two
times altogether, thus avoiding issues related to clustered, remotely
activated RaidLV.  Avoid need to repeat "lvchange --refresh RaidLV"
two times as a workaround to refresh a RaidLV.  Fix handles removal
of temporary *-missing-* devices created for any missing segments
in RAID SubLVs during activation.

Because the kernel dm-raid target isn't able to handle transiently
failing devices properly we need
"[dm-devel][PATCH] dm raid: fix transient device failure processing"
as well.

test: add lvchange-raid-transient-failures.sh
      and enhance lvconvert-raid.sh

Resolves: rhbz1025322
Related:  rhbz1265191
Related:  rhbz1399844
Related:  rhbz1404425
2016-12-23 03:41:32 +01:00
62be9c8de4 tests: use hold_device_open 2016-12-22 23:37:07 +01:00
e1943fc07f tests: add device holding function
Hold device open with sleep and wait till sleep really opens
given devices.
2016-12-22 23:37:07 +01:00
1053d46aff tests: workaround failure on fc23 2016-12-22 23:37:07 +01:00
dd19b56985 thin: refresh status when error processing fails
When thin-pool processes event and 'lvextend --use-policies' fails
rather capture up-to-date new info as the fullness percentage may
have jumped noticable. This way we could use 'more' correct numbers
when checking for thresholds.
2016-12-22 23:37:07 +01:00
77997c7673 report: show proper info for merging origin
When there is 'merging' of an origin in progress, but metadata stil
do provide both origin and snapshot, we should show data from merged
snapshot.  This is important mainly for thin case, where there was
a window, where i.e. 'lvs -o+device_id' would report information
about 'already gone' origin thin LV.

This race window is usually hard to trigger but can be ocasionally hit.
Usually shortly after activation, but before polling process manages
to update metadata after merge.
2016-12-22 23:37:07 +01:00
2aee4769b4 snapshot: validate merge has started
Before starting polling process, validate the merge has actually started
so there is not pointless invoke of lvmpolld.

This also fixes reported message from command, so user has
correct info whether merging has already started or
if it's delayed for next activation.
2016-12-22 23:37:07 +01:00
95e3dd5fb1 lv: more exact check for merging origin
Merging origin has 'MERGE_LV' and should also have its merging snapshot.
2016-12-22 23:37:07 +01:00
9491ab41cd validation: rework segment validation
Move individual segment validation to a separate function
executed for 'complete_vg'.

Move some 'extra' validation bits from 'raid' validation to global
segtype validation (so extending existing normal validation)

TODO: still some test are left to be moved.
Reduce some duplication in validation process - there are still
some left thought so still room for improving overal speed.
2016-12-22 23:37:07 +01:00
eacff5c189 lvmdbustest: Print messages if timeout value > 10%
We will dump some informational messages if the time to return when we
specify a timeout exceeds 10% of requested.
2016-12-20 11:06:57 -06:00
a7e1f973cc lvmdbusd: Use timeout_add instead
The function timeout_add_seconds has quite a bit of variability.  Using
timeout_add which specifies the timeout in ms instead of seconds.  Testing
shows that this is much more consistent which should improve clients that
are using shorter timeouts for the API and the connection.
2016-12-20 11:06:57 -06:00
75568294be lvmdbusd: Use cfg.reload() instead of dbo.refresh
We want to update the data and send out any signals as needed, not just
update the in memory database.
2016-12-20 11:06:57 -06:00
6fe6e8053a lvmdbusd: Remove un-needed main thread execution 2016-12-20 11:06:57 -06:00
f47da0ad23 tests: usage of cached volume for snapshot 2016-12-19 14:41:43 +01:00
0c56eb8f43 cache: support cached origin for snapshot
Enable  'lvcreate/lvconvert -s' for cached LV.
and supported operations:

Create a snapshot of cached LV

Split/Join snapshot LV to cached origin LV.
2016-12-19 14:41:42 +01:00
eb3f83357a lvconvert: fix shown lv name for snapshot split
We can't keep 'display_lvname' for too long - it's using
ringbuffer and keeps limited number of names. So it's
safe only per few simple tests,  but can't be used anymore
after some function calls..
(Fixes 00e641ef37)
2016-12-19 14:41:16 +01:00
c90e9392e4 libdm: add dm_stats_bind_from_fd()
dmsetup already has a version of this function, and dmfilemapd will
need it too: move it to libdevmapper to avoid copying it around.
2016-12-18 20:47:17 +00:00
009b711834 libdm: clear region table in dm_stats_list()
Call _stats_regions_destroy() from dm_stats_list() if dms->regions
is non-NULL. This avoids leaking any pool allocations and ensures
the handle is in a known state: if an error occurs during the list,
dms->regions will be NULL and the handle will appear empty.
2016-12-18 20:44:31 +00:00
8d6ac1c3ba tests: using cached LV for external origin 2016-12-18 19:38:51 +01:00
8c17233af5 debug: add debug message showing new lv
Make trace easier to follow knowing which LV was added to dtree.
2016-12-18 19:38:51 +01:00
034931f68d activate: further _info API refinement
Another cleanup of internal _info() API simplifying code.
Also make sure 'error' on _info() call is properly passed upward
(return 0 is error path).
2016-12-18 19:38:51 +01:00
79121416df thin: add comment with future extension
It could be actually better to use even cache origin in
read-only mode so there could no be some 'acidental'
change being done on this volume.

This however need further tools enhancment - where we would need
to handle whole subtree on 'lvchange -pr/-prw'.
2016-12-18 19:38:51 +01:00
75f2388093 backup: show warning once per command
When command calls backup() more then once (which is actually not
wanted) this warning message is shown repeatedly:

"WARNING: This metadata update is NOT backed up."

Instead now print message just once and less confuse user.
2016-12-18 19:38:30 +01:00
5bb6266046 lvconvert: support cache to external origin conversion
Add this functionality to lvconvert:

'lvconvert --thin cachedLV --thinpool vg/poll'

Converts cachedLV to external origin (which will be read-only).
New thin volume is created in thinpool LV and it's using external
origin as source for unprovisioned chunks.
This conversion happens  online (while volume is in use).
Thin LV remains fully writable.
Cached external origin no longer could be written so cache will be used
ONLY for read operations. For this limitation we require cache mode
to be writethrough (as writeback cannot write to read-only volumes).

When  thinLV is later removed  cached external origin is again
fully usable, just note, LV remain in 'read-only' mode.
When read-write is needed,  'lvchange -prw' has to be used.

Single external origin could be user by multiple thinLV in
multiple differen thin pool.
2016-12-18 19:35:27 +01:00
69434c2eca cache: improve activation with -real
When cache volume may be converted from normal to -real layer LV
we need to improve logic for call cache_check.

With this patch, we register call for cache_check only when metadata LV
is not yet present in active table slot (should match initial table
load).
This avoids unwanted checking when cache would become layer device
online.
2016-12-18 19:30:50 +01:00
954c59779d libdm: drop callback on revert path
The system is likely in some very inconsisten state.
Do not try to make it even more problematic with trying
to invoke tools like thin_check via callback.
2016-12-18 19:29:08 +01:00
29b0e42be3 lv: fix lock holder for external origin
External origin could be reloaded via more locks.
It's actually even more complex then thin-pool,
as it may be active on more nodes for linear LVs
(and maybe even more types).

External origin is always read-only thus unmodifiable
device so there should not be a problem accesing it
through multiple nodes.

Also for thin-pool check first presence of active thin-pool.

FIXME:
It's not easy to detect on which nodes this device is active
Thus manipulation with such device may require checking every
node and it active state and refresh.

But since such setup is quite complex to prepare and use,
hopefully there are not user trying to 'explore' this usage yet.
2016-12-18 19:25:25 +01:00
a24eae6e82 cache: prepare status checking for layer
To be ready to show status of cache volume, call the status
with layer.  Layer is automatically detected in this case when
cache volume is used in 'layered' form (needs -real suffix).
2016-12-18 19:23:13 +01:00
bf157ed833 cache: improve wait for cache clear
Avoid printing misleading message about single dirty block.
Instead properly detect condition where the 'cleaner' policy
needs to be installed without 'overloading' dirty variable.

Also print warning if we would be clearing read-only volume.
(it really shouldn't happen).
2016-12-18 19:22:11 +01:00
36f609e513 validation: check external property is matching
Detect if number of external_count is matching
referencing devices for  external_origin LV.
2016-12-18 19:17:59 +01:00
7db46c4a39 thin: reload external origin with last thin
External origin could be activated as stand-alone device.
When the last thin LV is removed, external origin is no longer
the external origin and it's layer property was dropped.

Ensure dm table is correct by reloading external origin
(when it's active).
2016-12-18 19:13:34 +01:00
c71fefad8d lvs: show status for layer
When LV is external origin, show info for LV but
status for -layer.  So we expose more info to a user
as otherwise active external origin is only linear
mapping of -real layer.

We do the same for i.e. old snaphost origin.
2016-12-18 19:12:12 +01:00
bdfc96cb08 raid: fix activation of tracked image
Activation of raid has brough up also splitted image with tracing
(without taking lock for this).

So when raid is now activate - such image is not put into
table (with _rmeta).  When user needs such device, just active it.
2016-12-18 19:10:38 +01:00
a15f0d181c dmstats: don't declare _start_timestamp if HAVE_SYS_TIMERFD_H
The _start_timestamp is not used by the TIMERFD clock.
2016-12-18 14:08:11 +00:00
3e53adf7c0 dmstats: fix TIMERFD _timer_running() test 2016-12-18 14:07:25 +00:00
5a4750d76c dmstats: fix interval number reporting with --count=0
When --count=0 interval numbers are miscalculated:

Interval     #18446744069414584325     time delta:    999920887ns
Interval     #18446744069414584325   current err:       -79113ns
End interval #18446744069414584325  duration:    999920887ns

This is because the command line argument is cast through the
uint32_t type, and fixed to UINT32_MAX:

  _count = ((uint32_t)_int_args[COUNT_ARG]) ? : UINT32_MAX;

We also need to handle --count=0 specially when calculating the
interval number: since intervals count from #1, this must account
for the implicit "minus one" when converting from zero to the
UINT64_MAX value used (which is too large to store in _int_args).
2016-12-18 13:03:45 +00:00
5635cd3b03 dmstats: separate TIMERFD and useleep() exit conditions
The time management code mixes tests of the _timer_fd value with
code that should be timer agnostic: this causes problems for users
of the usleep() timer, since it cannot properly detect the start
of a new interval:

Beginning first interval
Interval     #18446744069414584348     time delta:   1000000000ns
Interval     #18446744069414584348   current err:            0ns
End interval #18446744069414584348  duration:   1000000000ns
Adjusted sample interval duration:   1000000000ns
[...]
Beginning first interval
Interval     #18446744069414584349     time delta:   1000000000ns
Interval     #18446744069414584349   current err:            0ns
End interval #18446744069414584349  duration:   1000000000ns
Adjusted sample interval duration:   1000000000ns

Separate these out, by defining a _timer_running() call that each
timer implements, and only define _timer_fd if we are compiling
with TIMERFD enabled.
2016-12-18 13:03:44 +00:00
886b4f755d dmstats: use better interval estimate for usleep() timer
Although the usleep() interval timer is not used if the Linux
TIMERFD interface is available it should still provide reasonably
good timing.

Instead of trying to estimate the error from the duration of the
last sleep, peg it to the start time of the program, and use the
value of  ((start_time - now) % interval) to correct the current
interval duration.

This always pulls us back into sync at the end of each interval,
rather than relying on trying to incrementally adjust the time
duration at each interval start.

This greatly reduces drift when the usleep() clock is used.
2016-12-18 13:03:44 +00:00
68ec42ebaf dmstats: improve tool help output and option coverage 2016-12-18 11:51:13 +00:00
4f9d901c71 man: fix 'dmstats create' formatting in dmstats.8.in 2016-12-18 10:23:12 +00:00
14be8c4fad man: fix 'dmstats list' option formatting in dmstats.8.in 2016-12-18 10:12:56 +00:00
25dd3988c3 man: fix 'dmstats <command>' formatting in dmstats.8.in 2016-12-18 10:12:45 +00:00
35791689ba libdm: use destination size as limit in dm_bit_copy()
The dm_bit_copy() macro uses the source (bs1) bitset size as the
limit for memcpy:

    memcpy((bs1) + 1, (bs2) + 1, ((*(bs1) / DM_BITS_PER_INT) + 1)..)

This is safe if the destination bitset is smaller than the source,
or if the two bitsets are of the same size.

With a destination that is larger (e.g. when resizing a bitmap to
add more capacity), the memcpy will overrun the source bitset and
set garbage bits in the destination.

There are nine uses of the macro currently (8 in libdm/regex, and
1 in daemons/cmirrord): in each case the two bitsets are always of
equal size so the behaviour is unchanged.

Fix the macro to use bs2's size to simplify resizing bitsets and
avoid the need for another copy macro.
2016-12-14 11:28:11 +00:00
0f98d5c2e6 cleanup: use exiting function
Reuse existing code and some indent change.
2016-12-14 11:41:42 +01:00
fecd043cca raid: split preserves local exlusive activation 2016-12-14 11:40:01 +01:00
77e09c3fb4 raid: activation with list
Commit 0690392040 revealed a problem
in raid metadata manipulation.

We do two operations in one table reload:
- raid leg/image extraction
- rename remaining raid legs

This should be made in separate steps. Otherwise we do an
uncorrectable table change on error path (leaving tables
for admin and dmsetup).

As a hotfix - restore the previous logic and use a single
new function _lv_update_and_reload_list which activates exclusively
extracted LVs on the list before resuming suspended raid LV.
This restore 'rename' functionality upon resume.

Also still preserve the 'origin_only' logic - although we know
it's not working properly for cluster and LV stacking.

Further fixes are needed.
2016-12-14 11:37:02 +01:00
4a05f83278 configure: just move new macro to right file
aclocal is regenerated while acinclude is permanent.
Move new macro to permanent file.
2016-12-13 22:49:59 +01:00
f4401fe351 libdm: ensure first extent is always counted
If FIEMAP returns a single extent after the first call, no extent
boundary is detected and the first extent is not counted by the
normal mechanism.

In this case, increment nr_extents at the same time the extent is
added to the region table, before returning.
2016-12-13 21:41:31 +00:00
fce7449d73 cleanup: remove wrapping function
backup is not 'tested' for success and also it should
actually happen just when command is finished.
We do not target to make backups with each inter-step
metadata change.
2016-12-13 22:07:52 +01:00
c7da16e5f1 cleanup: log message updates 2016-12-13 22:07:52 +01:00
a8f5e1f274 cleanup: more lv_is_ usage 2016-12-13 22:07:52 +01:00
47b96c3537 cleanup: allocate NAME_LEN size for lv name 2016-12-13 22:07:52 +01:00
d0fe3ec0c5 raid: avoid manipulation of segment status
RAID is LV property

TODO: only 2 flags are seg->status: PVMOVE & MERGING
At least the second one should be soon elimanted as again
we merge LV not a segment.
2016-12-13 22:07:52 +01:00
d1e398c474 segtype: check for seg type instead of status
RAID is LV property - which has single segment of raid type.
2016-12-13 22:07:52 +01:00
0690392040 raid: improve table reload sequence
This is another place for 'common' use pattern or
reload and activation of deleted devices.
(Moving the exclusive activation to _deactivate_and_remove_lvs()).

TODO: looks like halve of raid function is reloading
just 'origin' - and the other full LV.
2016-12-13 22:07:52 +01:00
7dff632c11 libdm: add min_num_bits to dm_bitset_parse_list()
It's useful to be able to specify a minimum number of bits for a
new bitmap parsed from a list, for e.g. to allow for expansing a
group without needing to copy/reallocate the bitmap.

Add a backwards compatible symbol for programs linked against old
versions of the library.
2016-12-13 21:02:18 +00:00
e8d966bc31 libdm: use dm_bit_get_last() in _stats_group_tag_fill()
Instead of iterating over all bits, use dm_bit_get_last() to find
the last set bit in the group bitmap.
2016-12-13 21:02:18 +00:00
5d1d65e735 libdm: add dm_bit_get_last()/dm_bit_get_prev()
It is sometimes convenient to iterate over the set bits in a dm
bitset in reverse order (from the highest set bit toward zero), or
to quickly find the last set bit.

Add dm_bit_get_last() and dm_bit_get_prev(), mirroring the existing
dm_bit_get_first() and dm_bit_get_next().

dm_bit_get_prev() uses __builtin_clz when available to efficiently
test the bitset in reverse.
2016-12-13 21:01:58 +00:00
107bc13db3 util: add clz() and use __builtin_clz() if available
Add a macro for the clz (count leading zeros) operation.

Use the GCC __builtin_clz() for clz() if it is available and fall
back to a shift based implementation on systems that do not set
HAVE___BUILTIN_CLZ.
2016-12-13 20:41:29 +00:00
83a9cd5258 configure: check for __builtin_clz() 2016-12-13 20:38:40 +00:00
930b0b4c9e libdm: fix start of file detection in _stats_map_extents() 2016-12-13 20:25:47 +00:00
eb65572217 libdm: break up _stats_get_extents_for_file()
Split out the loop that iterates over each batch of FIEMAP
extent data from the function that sets up and calls the ioctl
to reduce nesting and simplify local variable use:

  _stats_get_extents_for_file()
  ->  _stats_map_extents()

The _stats_map_extents() function is responsible for detecting
eof and extent boundaries and adding whole, allocated extents
to the file extent table for region creation.
2016-12-13 20:25:45 +00:00
ea9af3e290 libdm: fix dm_stats_foreach_group() macro 2016-12-13 20:01:00 +00:00
8e33972828 libdm: check for non-existent region_id values in groups
Check that all region_id values specified in a group bitmap are
actually present: although this should not normally happen when
using the dmstats tool, it is possible as a result of manual
changes (or bugs) for a group descriptor to contain one or more
group_id values that do not exist.

Check for this situation when reading group descriptors, warn
the user the user, and clear these bits in the bitmap when
formatting it for output.
2016-12-13 15:37:48 +00:00
99b6d82e2d libdm: fix segfault with invalid group descriptor
If a region has a a DMS_GROUP tag in aux_data where the first
region_id in the bitmap is not the same as the containing region,
dmstats will segfault:

  # '2' is never a valid group bitset list for region_id == 0
  # dmsetup message vg_hex/root 0 "@stats_set_aux 0 DMS_GROUP=img:2#"

  # dmsetup message vg_hex/root 0 "@stats_list"
  0: 45383680+16384 16384 dmstats DMS_GROUP=img:2#
  1: 46071808+32768 32768 dmstats -
  2: 47382528+16384 16384 dmstats -

  # dmstats list
  Segmentation fault (core dumped)

The crash will occur in some arbitrary dm_stats_get_* property
method - this happens while processing the 1st region_id in the
bitset, because the region is marked as grouped, but there is
no group bitmap present at dms->groups[2]->regions.

Fix this by detecting a mismatch between the expected region_id
and dm_bit_get_first() for the parsed bitset during
_parse_aux_data_group().
2016-12-13 14:37:41 +00:00
138e4336fd libdm: fix region overlap tests 2016-12-13 09:09:29 +00:00
93f420caf4 libdm: fix _stats_get_extents_for_file()
Handle files that contain multiple logical extents in a single
physical extent properly:

  - In FIEMAP terms a logical extent is a contiguous range of
    sectors in the file's address space.

  - One or more physically adjacent logical extents comprise a
    physical extent: these are the disk areas that will be mapped
    to regions.

  - An extent boundary occurs when the start sector of extent
    n+1 is not equal to (n.start + n.length).

This requires that we accumulate the length values of extents
returned by FIEMAP until a discontinuity is found (since each
struct fiemap_extent returned by FIEMAP only represents a single
logical extent, which may be contiguous with other logical
extents on-disk).

This avoids creating large numbers of regions for physically
adjacent (logical) extents and fixes the earlier behaviour which
would only map the first logical extent of the physical extent,
leaving gaps in the region table for these files.
2016-12-13 09:09:25 +00:00
87117c2b25 lvchange: allow a transiently failed RaidLV to be refreshed
Enhance commit 0b8bf73a63 to refresh the top-level LV correctly
in case of a clustered, remotely activated RaidLV.

Related: rhbz1399844
2016-12-12 22:08:47 +01:00
75ec7c8dee tests: update seg_size_pe
Default prepare_vg uses 512K - so update test accordingly
2016-12-12 11:51:50 +01:00
3dd6e2c7e1 tests: use prepare_vg more often 2016-12-12 11:22:41 +01:00
8c9c6ab660 tests: no left devices check for skipped test 2016-12-12 11:22:10 +01:00
48d33e5fb6 cov: use unsigned for single bit values
Avoid using signed int.
2016-12-12 11:21:42 +01:00
56e4e2ce2b tests: track leaked devices in tests
When test calls teardown, no devices created by test are expected
to be left in table. Trap such orphans and make the test fail.
2016-12-11 23:24:19 +01:00
273ccb1170 tests: remove unwanted exit
Exit seemes slipped in from local testing in:
eb6b2a11e3
2016-12-11 23:24:19 +01:00
b902fd08f6 tests: remove some leaking device
These tests leaks devices (known bugs).
Remove them via dmsetup.

TODO: fix actual commands
2016-12-11 23:24:19 +01:00
bcf59a1b18 tests: test should clean devices it has created
To be able to detect lvm2 command is not leaking some
'unexpected' device - remove all devices before
test exits by its own command so test teardown
now can check what was 'left' unexpectedly.
2016-12-11 23:24:19 +01:00
198f335139 tests: slower device
Some of test machines are too fast, slow raid syncing even more.
2016-12-11 23:24:19 +01:00
4a33e4c509 cov: declaration matching 2016-12-11 23:24:19 +01:00
b8c729efd0 cov: add internal error for impossible code path 2016-12-11 23:24:19 +01:00
794093722c debug: missing stack traces 2016-12-11 23:24:19 +01:00
dc7d3dd5ed cleanup: use NAME_LEN stack buffer
Using NAME_LEN we get at least easy max LV name size validation.
Also code gets more simple.
2016-12-11 23:24:19 +01:00
6cd68c55dd cleanup: reuse existing function
Call lv_update_and_reload implementation.
2016-12-11 23:24:19 +01:00
6f84d3c69c libdm: validate vsnprintf
Avoid using buffer when no output has been generated.
Missed in ee13f265f0.
2016-12-11 23:24:17 +01:00
3903f915f8 pvmove: fix activation order
For proper locking we need to gain lock first for mirror which
needs to be deactivated later to be working in cluster.
2016-12-11 23:22:36 +01:00
67f9e6b175 raid: avoid _ at end of name of extracted metadata LV
Do not generate @PREFIX@vg/LV1_rmeta_1_extracted_.
2016-12-11 23:20:51 +01:00
55ca8043d4 raid: optimize clearing of lvs
Activate whole list of metadata lvs first before clearing them.
(Similar to commit ada5733c56)

TODO: make this clearing in a single common function.
2016-12-11 23:19:41 +01:00
8831a541a8 raid: fix delete on clustered vg
For clustered VG ensure lock is grabbed first,
so later deactivation works.

TODO: fix tree to solve device removal automatically.
2016-12-11 23:18:22 +01:00
0c8369099b raid: fix raid1 to mirror conversion
Fix order of operation when converting raid1 into old mirror.
Before any later metadata modification are initiated prepare
mirror_log device with all clearing.
Then directly convert  raid1 into mirror with mirror_log.
This convertion now properly see as precommitted metadata
new 'mirror' and committed old 'raid' and is able to
preload all LVs.
2016-12-11 23:17:22 +01:00
31564834db mirror: add prepare_mirror_log
Function prepares new mirror log LV in-sync optionaly.
This is useful to have such device ready when converting
raid1 to mirror.
2016-12-11 23:16:16 +01:00
b9f9ce52ec test: add results/ to .gitignore 2016-12-10 18:00:25 +00:00
14c20ae217 lvmdbusd: add path.py to .gitignore 2016-12-10 17:59:07 +00:00
f9c9772a80 scripts: add systemd unit files to .gitignore
com.redhat.lvmdbus1.service
lvm2_lvmdbusd_systemd_red_hat.service

.gitignore
2016-12-10 17:58:10 +00:00
383683ffd3 scripts: add lvmdump.sh to .gitignore 2016-12-10 17:56:56 +00:00
b311122a56 libdm: fix filemap cleanup loop condition 2016-12-10 13:31:12 +00:00
d8ba8ee9ae libdm: use a private pool for filemap extent table
When mapping regions to a file descriptor, a temporary table of
extent descriptors is built using the dm_pool object building
interface.

Previously this use borrowed the dms->mem region and counter
table pool (since nothing can interleave with the allocation
while the caller is still in dm_stats_create_regions_from_fd()).

This turns out to be problematic for error recovery. When a
region creation operation fails partway through file mapping,
we need to roll back the set of already created regions and
this requires a listed handle: the dm_stats_list() will then
allocate from the same pool as the extents; we either have
to throw away valid list data, or leak the extent table, to
return the handle in a valid state.

Avoid this problem by creating a new, temporary mem pool in
_stats_create_file_regions() to hold the extent data, and
discarding it on exit from the function.
2016-12-10 13:31:12 +00:00
1de3e106c9 doc: add filemap creation fixes to WHATS_NEW_DM 2016-12-10 12:02:30 +00:00
2d1dbb9edd libdm: fix performance of failed filemap cleanup
While cleaning up the table of already created regions during a
failed dm_stats_create_regions_from_fd(), list the handle once,
and call _stats_delete_region() directly. This avoids sending a
@stats_list message for each region deleted, reducing runtime
from 6s to 0.7s when cleaning up ~250 out of ~10000 regions:

  # time dmstats create --filemap b.img
  device-mapper: message ioctl on (253:0) failed: Cannot allocate memory
  Failed to create region 246 of 309 at 9388032.
  Could not create regions from file /root/b.img
  << pauses here >>
  Command failed

  real	0m6.267s
  user	0m3.770s
  sys	0m2.487s

  # time dmstats create --filemap b.img
  device-mapper: message ioctl on (253:0) failed: Cannot allocate memory
  Failed to create region 246 of 309 at 9388032.
  Could not create regions from file /root/b.img
  Command failed

  real	0m0.716s
  user	0m0.034s
  sys	0m0.581s

Testing the error path requires region creation to start to
fail part way through the operation (in order to have regions
to clean up): the simplest way is to ensure the system is
close to the kernel limit of 1/4 RAM or 1/2 vmalloc space
consumed by dmstats data.
2016-12-10 11:59:16 +00:00
97c4490cc5 libdm: split off internal _stats_delete_region()
Split dm_stats_delete_region() so that internal callers can manage
the handle state themselves.

dm_stats_delete_region() now just handles checking the state of the
handle, reporting validation errors, and calling dm_stats_list() if
necessary, before calling _stats_delete_region().

The new _stats_delete_region() function performs the actual group
member removal and region deletion, and requires a fully listed
handle to operate.

Callers that repeatedly delete regions can use a single listed
handle for many operations on the same device, avoiding one
message ioctl per region deleted: since @stats_list with many
regions is expensive, this yields large runtime improvements.
2016-12-10 11:57:14 +00:00
c459f23565 lvmetad: fix segfault in daemon_reply_simple
missing NULL termination
2016-12-09 15:22:30 -06:00
30ad254d84 libdm: use correct region_id when cleaning up a failed filemap
If we fail to create a region during dm_stats_create_regions_from_fd(),
we must remove all regions that were created to do this to date. This
needs to loop over the table of region_id values that were populated
by _stats_create_file_regions() before the error.

The code for this failure case in the out_remove branch incorrectly
uses the table index as the region_id:

    for (--i; i != DM_STATS_REGION_NOT_PRESENT; i--) {
            if (!dm_stats_delete_region(dms, i))
                    log_error("Could not delete region " FMTu64 ".", i);
    }

This causes the cleanup code to delete a completely unrelated set
of regions (since the index here will always be nr_regions..0).

Fix it to pass the actual region_id stored in regions[i] instead.
2016-12-09 16:04:13 +00:00
7fd2fa22dd libdm-stats: clear dms->groups in _stats_groups_destroy() 2016-12-09 16:04:13 +00:00
cb8c04760f libdm-stats: clear dms->regions in _stats_regions_destroy() 2016-12-09 16:04:13 +00:00
900d203586 tests: fix missing exclusive activation
For cluster conversion  LV for caching needs to be activated
exclusively.
2016-12-09 15:15:02 +01:00
c5aeb21015 cleanup: zero baton in struct initilizer 2016-12-09 15:15:02 +01:00
f9c6c115d3 cleanup: easier code for raid plugin
Set bits only when then were not yet assigned.
2016-12-09 15:15:02 +01:00
15e4ab3e93 cleanup: messages in raid
Use display_lvname and add 'dots'.
Add some missing WARNING and log_debug_metadata.
2016-12-09 15:15:02 +01:00
6dd0bd0255 libdm-stats: fix dm_stats_delete_region() performance
Fix a silly bug in dm_stats_delete_region() that hugely inflates
runtimes when deleting a large number of regions.

For ~50,000 regions this change reduces the runtime from 98s to
6s on my test systems (a ~93% reduction).

The bug exists because dm_stats_delete_region() applies a truth
test to the return value of dm_stats_get_nr_areas(); this is
never correct usage - it will walk the entire region table and
calculate area counts for each region (which is roughly O(n^2)
in the number of regions, as dm_stats_delete_region() is being
called inside a region walk).

Although the individual area calculation is not that costly,
uselessly running anything 2,500,000,000 times over gets a bit
slow.

A much cheaper test (which is always true if the areas check is
true) is to just test dm_stats_get_nr_regions() or dms->regions;
if either is true it implies at least one area exists.

Old:

 Performance counter stats for 'dmstats delete --allregions --alldevices':

      98117.791458      task-clock (msec)         #    1.000 CPUs utilized
               127      context-switches          #    0.001 K/sec
                 3      cpu-migrations            #    0.000 K/sec
             6,631      page-faults               #    0.068 K/sec
   307,711,724,562      cycles                    #    3.136 GHz
   544,762,959,577      instructions              #    1.77  insn per cycle
    84,287,824,115      branches                  #  859.047 M/sec
         2,538,875      branch-misses             #    0.00% of all branches

      98.119578733 seconds time elapsed

New:

 Performance counter stats for 'dmstats delete --allregions --alldevices':

       6427.251074      task-clock (msec)         #    1.000 CPUs utilized
                 6      context-switches          #    0.001 K/sec
                 0      cpu-migrations            #    0.000 K/sec
             6,634      page-faults               #    0.001 M/sec
    21,613,018,724      cycles                    #    3.363 GHz
     3,794,755,445      instructions              #    0.18  insn per cycle
       852,974,026      branches                  #  132.712 M/sec
           808,625      branch-misses             #    0.09% of all branches

       6.428953647 seconds time elapsed
2016-12-09 10:55:39 +00:00
0ce9ae3cda tests: more snaps
Check lvs reports 'origin' not openned.
2016-12-05 17:12:42 +01:00
3f6ade4b0d tests: apostrof 2016-12-05 17:12:42 +01:00
022d3af068 tests: check we recognize broken table entry
One (initial) test to recognize we see a mismatching
table entry for cache LV.
2016-12-05 17:12:42 +01:00
36b211b464 debug: add missing backtrace 2016-12-05 17:12:42 +01:00
3331199cc9 cleanup: simplier code 2016-12-05 17:12:42 +01:00
81ef4eb4f8 cleanup: indent and messsages updates 2016-12-05 17:12:42 +01:00
69c79ed2f4 cleanup: simplify code
Drop unneeded assignemnt in structs (var is set by called function).
2016-12-05 17:12:42 +01:00
114f7e6285 dev_manager: use setup_task_run for mknod
Simplify info run for use only for INFO & STATUS.
Drop handling MKNODES within _info_run() call
and use more advanced _setup_task_run() directly.

This allows to further simplify _info_run().
2016-12-05 17:12:39 +01:00
5163b8f697 dev_manager: extend setup_task
Integrate also query for inactive table and
handle dm_task_run() and dm_task_get_info()
(thus switching to setup_task_run)

Add one exception case for DM_DEVICE_TARGET_MSG.

This allows further shortening and simplification of all
other users of this function.
2016-12-05 17:11:49 +01:00
e2c7e0ad11 activation: optimize away lv_has_target_type
It's actually not needed to call extra lv_has_target_type() to detect
snapshot merge is in progress - decode this right during status
capturing and save even few extra ioctl calls.
2016-12-05 17:10:14 +01:00
6fd20be629 activation: lv_info_with_seg_status API change
Drop LV from passed API arg - it's always segment being checked.
Also use_layer is now in full control of lv_info_with_seg_status().
It decides which device needs to be checked to get 'the most info'.

TODO: future version should be able to expose status from
2016-12-05 17:09:47 +01:00
ed93f0973a activation: lv_info_with_seg_status unify status selection
Start moving selection of status taken for a LV into a single place.
The logic for showing info & status has been spread over multiple
places and were doing too complex decision going agains each other.

Unify selection of status of origin & cow scanned device.

TODO: in future we want to grab status for LV and layered LV and have
both statuses present for display - i.e. when 'old snapshot'
of thinLV is takes and there is ongoing merge - at some moment
we are not capable to show all needed info.
2016-12-05 17:09:13 +01:00
0089201588 cleanup: swap test order
Check for lv != lvseg->lv.
Make the logic of following patches look better and easier to read.
2016-12-05 17:05:23 +01:00
5ba2d58d28 activation: improve error handling for status reading
When lvm2 wants to see a status, it needs to validate,
segment for status reading is matching whan lvm2 expects in
metadata.

Also ensure status failure will not cause '0' from info reading
when actual info was collected properly.
Failure in 'status' reading is considered to be
a 'log_warn()' event only.
2016-12-05 17:05:17 +01:00
4a4b22e114 activation: status check switch to warn
When we can't parse status, switch to warning as this is not
considered an errornous case.  LVS is not supposed to return
error status code when  device is not what it's been expected to
be - but it should be WARNING a user there is something unexpected.
2016-12-05 17:04:24 +01:00
325c2c5687 lv: always check status type
Always validate status type has an expected value,
before accessing status struct members.
2016-12-05 17:03:38 +01:00
6a450952ad striped: implement compatible target name
Linear is handled by striped target.
2016-12-05 17:02:01 +01:00
254f73e3ef snapshot: reporting uses statusinfo
Convert lvs -o lv_merge_failed,lv_snapshot_invalid to use
lv_info_and_status function.

This makes it equal to attr value showing this info
(as they were different since they were derived from
different data set and different logic as well).

Also saves couple extra ioctl that were needed to obtain this info.
2016-12-05 17:01:15 +01:00
07f9889b53 report: order fields by type for field defintions in columns.h
When displaying <reporting_command> -o help, we'd like to have fields
grouped nicely, not starting having groups interleaved as it was before.
The code that displays the help output for fields takes the order as
written in columns.h file - this caused output like:

$ lvs -o help

Logical Volume Fields
---------------------
...field list...

Logical Volume Device Info and Status Combined Fields
-----------------------------------------------------
...field list...

Logical Volume Fields
---------------------
...field list...

Logical Volume Device Status Fields
-----------------------------------
...field list...

Logical Volume Fields
---------------------
...field list...

Instead, let's have it without groups interleaved which may be
a bit confusing, so:

Logical Volume Fields
---------------------
...field list...

Logical Volume Device Status Fields
-----------------------------------
...field list...

Logical Volume Device Info and Status Combined Fields
-----------------------------------------------------
...field list...

..and so on.
2016-12-01 14:55:29 +01:00
bb5eb324e3 post-release 2016-11-30 23:21:11 +00:00
57e24817b7 pre-release 2016-11-30 23:14:34 +00:00
745250073c raid: fix sync percent on large RaidLVs
Resolves: rhbz1400301
2016-12-01 00:00:02 +01:00
c9848bb7ea lvmdbusd: Only allow 0..N for --blackboxsize argument 2016-11-30 16:47:39 -06:00
c0a508cfab WHATS_NEW: New argument --blackboxsize 2016-11-30 16:47:31 -06:00
5da10fda4c WHATS_NEW: Allow a transiently failed RaidLV to be refreshed 2016-11-30 23:17:21 +01:00
ad7fd775f2 lvmdbustest.py: Rename env test variable
Use LVM_DBUSD_TEST_MODE env variable to customize what we test.
Default is the same where we try to test all combinations of all
modes.  Renamed to make it consistent with the other env variables
that are used in the unit test.
2016-11-30 15:59:06 -06:00
ea2eb2df97 lvmdbustest.py: Remove redundant import 2016-11-30 15:59:06 -06:00
b75d1a591c lvmdbustest.py: Remove outdated TODOs
- We check that all properties match the introspection data.  We
don't verify values for every property as only lvm knows what they
should be.

- We are testing vg.Move
2016-11-30 15:59:06 -06:00
bb845cab76 lvmdbustest.py: Re-enable test_vg_uuid_gen
This looks to be working now, not sure when it was resolved.
2016-11-30 15:59:06 -06:00
53ef496719 lvmdbusd: Emit signal on Job completion
Added a properties changed signal on the job dbus object so that client
can wait for a signal that the job is complete instead of polling or
blocking on the wait method.
2016-11-30 15:59:06 -06:00
1d52090953 lvmdbusd: Remove TODO on concurrent access to properties
As the code now uses a single thread to handle all changes to the
dbus model we no longer need to handle this potential race
condition.
2016-11-30 15:59:06 -06:00
37f05ccab1 lvmdbusd: Supress protected member access warning
We want _run to be protected so that users outside of the class
don't mistakenly use it.  It's for internal use only.
2016-11-30 15:59:06 -06:00
3bc69cb23c lvmdbusd: Add --blackboxsize command line argument
Allows the user to override the number of commands that get dumped
to the log when we encounter a lvm error.  Also useful during
development when you don't want to see the blackbox output.
2016-11-30 15:59:06 -06:00
b0757ac96e lvmdbusd: Remove unused variable
This variable has been un-used for a long time.
2016-11-30 15:59:06 -06:00
0b8bf73a63 lvchange: allow a transiently failed RaidLV to be refreshed
In case any SubLV of a RaidLV transiently fails, it needs
two "lvchange --refresh RaidLV" runs to get it to fully
operational mode again.  Reason being, that lvm reloads all
targets for the RaidLV tree but doesn't resume the SubLVs
until after the whole tree has been reloaded in the first
refresh run.  Thus the live mapping table of the SubLVs
still point to an "error" mapping and the dm-raid target
can't retrieve any superblock from the MetaLV(s) in processing
the constructor during this preload thus not discovering the
again accessible SubLVs.  In the second run, the SubLV targets
map proper (meta)data, hence the constructor discovers those
fine now.

Solve by resuming the SubLVs of the RaidLV before
preloading the respective top-level RaidLV target.

Resolves: rhbz1399844
2016-11-30 22:57:54 +01:00
58f4d98af1 lvmdbusd: Remove debug log_error 2016-11-29 16:50:30 -06:00
617a819abc lvmdbusd: WS fix 2016-11-29 16:50:30 -06:00
d882edb32d lvmdbusd: Simplfy reading streams
Remove redundant code and make code paths the same for all streams.
2016-11-29 16:50:30 -06:00
25b5413f89 lvmdbusd: Make lvm shell read more robust
Make sure JSON is correct before we stop trying to read.
2016-11-29 16:50:30 -06:00
b0bda09005 tests: ensure there is dbus config file
Copy lvmdbusd.profile to lib as installed place.
Use  TESTOLDPWD and avoid add new 'same' variable test_data_dir.
2016-11-26 00:22:38 +01:00
4a59cfaa1d makefiles: drop file source and indent 2016-11-26 00:22:38 +01:00
b7cf7b1d3a gcc: quiet warning about unused function
Once this function will need to be used, git revert.
2016-11-25 15:02:36 +01:00
108d9a63fd cleanup: indent 2016-11-25 15:01:28 +01:00
c10028dd8e cleanup: add missing WARNING into log_warn 2016-11-25 15:01:27 +01:00
1a4f13eb6e cleanup: add some dots and use display_lvname
Just some more VG/LV printing.
2016-11-25 15:01:27 +01:00
1d58074d9f debug: more stacktrace corrections
Continue previous patch dropping some unneeded stack traces
after printed log_error/warn messages.
2016-11-25 14:58:28 +01:00
2ad66b4e7b scripts: fix comment about blk-availability init script
The original comment got there as copy-paste error and it wasn't edited
properly for blk-availability.
2016-11-25 11:30:55 +01:00
064e24bc1e lvmdbusd: Only read whats buffered
When reading data from stdout & stderr we were reading until the
reading until we got None back which really isn't needed as the
read will return everything that is available.
2016-11-23 18:16:11 -06:00
a7404b5b83 debug: stack tracing corrections 2016-11-23 17:55:03 +01:00
4f39255dca cleanup: indent changes 2016-11-23 17:55:03 +01:00
ae95937af4 cleanup: defines 2016-11-23 17:55:03 +01:00
d05668c587 cleanup: use predefined macro for tmp image name 2016-11-23 17:55:03 +01:00
c621bc3d36 cleanup: deactivate has builtin check for active lv 2016-11-23 17:55:03 +01:00
74923c213f cleanup: add doc for raid status states
Show possible values for raid fields user may get ATM.
2016-11-23 17:55:03 +01:00
e38678be3f cleanup: single LVM_SYSTEM_DIR string 2016-11-23 17:55:03 +01:00
cc3895623c cleanup: hide gcc warning 2016-11-23 17:55:03 +01:00
8a4dfe6ce7 cleanup: use lv_update_and_reload
Avoid code duplication and use exiting commonly used
lv_update_and_reload() function.

There is still one place left where mirror is doing strange
double suspend call - needs there more thinking what's wrong with
that code.
2016-11-23 17:53:44 +01:00
a04b4bb89e cleanup: make this error an internal error
We shouldn't get here with wrong type.
2016-11-23 17:48:01 +01:00
5fd5cfe061 cleanup: use display_lvname and msg cleanup
Use display_lvname in tracing messages.
Add some missing 'dots' to messages.
2016-11-23 17:48:01 +01:00
0ad95b77d0 mirror: preserve MIRRORED status for temporara image
When lvconvert adds a new leg - it's doing it free 'temporary' image
layer - however this temporary 'internal' mirror is also MIRRORED LV.
But the status bit was not properly transfered through layer.
2016-11-23 17:47:58 +01:00
851095a6af raid: lvconvert uses transient check for raid
Also check if the raid status isn't teling us there is something wrong
with any raid image device.
2016-11-23 17:46:50 +01:00
23809379ba raid: implement transient status check
Take into acount reported state from 'raid' targets.
When raid leg is marked with 'D' - take it as missing leg.
2016-11-23 17:45:44 +01:00
2315743dd3 man: remove duplicate paragraph about selection criteria from lvm(8) man page
The paragraph about selection criteria together with all the related
context is now documented in lvmreport(7) man page completely.
2016-11-22 13:20:52 +01:00
0bbf631349 lvmdbusd: Remove extraneous finally
The print statement is incorrect.
2016-11-17 13:59:39 -06:00
3b4c5a2151 lvmdbusd: Fix source documentation 2016-11-17 13:58:17 -06:00
3a6c78e22a lvmdbusd: cmdhandler.py, fix imports
Use the correct py3 syntax for handling imports.  Also use print instead
of log_debug which in this context will produce no output.
2016-11-17 13:57:44 -06:00
19a0bf9df6 lvmdbusd: Remove debug JSON file 2016-11-17 11:45:11 -06:00
bd47b202fb lvmdbustest: Reduce dbus object churn
Instead of creating a new dbus object each time we get an interface object
we will use the same one.
2016-11-17 11:35:16 -06:00
bfedeb7481 lvmdbustest: Move std_err_print to testlib
So we can re-use it in the testlib too.
2016-11-17 11:35:16 -06:00
99806ec7ec lvmdbusd: Place Manager.UseLvmShell request on queue
We need to acquire a lock which can block us which in turn causes
the dbus request handling to block as well.  Place the request on
the work queue instead.
2016-11-17 11:35:16 -06:00
df92d330aa lvmdbusd: Extra report FD read on no data
Our expectation was that when using the lvm shell that when the lvm prompt
was read from stdout, that all other ouput had been written and flushed.
However, this doesn't appear to be the case.  Add extra read passes to
retrieve delayed report data.
2016-11-17 11:35:16 -06:00
a1805cf336 lvmdbusd: Bubble up invalid JSON
If we get invalid JSON, lets bubble that up to the user.
2016-11-17 11:35:16 -06:00
61f6be7d2b lvmdbustest.py: Reduce test client introspection calls
The default dbus python library mode of operation is to leverage
introspection.  However, this introspection data isn't accessible
for users of the library and they have to specifically retrieve
the introspection data too. This resulted in many introspection
calls being made.  This change eliminates introspection calls if
we are testing multiple concurrent test clients.  If it's a single
client we will leverage a reduced amount of introspection data to
verify the introspection data is correct.  Typically clients don't
leverage introspection data nearly as much as this test client.
2016-11-17 11:35:16 -06:00
4f1171466f lvmdbusd: Remove un-used import 2016-11-17 11:35:16 -06:00
2fbb90e403 lvmdbusd: WS corrections
Fix mixed spaces & tabs and other ws issues.
2016-11-17 11:35:16 -06:00
dcdef9647b lvmdbusd: Add cfg.load to pv remove
The global dbus state does not match lvm with simply removing the pv
dbus object.
2016-11-17 11:35:16 -06:00
24fd1dd7a3 lvmdbusd: _lv_create, simplify return path 2016-11-17 11:35:16 -06:00
cd28717f24 lvmdbustest.py: Support concurrent test runs
The env variable LVM_DBUSD_PV_DEVICE_LIST when present and filled in
with at least 4 physical devices will run concurrently with other
instances running as long as they specify different devices in their
env variable.

When the env variable is not present the test runs as it did before.
2016-11-17 11:35:16 -06:00
72a943f720 lvmdbusd: Long running operations use own thread
Anything that ends up using polld will be done in a unique thread
so that we don't hold off other operations from running concurrently.
2016-11-17 11:35:16 -06:00
fa444906bb lvmdbusd: Use one thread to fetch state updates
In preparation to have more than one thread issuing commands to lvm
at the same time we need to serialize updates to the dbus state and
retrieving the global lvm state.  To achieve this we have one thread
handling this with a thread safe queue taking and coalescing requests.
2016-11-17 11:35:16 -06:00
affe2cebf5 lvmdbus: Make bus name configurable
Add env LVM_DBUS_NAME to change what the bus name is.
2016-11-17 11:35:16 -06:00
560229178c lvmdbustest.py: Remove raid4 use
Looks like this isn't support across versions.  Need to add functionality
to service to return the supported segment types, so we only use the
supported ones.
2016-11-17 11:35:16 -06:00
2a86f54b09 libdm: separate dm_stats_populate() error cases
There are two possible errors in _dm_stats_populate_region():

  * No region struct in dms->regions[region_id]
  * Failure to parse data from @stats_print

These have very different causes: the first occurs where a client
program is populating one region at a time (region_id is a single
region identifier), and has not previously called dm_stats_list()
to dimension the region tables; this is an API usage error.

The second occurs when either we read unparseable data from the
kernel (kernel bug), or where various resource allocations fail.

Separate these two cases out and log separate messages for each
(allocation failures in the path already have their own distinct
message), since the "failed to parse.." message in the un-listed
handle case is confusing and misleading.
2016-11-17 11:39:43 +00:00
6de05cf5f5 raid: Remove fixed FIXME 2016-11-15 20:45:55 +00:00
cd0736a945 dbus: also recognize error state for missing service that comes from original D-Bus 2016-11-15 10:09:11 +01:00
68d6d342f8 dbus: only log msg as debug if lvm2-lvmdbusd unit missing for D-Bus notification
Do not emit warning message but only log debug message if
lvm2-lvmdbusd.service unit is missing and at the same time
we have global/notify_dbus=1 (which is used by default if we
configured sources with "--enable-notify-dbus"). We don't want
hard dependency between LVM2 and lvmdbusd so it's enough to log
only debug message in this case.
2016-11-14 14:53:19 +01:00
e7da8e7e1f tests: fix checking for pvmove LV
Use consitently egrep.

TODO: make probably aux func
2016-11-14 12:55:43 +01:00
a7691cdebb cleanup: debug trace and indent change 2016-11-11 16:58:20 +01:00
6db5b91231 cleanup: avoid using double __ in extracted image name 2016-11-11 16:58:20 +01:00
1bdcb01f63 cleanup: add dots to debug messages 2016-11-11 16:58:20 +01:00
b38564b8dc tests: do not set zero interval in aux lvm.conf
0 interval leads as of now to a busy loop with lvmetad and command.

Avoid testing this patological case.

TODO: Code should possibly translate zero interval into some small
sleep. With lvmpolld it's already 1/10s
2016-11-11 16:58:20 +01:00
de3d054f78 tests: avoid using polling 2016-11-11 16:58:20 +01:00
4a2250f9ce tests: update make targets
Add  new targets:

make check_lvmpolld
make check_cluster_lvmpolld
make check_lvmetad_lvmpolld
make check_all_lvmpolld

So check_lvmetad runs only base lvmetad test - to much
logic of remaining targets.

Previous behavior is available via  check_all_lvmpolld.
2016-11-11 16:58:20 +01:00
d8fc4d093e conf: support zero for missing_stripe_filler
Make it easier to replace missing segments with 'zero' returning
target - otherwise user would have to create some extra target
to provide zeros as /dev/zero can't be used (not a block device).

Also break code loop when segment is found and make it an INTERNAL_ERROR
where it's missing.
2016-11-11 16:58:16 +01:00
e54cce245f cleanup: skip checking for just assigned string
When 'stripe_filler' has been just set to 'error',
do not check it again for not being 'error'.
2016-11-11 16:52:24 +01:00
59b29716e5 lvconvert: repair accepts interval and background
For mirror and raid we expose --interval and --background on
command line (instead of using just always using compiled-in defaults).
2016-11-11 16:51:33 +01:00
f8b3b0bc9a lvconvert: Introduce enum to separate cases.
Start to separate out the different things that lvconvert does by using
an enum to identify 12 distinct cases.
2016-11-11 00:27:01 +00:00
b11f4f93d7 dmsetup: [v2] return 0 for [--]{version,help}
Leverage 0b1c796420 to cope with "dmsetup SubCommand --{help,version}"
and bail out directly when _report_init() fails.

Related: rhbz1393692
2016-11-10 18:09:37 +01:00
0b1c796420 dmsetup: return 0 for [--]{version,help}
dmsetup regressed returning 1 when properly processing
version or help subcommands.

Resolves: rhbz1393692
2016-11-10 17:03:04 +01:00
c1862ea84c tests: for repair we need neewer version
Older cache targets were not able to report write failures.
2016-11-08 16:01:35 +01:00
2ec3e7dca8 tests: test raid0_meta type
Enable testing of raid0_meta type.
Also slow down devices a bit more.
2016-11-08 16:01:35 +01:00
ada5733c56 raid: faster rmeta clearing
Instead of clearing multiple rmeta device with sequential activation
process and waiting for udev for every _rmeta device separately,
activate all _rmeta devices first and then clear them and deactivate
afterwards.

Also update some tracing messages.

When anyhing goes wrong during clearing process, always try to
deactivate as much _rmeta devices as possible before fail.
2016-11-08 16:00:14 +01:00
9e03fc3c2a post-release 2016-11-05 01:14:06 +00:00
eed708dbd9 pre-release 2016-11-05 01:03:32 +00:00
6dce0e9489 tests: Disable 3-leg raid1 pre-sync repair attempt
Test fails as it doesn't ensure device isn't already in sync.
2016-11-04 00:23:08 +00:00
461d340bd7 lvmdbusd: Remove the periodic timer task
This code is no longer needed because the back ground task has been
removed.  Will add back if we change the design and end up utilizing
multiple worker threads.
2016-11-03 18:38:10 -05:00
ee0c9e7b23 lvmdbusd: Take out background thread
There is no reason to create another background task when the task that
created it is going to block waiting for it to finish.  Instead we will
just execute the logic in the worker thread that is servicing the worker
queue.
2016-11-03 18:29:06 -05:00
a9ee86ccf2 dmeventd: provide message context
Show device name with printed message.
Also use different level for printing error message and
standard informational message.
2016-11-03 17:49:07 +01:00
4e26024add cleanup: use WARNING prefix for log_warn
Use capital WARNING prefix for log_warn() messages.
2016-11-03 17:49:07 +01:00
0d95082aa9 cleanup: remove goto
Move goto path into 'if()' branch.
2016-11-03 17:49:07 +01:00
9cbe4c1af9 log_info to log_very_verbose
Translate log_info() into log_very_verbose() which is macro
supposed to be used by our code.

log_info() is internal macro with eventually some 'symbolic' meaning
in syslogging daemons.
2016-11-03 17:49:07 +01:00
cc19cc07f7 log_info to log_warn
Switch to log_warn level when we are reporting these message.
2016-11-03 17:49:07 +01:00
e3775173b4 cleanup: log_info to log_error
Switch to more appropriate logging level.
2016-11-03 17:49:07 +01:00
ee13f265f0 libdm: use dm_log_with_errno always
Instead of compiling 2 log call for 2 different logging functions,
and runtime decide which version to use - use only 'newer' function
and when user sets his own OLD dm_log logging translate it runtime
for old arg list set.

The positive part is - we get shorter generated library,
on the negative part this translation means, we always have evaluate
all args and print the message into local on stack buffer, before
we can pass this buffer to the users' logging function with proper
expected parameters (and such function may later decide to discard
logging based on message level so whole printing was unnecessary).
2016-11-03 17:49:07 +01:00
221d8ff2a4 tests: check that pvscan cannot activate exported VG 2016-11-03 11:43:37 -05:00
28b210f4fa cleanup: add 'static' for local struct 2016-11-03 12:43:09 +01:00
1db4b81d5a cleanup: drop unused attribute
In this function we pass args through so make the function
header look the same as with _default_log().
2016-11-03 12:43:09 +01:00
4b4d19e3aa dmeventd: separate dm and dmeventd logging
Ensure different logging function for dmeventd.c logging
and dm and lvm library.

We can recognize we want to show every log_info() and
log_notice() message from dmeventd.c code while not
exposing those from libdm/libdevmapper-event

Also switch to use log with errno - it's not changing
anything and doesn't bring any more features yet to dmeventd
logging but we just properly pass dm_errno_or_class properly
through the whole code stack for possible future use
(i.e. support of class logging for dmeventd).
2016-11-03 12:43:09 +01:00
cd468b6218 dmeventd: debug only subsystemd with # sign
Reword the logging logic and try to restore previous logging
behavior for 'standalone' running daemon while preserving
debuggable feautures it has gained.

So actual rules:

dmeventd without any '-d' option will syslog all messages
from dmeventd.c it dmeventd plugins.

log_notice()==log_verbose()
log_info()==log_very_verbose()
But to show also log_debug() used has to give '-ddd'.

When user specified '-d, -dd, -ddd, -dddd' it
will also enable tracing of messages from libdm & lib
executed code - which is mainly useful for testing
i.e.: 'dmeventd -fldddd'
2016-11-03 12:43:09 +01:00
33dd1f7747 dmeventd: abort on internal error
Provide same support for DM_ABORT_ON_INTERNAL_ERRORS we do have
with default libdm logging  as  dmeventd is libdm based tool.
2016-11-03 12:43:09 +01:00
e50d434a35 libdm: report logging with errno as changed default
When user changes logging with 'dm_log_with_errno_init()'
also report this as non default dm logging.
2016-11-03 12:43:09 +01:00
6af26273cb logging: add more log macros
Introduce macros:

log_level(), log_stderr(), log_once(), log_bypass_report()

For easier and more consisten way how to 'decoder' bits
of info from passed 'level'.

This patch fixes potential problem when 'level' of message
might not have always masked right bits.
2016-11-03 12:43:09 +01:00
96118a2508 lvmdbusd: Stop using threads for job wait
Instead of creating a thread to handle the case where a client
is calling job.Wait, we will utilize a timer.  This significantly
reduces the number of threads that get created and destroyed while
the service is running.
2016-11-02 16:39:13 -05:00
95abadd13c lvmdbusd: main.py: change debug msg text 2016-11-02 16:39:13 -05:00
60de09b00c lvmdbusd: Don't use dbus lib in worker thread
Simplify the code paths so that we don't utilize the dbus library code
when we are in worker thread context.

ref. https://bugs.freedesktop.org/show_bug.cgi?id=98521
2016-11-02 16:39:03 -05:00
38dd79307a lvmdbusd: Execute load in main thread
We will fetch the lvm state in non-main thread and only process the new
data with the main thread to prevent hanging the main thread event loop.

ref. https://bugs.freedesktop.org/show_bug.cgi?id=98521
2016-11-02 16:38:49 -05:00
24803bbaad lvmdbusd: Return results in main thread
Also introduce some additional new code to execute code other code
in main thread too.

ref. https://bugs.freedesktop.org/show_bug.cgi?id=98521
2016-11-02 16:38:00 -05:00
c8e8439b3d lvmdbusd: Use timer instead of thread
We had a thread sitting around for cleaning up other processes, changed to
a periodic timer task.
2016-11-02 16:35:45 -05:00
68e7d34965 pvscan: fix autoactivation of exported VG
pvscan --cache -aay was activating LVs in exported VGs
when it should not.

It appears that this was a regression from commit 9b640c3684
"pvscan: use process_each_vg for autoactivate".
2016-11-02 16:29:52 -05:00
4585785613 blkdeactivate: deactivate dev stack if dev on top already unmounted
If blkdeactivate finds out that the device on top of device stack
is already unmounted, it still proceeds with device stack deactivation
underneath now.

This situation can happen if blkdeactivate is started and the mount
point is unmounted in parallel by chance (so when blkdeactivate
gets the the actual umount call, the device is not mounted anymore).
Before, the blkdeactivate added such device to skip list which caused
all the stack underneath to be skipped too on deactivation. Now, we
proceed just as if blkdeactivate did the umount itself.

For example, in the example below, the vg-lvol0 is mounted on /mnt/test
when blkdeactivate is called, but it gets unmounted in parallel later
on when blkdeactivate gets to the actual umount call.

Before this patch (vg-lvol0 underneath not deactivated):

  $ blkdeactivate -u
  Deactivating block devices:
    [UMOUNT]: unmounting vg-lvol0 (dm-2) mounted on /mnt/test... skipping

With this patch applied (vg-lvol0 underneath still deactivated):

  $ blkdeactivate -u
  Deactivating block devices:
    [UMOUNT]: unmounting vg-lvol0 (dm-2) mounted on /mnt/test... already unmounted
    [LVM]: deactivating Logical Volume vg/lvol0... done
2016-11-01 16:52:51 +01:00
a9651adc84 test: add raid4 checks to respective tests
Add missing checks for valid raid4 mapping to tests.
2016-10-28 21:54:10 +02:00
e611f82a11 lvconvert: fix raid repair regression
Limit prevention to raid1 as intended with commit 8270ff5702.

Related to rhbz1311765
2016-10-28 21:45:00 +02:00
8270ff5702 lvconvert: prevent non-synced raid1 primary leg repair
(Automatic) repair may not be allowed during the initial sync of an upconverted
linear LV, because the data on the failing, primary leg hasn't been completely
synchronized to the N-1 other legs of the raid1 LV (replacing failed legs during
repair involves discontinuing access to any replaced legs data, thus preventing
data recovery on the primary leg e.g. via dd_rescue).

Even though repair would not cause data loss when adding legs to a fully synced
raid1 LV, we don't have information yet defining this state yet (e.g. a raid1
LV flag telling the fully synchronized status before any legs were added),
hence can't automatically decide to allow to repair.

If nonetheless a repair on a non-synced raid1 LVs is intended, the "--force"
option has to be provided.

Resolves: rhbz1311765
2016-10-28 15:55:10 +02:00
e118b65d65 lvconvert: check for supported raid0/raid4 segtypes
Validate kernel support for raid0/raid4 on given and
requested segtype before requesting conversions on them.

Because raid10 wasn't present in old RAID targets, add
the same validation to be prepared once we support them.
2016-10-27 16:44:32 +02:00
61ae07966d lvconvert-raid-takeover.sh: fix test 2016-10-27 16:38:15 +02:00
ff05ed7afd lvchange/vgchange/lvconvert: prevent raid4 creation/activation/conversion on non-supporting raid targets
Check for dm-raid target version with non-standard raid4 mapping expecting the dedicated
parity device in the last rather than the first slot and prohibit to create, activate or
convert to such LVs from striped/raid0* or vice-versa in order to avoid data corruption.

Add related tests to lvconvert-raid-takeover.sh

Resolves: rhbz1388962
2016-10-27 11:42:07 +02:00
e84f527cd3 lvconvert: revert to only letting raid4 through to lv_raid_convert()
Commit de78e8eae7 allowed to let any raid layout through
which we want to avoid until further validation cleanups.

Related to rhbz1386184
2016-10-26 17:54:19 +02:00
0468f5da6d raid_manip: fix typo
Related to rhbz1386184
2016-10-26 17:53:55 +02:00
021715e897 dmsetup: remove stray '\n' in delete log message 2016-10-24 17:21:35 +01:00
5eda393488 dmsetup: obey --programid when deleting regions 2016-10-24 17:21:18 +01:00
de78e8eae7 lvconvert: position dedicated parity device in raid4 conversions porperly
On conversions between striped/raid0* and raid4, the kernel expects
the dedicated raid4 parity SubLVs in the first segment area rather than
in the last it's been allocated to, thus the data mapping ain't proper.

Enhance lvconvert (lib/metadata/raid_manip.c) to shift the dedicated
parity SubLVs on conversions from striped/raid0* to raid4 and vice-versa.

In case of raid0_meta -> raid4 where the MD raid0 personality already has
stored RAID array device positions in the superblocks, the MetaLVs have to
be cleared so that the kernel doesn't fail validating the array positions
after lvm has shifted them up by one.

Add more tests to lvconvert-raid-takeover.sh including one to check for
mapping flaws by converting a created raid4 with filesystem -> striped
and fsck it.

Whilst on it:
- add missing direct striped -> raid4 conversion to the takeover array
  to avoid an intermim conversion from striped -> raid0*
- clean up the takeover array
- allow lvconvert to actually call lv_raid_convert() on all takeover requests
  in order to check parameters and display messages provided by takeover
  functions rather than just "...not supported" from within lvconvert
- fix a typo

Resolves: rhbz1386148
2016-10-21 19:00:31 +02:00
34da83d729 dmsetup: Produce partial output if dev disappears.
If a device disappears after obtaining the list of devices but before
processing it as a member of that list, dmsetup exits with a failure code.

Most commands still produce what output they can in these circumstances,
but 'ls --tree' and 'info -c' with fields depending on device dependencies
didn't.  Change this.
2016-10-18 18:01:52 +01:00
5c55c4ac18 spec: move dmeventd -R from post to posttrans script for device-mapper-event package
See also https://bugzilla.redhat.com/show_bug.cgi?id=1382688.
2016-10-12 13:52:13 +02:00
900e899739 lvconvert: still use strcmp for now
Keep for now function logic making its decision on string content.
We need bigger patch converting all things to bit-checks later.
This needs however bigger refactoring.
So this commit reverts some changes from:
c8b6c13015
2016-10-12 11:18:23 +02:00
8859d4508a lvconvert: fix RAID SubLV --splitmirror regression
Commit 088b3d036a allowed repair on cache origin RAID LVs
and restricted lvconvert actions on RAID SubLVs to change number of mirrors, repair,
replace and type changes in order to avoid unsuitable coversions on them.

This introduced a regression prohibiting --splitmirrors on any RAID SubLVs
(e.g. of cache or thin LVs; lvconvert-{cache,thin}-raid.sh tests failing).

Fix allows split mirrors again.

Fix some indenting whilst on it.
2016-10-12 00:24:57 +02:00
e57fd9d963 lvmdbustest.py: ws fixes 2016-10-11 13:16:57 -05:00
9c56902365 lvmdbustest.py: Add $PREFIX support
Use the env variable PREFIX for vg & lv names
2016-10-11 13:16:57 -05:00
595af62ebd lvmdbustest.py: Use more compatible syntax 2016-10-11 13:16:57 -05:00
4fab833920 lvmdbusd: Remove log ouput when ec=0 & stderr != 0 bytes
lvm likes to log to stderr virtually all the time, this isn't
helpful.
2016-10-11 13:16:57 -05:00
2830f72288 lvmdbusd: Disable lvm abort on too much log output
The commit:
https://git.fedorahosted.org/cgit/lvm2.git/commit/?id=34c55d98eefd88f85476c0f62f0649c706bde6f0

introduced an abort if lvm logs too much.  In the case of utilizing
lvm shell this is a pretty normal occurance, so we will disable
when we use lvm shell.
2016-10-11 13:16:57 -05:00
fe437a6e7d tests: notify dbus only for dbus test 2016-10-11 13:37:44 +02:00
8f30069160 cleanup: indent 2016-10-11 13:37:43 +02:00
6f576483a8 cleanup: lvconvert drop unused variable 2016-10-11 13:37:43 +02:00
c8b6c13015 cleanup: use already set values
When we have already decoded arg_is_set into a local var
or already set  segment type - already use these
values instead of repeating calls and string checks.
2016-10-11 13:37:43 +02:00
f4ae43934a cleanup: reorder code
Move some arg test into a single place with sort of alphabetic order
when possible to make reading easier.
2016-10-11 13:37:43 +02:00
706d3ddf90 lvconvert: use _read_conversion_type
Code reodering and using same pattern for reading and validating arg
(--type in this case).
2016-10-11 13:36:51 +02:00
1186cf2ad4 lvconvert: fix error value
Seems some error path where not converted to 'new' ECMD return value.
Fix them to always 'goto out'.
Also drop unneeded   'ret = 0' when ret already is 0.
2016-10-11 13:36:29 +02:00
20e74313cd lvmdbustest.py: Add profile and path for lvm binary 2016-10-10 16:33:42 -05:00
be06fa695e lvmdbustest.py: Skip test_job_handling_timer on loopback
This test never passes on loop back, so we will skip unless the
pv devices are real devices which contain `/dev/sd`.

We always fail because we need lvm to run slow to get a timer to
pop, and loopback are too fast.
2016-10-10 16:31:00 -05:00
3e45285b40 lvmdbustest.py: Denote failure if set_execution fails 2016-10-10 16:31:00 -05:00
0c51f369a4 lvmdbustest.py: Print to stderr
It's easier to follow if we print to stderr, so that our print messages
are in the lvm error log in the correct position to other printed
messages.
2016-10-10 16:31:00 -05:00
cb4e26dcb3 lvmdbustest.py: Ensure we exit non-zero on fail
If you run multiple runs of unittest.main, unless you don't pass exit=true
the test case always ends with a 0 exit code.  Add ability to store the
result of each invocation of the test and exit with a non-zero exit code
if anyone of them fail.
2016-10-10 16:31:00 -05:00
9f0195ec1e lvmdbusd: Ensure tmp dir gets cleaned up
Regardless of the outcome of starting up the lvm shell process, lets
ensure we clean up the temp directory and pipe.
2016-10-10 16:31:00 -05:00
2e941beb44 lvmdbusd: Ensure lvm shell still exists 2016-10-10 16:31:00 -05:00
088b3d036a lvconvert: certain repair of cache raid volumes fails "Cannot convert internal LV"
In case a RAID orig LV is being cached and fails, repair is impossible because
"lvconvert --repair" gets rejected.

Fix by allowing repair on cache orig RAID LVs and
"lvconvert --replace/--mirrors/--type {raid*|mirror|striped|linear}" as well.

Allow the same lvconvert actions on any cache pool and metadata RAID SubLVs.

Resolves: rhbz1380532
2016-10-10 17:31:29 +02:00
a8bb8dfb08 lvmdbusd: Add LvCommon.DataPercent 2016-10-05 15:55:41 -05:00
d54ffcfcd1 lvmdbusd: Add LvCommon.MovePv
Needed for feature parity for lvm2app.
2016-10-05 15:28:42 -05:00
a3f24aaf5c lvmdbusd: Add properties to LvCommon
The following LvCommon properties were added so that the API
would have the same functionality as lvm2app has.

LvCommon.MetaDataSizeBytes
LvCommon.Attr
LvCommon.MetaDataPercent
LvCommon.CopyPercent
LvCommon.SnapPercent
LvCommon.SyncPercent
2016-10-05 13:59:38 -05:00
bf5d0a2651 toollib: clean up coverity issue
in processing duplicate pvs.
2016-10-04 16:25:32 -05:00
c900cf7ed4 Revert "cleanup: simplier assign of cmd vars"
This reverts commit cea441f4d1.

cmd->default_values is configurable and this code should not make
any assumptions about values it holds.
2016-10-03 18:14:17 +01:00
9e33781d95 tests: proper wait usage
Fix missing wait so we have paired waiting.
Also 'wait' for precise PID to get 'exit' code.

Test for 'error' replacing only with newer snapshot targets.
The old one will wait for resume.

Note: 'wait -n' is not always available so can't be used..
2016-10-03 17:49:56 +02:00
43662fa081 cleanup :drop unneeded header file
Not needed  (Coverity).
2016-10-03 17:49:56 +02:00
77ffd39dfb cleanup: drop test for NULL
Since lp->segtype has been already checked for not-being NULL,
drop this test so Coverity is not later confused it 'can be a NULL'.
2016-10-03 17:49:56 +02:00
9fe4f2337b cleanup: drop assign before use
Drop unneeded assigns singe vars are set later in code before
their first use (Coverity).
2016-10-03 17:49:55 +02:00
cea441f4d1 cleanup: simplier assign of cmd vars
Directly assign queried args as they provide matching values for
a setting.
2016-10-03 17:49:55 +02:00
00f883a4aa dmeventd: pthread_sigmask in single function
Integrate back _unblock_sigalrm() and check for error code of
pthread_sigmask() function so we do not use uninitialized
sigmask_t on error path (Coverity).
2016-10-03 17:47:28 +02:00
d70f112762 libdm: check for mem when _canonicalize_field_ids
Add missing check for dm_pool_strdup() call (Coverity).
2016-10-03 17:46:26 +02:00
ee04f1fcfd raid: dmeventd plugin use 64bit arithmetic
Coverity suggested to used 64bit unsigned ints instead of signed 32b int.
Assuming there is no user of >31legs raid array.
2016-10-03 17:44:25 +02:00
e95a252974 libdm: convert FIEMAP buffer allocation from stack to dm_zalloc 2016-10-03 15:14:33 +01:00
49a1c4d4b0 lvmlockd: fix segfault in error path
The log_debug statement was ignoring the NULL vg error case.
2016-09-28 13:29:55 -05:00
bd96036835 lvmdbusd: Use 'pv_missing' column instead of '[unknown]'
Previously using '[unknown]' for PV device path comparison which
is incorrect as it's not always true.
2016-09-28 12:07:48 -05:00
be5eb995d3 lvmdbusd: Remove extraneous parameter
Remove 'gen_new' parameter as it's not needed, correct documentation.
2016-09-28 12:05:44 -05:00
a93616cf66 lvmdbusd: Add diagnostic validate for look ups
Make sure that the lookup tables don't have extranoues stuff in
them.
2016-09-27 13:28:54 -05:00
d906fd5201 lvmdbustest.py: Make sure to test for hidden lookups
Test both vgname/[hidden] and vgname/hidden forms
2016-09-27 13:28:54 -05:00
063265eacd lvmdbusd: Allow PV device names to be '[unknown]'
When a PV device is missing lvm will return '[unknown]' for the device
path.  The object manager keeps a hash table lookup for uuid and for PV's
device name.  When we had multiple PVs with the same device path we
we only had 1 key in the table for the lvm id (device path).  This caused
a problem when the PV device transitioned from '[unknown]' to known as any
subsequent transitions would cause an exception:

Traceback (most recent call last):
  File "/usr/lib/python3.5/site-packages/lvmdbusd/request.py", line 66, in run_cmd
    result = self.method(*self.arguments)
  File "/usr/lib/python3.5/site-packages/lvmdbusd/manager.py", line 205, in _pv_scan
    cfg.load()
  File "/usr/lib/python3.5/site-packages/lvmdbusd/fetch.py", line 24, in load
    cache_refresh=False)[1]
  File "/usr/lib/python3.5/site-packages/lvmdbusd/pv.py", line 48, in load_pvs
    emit_signal, cache_refresh)
  File "/usr/lib/python3.5/site-packages/lvmdbusd/loader.py", line 80, in common
    cfg.om.remove_object(cfg.om.get_object_by_path(k), True)
  File "/usr/lib/python3.5/site-packages/lvmdbusd/objectmanager.py", line 153, in remove_object
    self._lookup_remove(path)
  File "/usr/lib/python3.5/site-packages/lvmdbusd/objectmanager.py", line 97, in _lookup_remove
    del self._id_to_object_path[lvm_id]
KeyError: '[unknown]'

when trying to delete a key that wasn't present.  In this case we don't add a
lookup key for the device path and the PV can only be located by UUID.

Ref: https://bugzilla.redhat.com/show_bug.cgi?id=1379357
2016-09-27 13:28:54 -05:00
a882eb2b3b lvmdbusd: Clean up objectmanager.get_object_path_by_uuid_lvm_id
This method grew crufty with a number of stuble bugs.  Refactor and
simplify.
2016-09-27 13:28:54 -05:00
ec076b1df2 lvmdbustest.py: Make env variable work 2016-09-27 13:28:45 -05:00
1bc546269a lvconvert: Disable thin pool raid conversion while active.
Works if the pool is inactive.

Activation code doesn't notice a new raid dependency in on-disk metadata
when a thin LV is already active.

https://bugzilla.redhat.com/1365286
2016-09-27 18:22:54 +01:00
56c90ffa5e libdm: fix dm_stats_delete_region() backwards compat
The dm_stats_delete_region() call removes a region from the bound
device, and, if the region is grouped, from the group leader
group descriptor stored in aux_data.

To do this requires a listed handle: previous versions of the
library do not since no dependencies exist between regions without
grouping.

This leads to strange behaviour when a command built against an old
version of the library is used with one supporting groups. Deleting
a region with dmstats succeeds, but logs errors:

  # dmstats list
  Name             RgID RgSta RgSiz #Areas ArSize ProgID
  vg_hex-root         0     0 1.00g      1  1.00g dmstats
  vg_hex-root         1 1.00g 1.00g      1  1.00g dmstats
  vg_hex-root         2 2.00g 1.00g      1  1.00g dmstats
  # dmstats delete --regionid 2 vg_hex/root
  Region ID 2 does not exist
  Could not delete statistics region.
  Command failed
  # dmstats list
  Name             RgID RgSta RgSiz #Areas ArSize ProgID
  vg_hex-root         0     0 1.00g      1  1.00g dmstats
  vg_hex-root         1 1.00g 1.00g      1  1.00g dmstats

This happens because the call to dm_stats_delete_region() is inside
a dm_stats_walk_*() iterator: upon entry to the call, the iterator
is at its end conditions and about to terminate. Due to the call to
dm_stats_list() inside the function, it returns with an iterator at
the beginning of a walk and performs a further iteration before
exiting. This final loop makes a further attempt to delete the
(already deleted) region, leading to the confusing error messages.
2016-09-27 17:58:05 +01:00
6ec8854fdb libdm: fix stats walk compatibility with older dmsetup
The current dmsetup.c handles DR_STATS and DR_STATS_META reports
separately in _display_info_cols(), meaning that the stats walk
functions are never called for these report types.

Versions before v2.02.159 have a loop using dm_stats_walk_do() and
dm_stats_walk_while(), that executes once for non-stats reports,
and once per region, or area, for DR_STATS/DR_STATS_META reports.

This older behaviour relies on the documented behaviour that the
walk functions will accept a NULL pointer as the struct dm_stats*
argument.

This was broken by commit f1f2df7b: the NULL test on dms and
dms->regions were incorrectly moved from the dm_stats_walk_end()
wrapper to the internal '_stats_walk_end()' helper.

Since the pointer is dereferenced in between these points, using
an older dmsetup with current libdm results in a segfault when
running a non-stats report:

  # dmsetup info -c vg00/lvol0
  Segmentation fault (core dumped)

Restore the NULL checks to the wrapper function as intended.
2016-09-27 14:46:00 +01:00
0a480c5c52 systemd: disable service start rate limiting for lvm2-pvscan@.service
We shouldn't be losing pvscans just because of the fact that the
underlying device (PV) appears and disappears quickly in the system,
otherwise lvmetad may not see the device if it appears again (or it may
still keep the device in cache even it's already gone).
2016-09-27 10:48:01 +02:00
397c246fe0 post-release 2016-09-26 14:29:35 +01:00
5233a3468c pre-release 2016-09-26 14:20:08 +01:00
f93cddeafd man: fix dmsetup stats
Fix typo  STATS -> STATUS.
2016-09-26 12:38:32 +02:00
70be57c8da systemd: fix extra space in unit generated by lvm2-activation-generator 2016-09-26 09:54:19 +02:00
b5e093624d toolcontext: read all configuration sources when checking config values in lvm2-activation-generator through lighweight toolcontext handler
We added lightweight toolcontext handle to avoid useless initialization
of some parts of the context and also to avoid problems when using the
handle very soon at system boot, like in lvm2-activation-generator
through lvm2app interface. However, we missed reading all the other
config sources like lvmlocal.conf as well as any tag config - we need to
read these too to get the final config value which may be overriden in
any of these additional config sources.

Currently, we use this lightweight toolcontext handle to read
global/use_lvmetad and global/use_lvmpolld config values in
lvm2-activation-generator using lvm2app interface (lvm_config_find_bool
lvm2app function).
2016-09-23 14:57:44 +02:00
dbcfd59714 make: also clean up lvmdump.sh with substitutions - there's original lvmdump.sh.in 2016-09-23 12:48:52 +02:00
f2efd04052 tests: fix raid rebuild tests to work with older target versions
Pre 1.9 dm-raid targets status output was racy, which caused
the device status chars to be unreliable _during_ synchronization.
This shows paritcularly with tiny test devices used.

Enhance lvchange-rebuild-raid.sh to not check status
chars _during_ synchronization. Just check afterwards.
2016-09-22 23:35:37 +02:00
38a6a39daa tests: raid repair needs devices in-sync
Though I'm not quite sure why we push this limit on user,
current --repair logic requires user to wait outside of command.

TODO: I'm not quite sure this repair logic is 'the most wanted'.
2016-09-22 15:46:18 +02:00
eb6b2a11e3 tests: check for TRIM support
passdown can really work only on discardable device.
Skip 'status' test when PV does no support discard.
2016-09-22 15:37:52 +02:00
f1cad4c710 config: use config_tree_from_string_without_dup_node_check throughout code to construct metadata trees 2016-09-21 18:18:15 +02:00
045772aa30 config: add config_tree_from_string_without_dup_node_check to replace dm_config_from_string where needed 2016-09-21 18:18:15 +02:00
e40fbd08c8 config: parse config tree without dup node checking if it's metadata tree 2016-09-21 18:16:05 +02:00
7563e69cf1 libdm: add dm_config_parse_without_dup_node_check
Introduce function for config parsing tree without checking
for duplicate nodes.
2016-09-21 18:15:18 +02:00
094488ffab cleanup: remove unused variables 2016-09-21 15:53:50 +02:00
926a565781 coverity: dmsetup: fix possible use of uninitialized value 2016-09-21 15:52:23 +02:00
7ea5758c91 dmsetup: ensure --filemap histogram bounds are freed
Make sure that the temporary dm_histogram used for the bounds
argument is freed in the case that the user provided a --bounds
argument on the command line.
2016-09-21 10:09:20 +01:00
5d455b28fc lvconvert: fix (automatic) raid repair regression
The dm-raid target now rejects device rebuild requests during ongoing
resynchronization thus causing 'lvconvert --repair ...' to fail with
a kernel error message. This regresses with respect to failing automatic
repair via the dmeventd RAID plugin in case raid_fault_policy="allocate"
is configured in lvm.conf as well.

Previously allowing such repair request required cancelling the
resynchronization of any still accessible DataLVs, hence reasoning
potential data loss.

Patch allows the resynchronization of still accessible DataLVs to
finish up by rejecting any 'lvconvert --repair ...'.

It enhances the dmeventd RAID plugin to be able to automatically repair
by postponing the repair after synchronization ended.

More tests are added to lvconvert-rebuild-raid.sh to cover single
and multiple DataLV failure cases for the different RAID levels.

- resolves: rhbz1371717
2016-09-21 00:39:29 +02:00
78e0fdb618 tests: correcting kernel version test
Debug force leaked in.
2016-09-20 22:50:43 +02:00
9f6b006272 tests: show some more device info
When passdown is not there, look for possible reason.
2016-09-20 22:47:14 +02:00
994df22b60 tests: read messages instead of syslog
Since on those older system there is rather 'fight' over
syslog reading buffer - lets read output from /var/log/messages
intead.
2016-09-20 22:36:29 +02:00
a9c2a62939 tests: kernel message for <3.5 kernels
Since /dev/kmsg is useless on kernel <3.5 user there automatically
syslog to obtain traces from kernel log buffer during test.
2016-09-20 17:09:46 +02:00
67d4b3b7f2 cache: restore reported origin field
Commit 199697accf rerouted funtion
for priting cache volume origin to lvm2app app function - which
however had a bug.  So restore the original functionality
and print correct LV as cache origin LV.
2016-09-20 14:26:11 +02:00
414d39085c snapshots: Fix monitoring to use cow not internal LV. 2016-09-20 02:30:58 +01:00
ed37b4a626 lvmdbusd: Assign percentage on set 2016-09-19 15:32:47 -05:00
d18ea3f2cb lvmdbustest: Remove pyudev deprecated warnings 2016-09-19 15:32:47 -05:00
ec821d37a8 lvmdbusd: Correct imports
Place the imports in the files where they are directly needed.
2016-09-19 15:32:47 -05:00
c23d5f63fd lvmdbustest: ws fix-ups 2016-09-19 15:32:47 -05:00
9cb8865511 lvmdbusd: Fix dbus object with only properties and no method
Gris debugged that when we don't have a method the introspection
data is missing the interface itself eg.

<interface name="<your_obj_iface_name>" />

When adding the properties to the dbus object introspection we will
add the interface too if it's missing.  This now allows us the
ability to have a dbus object with only properties.
2016-09-19 15:32:47 -05:00
cb2b261510 lvmdbustest.py: Test with/without timeout values
Because of the different code paths we need to test job handling with
all operations.  Test now runs virtually everything with timeout == 0
and timeout == 15 so that we test both use cases.

Note:  If a client passes -1 for the timeout value they need to make
sure that their connection time out is also infinite.  Otherwise, if the client
times out the service side hangs any new dbus calls until the job
that is in progress completes.  Not sure why this behavior is occuring
at this time, but it appears a limitation/bug of the dbus-python library.
2016-09-19 15:32:27 -05:00
5366e87574 lvmdbusd: Set value to non none on error
When we register a failure we need to use a valid value which will be
returned with the object manager.  Otherwise we will raise an Exception
because we are trying to construct an object path from None.
2016-09-19 15:31:04 -05:00
65f59184c8 lvmdbustest.py: Make methods static
Changed methods to be static that should be.
2016-09-19 15:31:04 -05:00
ac2fc7a366 lvmdbusd: Vg.LvCreate* methods, correct return type
The methods were returning an instance of the object instead of the
object path which was causing an exception when the result was returned
with the job object as we are explicity trying to return an object path.

Unit test added which re-creates the issue and verifies the fix.
2016-09-19 15:31:04 -05:00
72abf692e5 debug: cleanup backtrace after log_error 2016-09-19 14:00:56 +02:00
a029123679 debug: mention origin_only in message 2016-09-19 14:00:56 +02:00
b3b8834724 tests: enhance lvchange of thin pool tests
Validate also content of dmtable.
Check operations with unused thin-pool as well.
2016-09-19 14:00:56 +02:00
1a30adc062 tests: check for metadata test working properly
Add more tests to check they guard minimum free space in metadata
for new thin volume creation.
2016-09-19 14:00:56 +02:00
561f773bb4 tests: add check grep_dmsetup
Add simple helper/wrapper check function to check result
of dmsetup call i.e.:

check grep_dmsetup table vg-lv  "grep_expected"
check grep_dmsetup status vg-lv -v "grep_unexpected"
2016-09-19 14:00:56 +02:00
0e8449a5b9 thin: fix lvchange of discards and zero flag
Reload of thin-pool origin_only is designed to only post messages
to a thin-pool. It's not intended to be used for reload of thin-pool
table. Fix it by using standard call  'lv_update_and_reload()'.
2016-09-19 14:00:56 +02:00
c2c2721d00 thin: enforce there is some free space in thin pool metadata
Unconditionally guard there is at least 1/4 of metadata volume
free (<16Mib) or 4MiB - whichever value is smaller.

In case there is not enough free space do not let operation proceed and
recommend thin-pool metadata resize (in case user has not
enabled autoresize, manual 'lvextend --poolmetadatasize' is needed).
2016-09-19 14:00:56 +02:00
776d5a25b4 thin: report pool as holder when no active thin volume
In the case there is no active thin volume, report thin pool
as lock holder. This fixed function like lvextend
which either expecte lock holder LV is some active thin
or 'possibly' inactive thin pool.
2016-09-19 14:00:56 +02:00
c26cd48536 libdm: fix end-of-groups test in _stats_walk_end() 2016-09-16 13:09:22 +01:00
9c8c8fb63a alloc: Use --alloc normal for mirror logs.
The existing code doesn't understand that mirror logs should cling to
parallel LVs (like extending them) instead of avoiding them.

As a quick workaround to avoid lvcreate failures, hard-code
--alloc normal for mirror logs even if the rest of the allocation
used a stricter policy.

https://bugzilla.redhat.com/show_bug.cgi?id=1376532
2016-09-16 02:11:58 +01:00
5da35d879a lvmdump: Use O_DIRECT to gather metadata. 2016-09-15 14:00:39 +01:00
d455300d7b lvmlockd: fix metadata validation when rescanning VG
When rescanning a VG from disk, the metadata read from
each PV was compared as a sanity check.  The comparison
is done by exporting the vg metadata from each dev to
a config tree, and then comparing the config trees.
The function to create the config tree inserts
extraneous information along with the actual VG metadata.
This extra info includes creation_time.  The config
trees for two devs can easily be created one second
apart in which case the different creation_times would
cause the metadata comparison to fail.  The fix is to
exclude the extraneous info from the metadata comparison.
2016-09-14 10:43:33 -05:00
629059ee84 tests: Revert "tests: not redirect strderr to stdout"
This reverts commit 5314d36f3d.

Ok - some tests do look for 'stderr' output of 'not' commands.
So let's keep existing functionality.
2016-09-13 13:23:47 +02:00
cebcc8a604 tests: slightly bigger raid arrays
Just to ensure we catch devices in sync.
2016-09-13 12:25:36 +02:00
08c94de798 tests: more permissive on test percent value
Just check there is some output.
Values may slightly differ per policy target version.
2016-09-13 12:25:36 +02:00
d34e315b8d tests: use just single raid_leg_status
Simplify 'check' test actualy and correct printed tracing output
2016-09-13 12:25:36 +02:00
5314d36f3d tests: not redirect strderr to stdout
Errors are 'wanted' and expected in this case.
2016-09-13 12:25:06 +02:00
a156fc9a54 libdm: cleaner debug message 2016-09-13 09:24:38 +02:00
5bf1778e33 rpm: install lvmreport.7 2016-09-12 16:51:53 +02:00
4ddcbe22b7 tests: slow down disks more 2016-09-12 16:51:53 +02:00
5b55f9616d tests: add check function for raid leg status
2 new check test functions:

raid_leg_status    - to just compare
raid_leg_status_is - to compare and die when different
2016-09-12 16:51:53 +02:00
44f1f45e16 tests: use exclusive activation
Slightly better for clvmd - thought test is still crashing
as table is broken.
2016-09-12 16:51:53 +02:00
a4363fbcb5 tests: move cache test to separate file
Don't mix plain raid test with  'raid+cache' test.
2016-09-12 16:49:51 +02:00
b592ea5bbc activation: dso always defined for monitoring query
Ensure 'dso' has always a defined (NULL) value,
and also ensure NULL 'dso' is not dereferenced.
2016-09-12 16:49:49 +02:00
06c7220f78 man: add lvmreport man page 2016-09-12 14:11:39 +02:00
1768ca599b man: Only install lvmraid when needed. 2016-09-12 13:03:09 +01:00
05dc70e22e cache: fixed copy&paste from last commit 2016-09-09 21:26:38 +02:00
ca7921f54b rpm: build with raid man page 2016-09-09 20:59:22 +02:00
75a42845c1 tests: rename test _ -> -
Change '_' in the test name.
2016-09-09 20:59:21 +02:00
6166cea5bf tests: increate delay for raid rebuild
Delay writes just to usable extents on a PV
(so lvm2 metadata update remains fast).
Raise delay to 10ms for write.
2016-09-09 20:59:21 +02:00
06e36fb434 tests: skip synaction test in cluster for now
Until we resolve it - we do not support syncaction on clustered VG.
2016-09-09 20:55:01 +02:00
e5ec348d68 tests: lowering disc usage
Correction for aux test result  ([] -> if;then;fi)

Use issue_discard to lower memory demands on discardable test devices
Use large devices directly through prepare_pvs

I'm still observing more then 0.5G of data usage through.

Particullary:

'lvcreate' followed by 'lvconvert' (which doesn't yet support --nosync
option)  is quite demanging, and resume returns quite 'late' when
a lot of data has been already written on PV.
2016-09-09 20:55:00 +02:00
454b891f6d cache: fix reporting of dirty cache
When cache has zero used blocks it's been wrongly reported as 100.00% dirty.
Fix it and report 0.00.
2016-09-09 20:53:36 +02:00
9350aa7218 lvm2app: fix cache percantage reporting
In lvm2app we were always returning dirty (copy%) value.
Return properly data & metadata usage values.
2016-09-09 15:03:28 +02:00
4b22cd81e6 cache: report metadata percentage
Reinstantiate reporting of metadata percent usage for cache volumes.
Also show the same percentage with hidden cache-pool LV.
This regression was caused by optimization for a single-ioctl in
2.02.155.
2016-09-09 15:01:35 +02:00
a13440d7ca tests: lower allocated memory
Use  smaller mirror to have faster sync.
TODO: switch to delayed devs...
2016-09-07 16:43:42 +02:00
6064a5084e cleanup: clean gcc6 minor/major types warnings
Put sys/sysmacros.h in front of sys/types.h header file as requested
by gcc6 part II.
2016-09-07 16:42:34 +02:00
5838c41a35 cache: scrubbing for cache origin LV - Bug 1169495
Allow RAID scrubbing on cache origin sub-LV

This patch adds the ability to perform RAID scrubbing on the cache
origin sub-LV (https://bugzilla.redhat.com/1169495).  Cache origin
operations are restricted to non-clustered RAID LVs until there can
be further testing in a cluster (even for exclusive activation).

User can either specify directly _corig LV
or he can specify cache LV and operation  --syncation is
passed ONLY to   _corig LV.

If users wants to manipulation with cache-pool devices - he
needs to specify this object name.

Signed-off-by: Jonathan Brassow <jbrassow@redhat.com>
2016-09-07 16:42:32 +02:00
01cc0dfae9 post-release 2016-09-07 02:34:15 +01:00
3d2b1ff5c4 pre-release 2016-09-07 02:25:51 +01:00
a6bcdbe13c man: Additional info on exit statuses. 2016-09-07 01:57:09 +01:00
a54f073af8 man lvmraid: install 2016-09-06 15:20:43 -05:00
e1f4fc22d2 man lvmraid: comment out unfinished features 2016-09-06 15:13:59 -05:00
ff3f5fa179 man lvmraid: remove rebuild example 2016-09-06 14:54:45 -05:00
a1fb7b51b7 man: add lvmraid(7) 2016-09-06 14:50:08 -05:00
c8a14a29cd dev-type: check for DEVLINKS udev db variable existence if udev_device_get_is_initialized fn is not present
Older udev versions (udev < v165), don't have the official
udev_device_get_is_initialized function available to query for
device initialization state in udev database. Also, devices don't
have USEC_INITIALIZED udev db variable set - this is bound to the
udev_device_get_is_initialized fn functionality.

In this case, check for "DEVLINKS" variable instead - all block devices
have at least one symlink set for the node (the "/dev/block/<major:minor>".
This symlink is set by default basic udev rules provided by udev directly.
We'll use this as an alternative for the check that initial udev
processing for a device has already finished.
2016-09-06 13:21:29 +02:00
2e4821a847 lvmetad: Unused includes. 2016-09-05 17:14:53 +01:00
d7b282c601 dev-type: use more appropriate messages in udev_dev_is_mpath_component and use 10s timeout 2016-09-05 14:37:13 +02:00
5d323c37f3 refactor: move and rename _dev_is_mpath_component in lvmetad.c to udev_dev_is_mpath_component in dev-type.c 2016-09-05 12:55:25 +02:00
29d0317557 lvmetad: check udev for mpath component several times if udev record not initialized yet
It's possible (mainly during boot) that udev has not finished
processing the device and hence the udev database record for that
device is still marked as uninitialized when we're trying to look
at it as part of multipath component check in pvscan --cache code.

So check several times with a short delay to wait for the udev db
record to be initialized before giving up completely.
2016-09-05 12:43:11 +02:00
939f5310b9 lvmetad: use udev to ignore multipath components during scan
When scanning devs to populate lvmetad during system startup,
filter-mpath with native sysfs multipath component detection
may not detect that a dev is multipath component.  This is
because the multipath devices may not be set up yet.

Because of this, pvscan will scan multipath components during
startup, will see them as duplicate PVs, and will disable
lvmetad.  This will leave lvmetad disabled on systems using
multipath, unless something or someone runs pvscan --cache
to rescan.

To avoid this problem, the code that is scanning devices to
populate lvmetad will now check the udev db to see if a
dev is a multipath component that should be skipped.

(This may not be perfect due to inherent udev races, but will
cover most cases and will be at least as good as it's ever
been.)
2016-08-31 13:19:57 -05:00
3a4267ade4 tests: skip test for older cache target
Some test on older can targets are not going to work, and
since there is no other fix then using newer kernel - skip
such tests completely.
2016-08-31 11:13:59 +02:00
b26604c8d8 dmeventd: typo and debug name fix
Fix 'raw' -> 'row' fix.
Consitently use thin pool as a type of monitored device in info message.
2016-08-31 11:13:59 +02:00
16ed726610 lvmdump: use lsblk -s and lsblk -O in lvmdump only if these options are supported
The lsblk is just a nice helper here - it's not crucial for lvmdump so
do best effort here and use the most we can from current version of
lsblk that is installed on system. The lsblk -s option was added a bit
later after lsblk introduction and lsblk -O support even more later -
so if these are not available, use only pure lsblk output without any
extras.
2016-08-30 15:38:34 +02:00
52d1ddd601 config: regenerate 2016-08-30 13:23:39 +01:00
be85c22f65 raid10: Fix #stripes in lvcreate msg when too many. 2016-08-30 12:04:23 +01:00
7412690dd2 lvmdbusd: Prefix tag string with '@' 2016-08-29 18:00:21 -05:00
257ce5733e lvmdbustest.py: Add tag regression test
Add '-' back in as acceptable tag character
2016-08-29 17:59:42 -05:00
5392a612dc lvmdbusd: WS/pep8 corrections 2016-08-29 15:28:06 -05:00
1870b3293a lvmdbusd/lvmdb.py: Make stand alone execution work
This was broken when the args were moved to cfg
2016-08-29 15:26:56 -05:00
96a0604bd0 lvmdbusd: Correct imports 2016-08-29 15:26:56 -05:00
756f51eac8 test/lib/aux.sh: Remove incorrect comment
The dbus service needs to use the system bus.  The test environment does
not allow work with session bus environment.
2016-08-29 15:26:56 -05:00
7c386bf4d4 test/lib/aux.sh: Remove '--udev' for lvmdbusd start
The service will start up with udev monitoring and disable it if lvm
starts calling ExternalEvent.
2016-08-29 15:26:56 -05:00
70d4e2e8d5 lvmdbusd: Handle different daemon options
- Prevent --lvmshell with --nojson, not a valid combination
- If user is preventing json, then no lvmshell usage
- Return boolean on Manager.UseLvmShell
2016-08-29 15:26:56 -05:00
1d1fe00846 lvmdbusd: Include lvm shell testing as the default 2016-08-29 15:26:56 -05:00
313c40ed09 dbus/testlib.py: Improve type checking
Leverage the introspection data to ensure that the service is returning
what is says it will be returning for methods and properties.
2016-08-29 15:26:56 -05:00
9241dbdf57 lvmdbusd: Correct return type for empty PeSegments 2016-08-29 15:26:56 -05:00
20318e4c6c lvmdbusd: Be more specific on return types for Lv 2016-08-29 15:26:56 -05:00
9aed18a571 lvmdbustest.py: Remove '-' from tag ch set 2016-08-29 15:26:55 -05:00
0985b2d0d4 lvmdbusd: Make job.Percent a double 2016-08-29 15:26:55 -05:00
2bb09b4015 lvmdbusd: Be more explicit on return values
The python dbus library tries to make best on what the dbus type is based on
python data type.  Some times it gets this wrong, so we will be explicit.
2016-08-29 15:26:55 -05:00
4902034c89 lvmdbusd: Use udev until ExternalEvent occurs
The normal mode of operation will be to monitor for udev events until an
ExternalEvent occurs.  In that case the service will disable monitoring
for udev events and use ExternalEvent exclusively.

Note: User specifies --udev the service will always monitor udev regardless
if ExternalEvent is being called too.
2016-08-29 15:26:55 -05:00
2352ff24a5 lvmdbusd: Add support for using lvm shell
With the addition of JSON and the ability to get output which is known to
not contain any extraneous text we can now leverage lvm shell, so that we
don't fork and exec lvm command line repeatedly.
2016-08-29 15:26:55 -05:00
a0a2c84a26 lvmdbusd: Add date & ts if running in a terminal
When we are running in a terminal it's useful to have a date & ts on log
output like you get when output goes to the journal.  Check if we are
running on a tty and if we are, add it in.
2016-08-29 15:26:55 -05:00
7e37e7fde4 lvmdbusd: Always fork & exec background commands
Our background job support requires a separate instance of lvm.  Use the
full lvm command to do so.
2016-08-29 15:26:55 -05:00
784b46ef2a debug: better verbose message 2016-08-29 20:51:16 +02:00
92d5a84410 cleanup: clean gcc6 minor/major types warnings
Put sys/sysmacros.h in front of sys/types.h header file as requested
by gcc6.
2016-08-29 20:51:16 +02:00
81970d22d8 cache: do not monitor cache-pool
Avoid monitoring of activated cache-pool - where the only purpose ATM
is to clear metadata volume which is actually activate in place
of cache-pool name (using public LV name).

Since VG lock is held across whole clear operation, dmeventd cannot
be used anyway - however in case of appliction crash we may
leave unmonitored device.

In future we may provide better mechanism as the current name
replacemnet is creating 'uncommon' table setups in case the metadata
LV is more complex type like raid  (needs some futher thinking about
error path results).

Another point to think about is the fact we should not clear device
while holding lock (i.e. dmeventd mirror repair cannot work in cases
like this).
2016-08-29 20:51:15 +02:00
b493811968 cache: introduce cache_pool_max_chunks
Introduce 'hard limit' for max number of cache chunks.
When cache target operates with too many chunks (>10e6).

When user is aware of related possible troubles he
may increase the limit in lvm.conf.

Also verbosely inform user about possible solution.

Code works for both lvcreate and lvconvert.

Lvconvert fully supports change of chunk_size when caching LV
(and validates for compatible settings).
2016-08-29 20:47:31 +02:00
2fde4399a0 lvconvert: Fix --splitmirrors segfault with incorrect PV.
Commit 9ee071705b misunderstood integer
promotion, but it's simpler to detect -1 more directly.
2016-08-26 01:21:01 +01:00
fc93f10892 tests: also fix typo in report/columns_as_rows in tests 2016-08-25 16:25:23 +02:00
e758d722c7 conf: fix typo in report/columns_as_rows config option name recognition
Commit e947c362dd introduced
config_settings.h file for central place to store all definitions for
config options. By mistake, it used report/colums_as_rows instead
of report/columns_as_rows (missing "n" in "columns").
2016-08-25 14:53:32 +02:00
b0e07d516e test: delay writes to all test PVs in lvchange-rebuild-raid.sh to avoid race 2016-08-25 01:37:34 +02:00
7ba7768111 alloc: Avoid PV tags too when avoiding parallel PV allocation.
Also add debug messages for parallel PVs.
2016-08-24 19:41:11 +01:00
bff470f83f test: add missing lvchange-rebuild-raid.sh 2016-08-24 18:22:34 +02:00
40a4f5f38f alloc: Record PV tags of parallel PVs in log. 2016-08-24 15:49:34 +01:00
68adf2c199 alloc: Move _log_parallel_areas. 2016-08-24 15:47:38 +01:00
7837fbc1c1 lvconvert: Disallow raid10 mirror conversions. 2016-08-23 23:40:16 +01:00
2d65ce9711 dmeventd: Add fixed timeout when unmonitoring. 2016-08-23 16:09:18 +01:00
db0e34535c libdm: add some comments about DM_UDEV_DISABLE_LIBRARY_FALLBACK flag 2016-08-23 15:58:03 +02:00
b975532433 dmeventd: Simplify replacement unmonitor code. 2016-08-23 12:16:39 +01:00
97ee5a1cd3 dmeventd: Start merging back replacement unmonitor code. 2016-08-23 11:30:34 +01:00
952e413328 dmeventd: Fix unmonitoring when segtype changes.
When the segment type is being changed, unmonitoring an LV requires
the existing dso to be specified as a parameter, not the new one.
2016-08-23 02:26:14 +01:00
7646741ec6 raid: Don't monitor raid0 or raid0_meta LVs. 2016-08-20 02:14:33 +01:00
896912b14d lvcreate: Never treat raid0 as linear.
raid0 and raid0_meta require, or default to, at least 2 stripes.
2016-08-19 23:57:30 +01:00
88e6abc5a0 lvconvert: Don't allow --repair on raid0 LVs. 2016-08-19 23:42:01 +01:00
bf0eaafa6b libdaemon: add errno to error message 2016-08-19 10:59:46 -05:00
e192fde687 lvcreate: Drop warning messages for number of raid stripes.
It's now just setting a default, not adjusting the user's parameter.
2016-08-19 14:53:33 +01:00
ea0f604e70 lvcreate: No longer adjust --stripes for raid types.
If the number of stripes requested is incompatible with the requested
type of raid, give an error instead of adjusting it.

If no stripes argument is supplied, continue to use an appropriate
default.
2016-08-19 14:19:51 +01:00
c1a0a2c712 toollib: Record whether or not stripes/stripe_size args supplied. 2016-08-19 13:51:43 +01:00
c27963c566 lib: Move lcm and gcd to lib/misc for wider use. 2016-08-18 14:06:13 +01:00
8c71fc1cc2 man: lvconvert mention required option 2016-08-17 14:56:01 -05:00
0336b41828 man: lvconvert change location of sentence
The details about each option are explained in the
section for that option.
2016-08-17 14:13:17 -05:00
c0a0eedf2e vgsplit: fix regression processing thin external origins
a579ba2ac2 fixed a regression causing a segfault if no external
origin existed but broke the logic leading to erroneous error
messages and creations of split off exported VGs in case the
external origin and the pool LVs were allocated on different PVs.

- resolves rhbz1367459
2016-08-16 23:57:09 +02:00
73df2aedf9 lvcreate: better error message creating RAID LV on < 4 KiB VG extent size
Creating a RaidLV in VGs with very small extent sizes caused
late failure in the kernel giving a not very informative error
message. Catch the attempt early and display failure message
'Unable to create RAID LV: requires minimum VG extent size 4.00 KiB'.

- resoves rhbz1179970
2016-08-16 13:39:40 +02:00
114db6f745 tools: Suppress some unnecessary --stripesize warnings.
https://bugzilla.redhat.com/1366745
2016-08-15 19:38:45 +01:00
d83f2d766d pvmove: fix regression introduced with 8e9d5d12ae
'pvmove -n name pv1 pv2' called with the name of a top-level LV
failed with mentioned commit.

Enhance pvmove-raid-segtypes.sh to test for prohibited RAID SubLV moves.
2016-08-15 19:31:04 +02:00
8e9d5d12ae pvmove: prohibit non-resilient collocation of RAID SubLVs
'pvmove -n name pv1 pv2' allows to collocate multiple RAID SubLVs
on pv2 (e.g. results in collocated raidlv_rimage_0 and raidlv_rimage_1),
thus causing loss of resilence and/or performance of the RaidLV.

Fix this pvmove flaw leading to potential data loss in case of PV failure
by preventing any SubLVs from collocation on any PVs of the RaidLV.
Still allow to collocate any DataLVs of a RaidLV with their sibling MetaLVs
and vice-versa though (e.g. raidlv_rmeta_0 on pv1 may still be moved to pv2
already holding raidlv_rimage_0).

Because access to the top-level RaidLV name is needed,
promote local _top_level_lv_name() from raid_manip.c
to global top_level_lv_name().

- resolves rhbz1202497
2016-08-15 18:22:32 +02:00
c7bd33d951 post-release 2016-08-15 13:23:06 +01:00
8297276967 pre-release 2016-08-15 13:17:47 +01:00
2ff893cd85 conf: add comment about cfg_runtime 2016-08-15 10:38:38 +02:00
9c9b9b276a raid_manip: pay attention to PVs listed on command line when allocating MetaLVs
Adding MetaLVs to given DataLVs (e.g. raid0 -> raid0_meta takeover) wasn't
paying attention to any PVs listed on the lvconvert command line.
2016-08-13 00:20:01 +02:00
6d52b17dfc raid_manip: add missing code avoiding MetaLV collocation on the same PV
Adding MetaLVs to given DataLVs (e.g. raid0 -> raid0_meta takeover),
_avoid_pvs_with_other_images_of_lv() was missing code to prohibit
allocation when called with a just allocated MetaLV to prohibit
collaocation of the next allocated MetaLV on the same PV.

- resolves rhbz1366738
2016-08-12 22:46:57 +02:00
0973d6e331 notify: Fix hang with lvm shell & --enable-notify-dbus
When lvm is compiled with --enable-notify-dbus and a user uses lvm
shell, after they issue 200+ commands the lvm shell will hang for
~30 seconds trying to notify the lvm dbus service that a change
has occurred.  This appears to be caused by resource exhaustion,
because the sockets used for dbus communication are not be closed.
2016-08-12 14:36:43 -05:00
a185a2bea2 lvcreate/lvconvert: fix validation of maximum mirrors/stripes
Enforce mirror/raid0/1/10/4/5/6 type specific maximum images when
creating LVs or converting them from mirror <-> raid1.

Document those maxima in the lvcreate/lvconvert man pages.

- resolves rhbz1366060
2016-08-12 19:14:28 +02:00
93b61c07eb raid: Avoid double suffix on rmeta LV name paired with rimage LV. 2016-08-11 23:31:49 +01:00
e30fb19030 spec: Add new files 2016-08-11 14:10:59 +02:00
2fed8d8515 lvmcmdline: use long int for number returned by strtol 2016-08-10 09:10:37 +02:00
480c1c9599 post-release 2016-08-10 03:01:55 +01:00
37b8b84fee pre-release 2016-08-10 02:42:35 +01:00
b4f0503d1b man: fix references to names for --configreport arg in pvs, vgs and lvs man page 2016-08-09 18:49:11 +02:00
6fcfa2855b man: add lvm fullreport man page 2016-08-09 18:49:11 +02:00
5ac008116b report: add report_reset_cmdlog_seqnum and call it for each new cmd executed in lvm shell 2016-08-09 18:49:11 +02:00
29f7dc2922 conf: mark selected settings with CFG_DISALLOW_INTERACTIVE flag 2016-08-09 18:49:11 +02:00
e8985c71bc config: add support for CFG_DISALLOW_INTERACTIVE flag to mark settings as not suitable for override in interactive mode
Some settings are not suitable for override in interactive/shell
mode because such settings may confuse the code and it may end
up with unexpected behaviour. This is because of the fact that
once we're in the interactive/shell mode, we have already applied
some settings for the shell itself and we can't override them
further because we're already using those settings to drive the
interactive/shell mode. Such settings would get ignored silently
or, in worse case, they would mess up the existing configuration.
2016-08-09 18:49:11 +02:00
54bf15555b refactor: modify original _check_profile fn and rename to config_force_check for general use 2016-08-09 18:49:11 +02:00
785e2c31f5 conf: add lvmdbusd.profile 2016-08-09 18:49:11 +02:00
7111d48748 lvm: shell: honor log/command_log_selection as default and reset to this value after lastlog 2016-08-09 18:49:11 +02:00
e805ef2d66 lvmcmdline: profile: early profile load for lvm shell
Make it possible to also load profile for lvm shell by honouring
LVM_COMMAND_PROFILE environment variable.
2016-08-09 18:49:11 +02:00
f21afddeb7 lvm: shell: extend log report to cover whole lvm shell's main loop
When lvm commands are executed in lvm shell, we cover the whole lvm
command execution within this shell now. That means, all messages logged
and status caught during each command execution is now recorded in the
log report, including overall command's return code.
2016-08-09 18:49:10 +02:00
7d1125e5b7 libdm: report: add dm_report_group_output_and_pop_all
The dm_report_group_output_and_pop_all calls dm_report_output and
dm_report_group_pop for all the items that are currently in report
group. This is just a shortcut that makes it easier to output and
pop group's content so the group handle can be reused again without
a need to initialize and configure it again.

The functionality of dm_report_group_output_and_pop_all is the
same as dm_report_destroy but without destroying the report group
handle.
2016-08-09 18:24:45 +02:00
d86caf952e libdm: report: postpone printing of JSON starting '{' character till it's needed
This patch moves printing of starting '{' character for JSON output up
untili it's known there's any further output following - either the
content or ending '}' character.

Also, remove unnecessary switch for different report group types and
calling individual functions to handle dm_report_group_create as that
code is shared for all existing types at the moment.
2016-08-09 18:24:45 +02:00
9c21139284 libdm: report: add dm_report_destroy_rows
Calling dm_report_destroy_rows makes it possible to destroy any report
content we have but at the same time it doesn't destroy the report
handle itself, thus it's possible to reuse that handle again for new
report content.

Functionally, this is the same as calling dm_report_output with the
report handle but omitting the output iself. This functionality may
be useful if we, for whatever reason, need to discard the report
content and start a fresh new one but with the same report configuration
and initialization and thus we can just reuse the existing handle.
2016-08-09 18:24:45 +02:00
5649834f7d lvmcmdline: return 0/NULL if cmd->arg_values not set and arg_count/grouped_arg_count/arg_value called
We may call arg_count/grouped_arg_count/arg_value soon enough that
cmd->arg_values is not set yet.

Normally, when running a command, we execute lvm_run_command which in
turn calls _process_command_line to allocate and parse the command line
values and stores them in cmd->arg_values.

However, if we run lvm shell, this one doesn't accept any command line
options and we parse the command line for each command that is executed
within the lvm shell then. If we used any code that tries to access
cmd->arg_values through any of the the arg handling functions too
early, we could end up with a segfault due to uninitialized (NULL)
cmd->arg_values.

This patch just saves extra checks in all the code where arg handling
may be called too early so that the cmd->arg_values is not set up yet.
This does not apply to any of existing code, but subsequent patches
will need that.
2016-08-09 18:24:45 +02:00
1fde4bf4d0 refactor: move report grouping and log reporting handles from processing_handle to cmd_context
With patches that will follow, this will make it possible to widen log
report coverage when commands are executed from lvm shell so the amount
of messages that may end up in stderr/stdout instead of log report are
minimized.
2016-08-09 18:24:45 +02:00
ef69934746 shell: also collect last command's return code for subsequent 'lastlog' invocation
Add new log_context=shell and with log_object_type=cmd and
log_object_name=<command_name> for command log report to collect
overall return code from last command (this is reported under
log_type=status).
2016-08-09 18:24:45 +02:00
06ce9b4e42 log: separate output and make it possible to use given FDs
Currently, the output is separated in 3 parts and each part can go into
a separate and user-defined file descriptor:

  - common output (stdout by default, customizable by LVM_OUT_FD environment variable)
  - error output (stderr by default, customizable by LVM_ERR_FD environment variable)
  - report output (stdout by default, customizable by LVM_REPORT_FD environment variable)

For example, each type of output goes to different output file:

  [0] fedora/~ # export LVM_REPORT_FD=3

  [0] fedora/~ # lvs fedora vg/abc 1>out 2>err 3>report

  [0] fedora/~ # cat out

  [0] fedora/~ # cat err
    Volume group "vg" not found
    Cannot process volume group vg

  [0] fedora/~ # cat report
    LV   VG     Attr       LSize   Layout     Role       CTime
    root fedora -wi-ao----  19.00g linear     public     Wed May 27 2015 08:09:21
    swap fedora -wi-ao---- 500.00m linear     public     Wed May 27 2015 08:09:21

Another example in LVM shell where the report goes to "report" file:

  [0] fedora/~ # export LVM_REPORT_FD=3
  [0] fedora/~ # lvm 3>report

  (in lvm shell)
  lvm> vgs

  (content of "report" file)
  [1] fedora/~ # cat report
    VG     #PV #LV #SN Attr   VSize  VFree
    fedora   1   2   0 wz--n- 19.49g    0

  (in lvm shell)
  lvm> lvs

  (content of "report" file)
  [1] fedora/~ # cat report
    VG     #PV #LV #SN Attr   VSize  VFree
    fedora   1   2   0 wz--n- 19.49g    0
    LV   VG     Attr       LSize   Layout     Role       CTime
    root fedora -wi-ao----  19.00g linear     public     Wed May 27 2015 08:09:21
    swap fedora -wi-ao---- 500.00m linear     public     Wed May 27 2015 08:09:21
2016-08-09 18:24:45 +02:00
bb9789f2b3 test: fix/enhance lvcreate-large-raid*.sh
Multi-step extend to even larger raid10 LV lvcreate-large-raid.sh.

Comment fixes.
2016-08-09 18:16:01 +02:00
48e14390c1 test: fix lvcreate-large-raid.sh
RAID6 LVs may not be created with --nosync or data corruption
may occur in case of device failures.  The underlying MD raid6
personality used to drive the RaidLV performs read-modify-write
updates on stripes and thus relies on properly written parity
(P and Q Syndromes) during initial synchronization.

Once on it, enhance test to create/extend more and
larger RaidLVs and check sync/nosync status.
2016-08-09 17:45:37 +02:00
3d3f62e10a test: add lvconvert-raid-takeover.sh
Commit 76ef2d15d8 introduced
raid0 <-> raid4 takeover and full mirror <-> raid1 support.

Add tests for these conversions.

Tests exposed a kernel semantics change freezing resynchronization
on conversions from raid0[_meta] -> raid4 or adding raid1 legs
because kernel kept the RAID mapped device in 'frozen' state unless
an 'idle' message was sent or the table was reloaded (kernel patch pending).
2016-08-09 14:17:26 +02:00
e5a5fd3669 lvconvert: Fix repair and replace routing. 2016-08-08 23:13:34 +01:00
dad02900f1 man: explain deletion of 1st group member in dmstats.8.in
Although the use of the first region_id in a group to store the
DMS_GROUP=... aux_data tag is an internal implementation detail,
it has a user visible consequence in that deleting this region will
cause the group to disappear: add an explanation of this to the
'group' command and 'Regions, areas, and groups' section.
2016-08-08 19:29:12 +01:00
4bcbcdb1a2 man: minor fixes to dmstats.8.in
Remove obsolete reference to '--target'.
2016-08-08 19:07:56 +01:00
175e0905d5 test: Drop --mirrorlog when not a mirror. 2016-08-08 18:43:54 +01:00
fc93085c7a lvconvert: separate type raid to mirror
By the current division of unique operations,
converting type raid to type mirror is distinct
from converting type raid to raid.
2016-08-08 10:37:24 -05:00
6f90c954b7 WHATS_NEW: reject --nosync option for RAID6 LVs in lvcreate 2016-08-08 16:00:49 +02:00
c55134aa48 lvconvert: Limit --corelog and --mirrorlog to mirrors.
It's an error to specify a log when the final result is not of type
mirror.
2016-08-08 14:39:55 +01:00
7d6cf12554 lvcreate: reject '--nosync' option for RAID6 LVs
The MD raid6 personality being used to drive lvm raid6 LVs does
read-modify-write updates to any stripes and thus relies on correct
P and Q Syndromes being written during initial synchronization or
it may fail reconstructing proper user data in case of SubLVs failing.

We may not allow the '--nosync' option on
creation of raid6 LVs for that reason.

Update/fix 'man lvcreate' in that regard.

add lvcreate-raid-nosync.sh test script.

- Resolves rhbz1358532
2016-08-08 13:52:35 +02:00
57fa5d4329 lvmcmdline: do not refresh whole cmd context if profile dropped after processing LVM cmd
We don't need to refresh whole cmd context if we drop profile after
processing LVM command - just like we don't refresh cmd context when
we're applying the profile. It's because profiles contain only safe
subset of settings which do not require complete cmd context refresh.

This patch calls process_profilable_config instead of
refresh_toolcontext if there was profile applied for the LVM
command only, not --config which requires toolcontext refresh.
The process_profilable_config just sets proper values based on
values of profilable settings, but it does not do complete
reinitialization of various parts (e.g. filters, logging etc.).
2016-08-08 11:57:13 +02:00
76ef2d15d8 lvconvert: Support raid0<->raid4 and mirror<->raid1.
Only simple takeover cases so far.
2016-08-07 00:56:08 +01:00
de7f1deb80 raid: Report supported lvconvert conversions if invalid. 2016-08-07 00:30:26 +01:00
6f236c3353 raid: Add workaround to prepare for raid4 conversions. 2016-08-07 00:07:06 +01:00
ba0c26a078 raid: Pass list of LVs to remove into more fns. 2016-08-06 23:46:45 +01:00
30884208d4 raid: Move two functions. 2016-08-06 23:29:27 +01:00
802bd34562 WHATS_NEW: fixup order 2016-08-05 16:31:46 +02:00
8f25ad6416 raid_manip: fix log print format from commit d2c3b23e6d 2016-08-05 16:29:56 +02:00
9aefe9aa7a WHATS_NEW: add '--rebuild PV' option to lvchange to allow for PV selective rebuilds 2016-08-05 16:07:14 +02:00
d2c3b23e6d lvchange: Allow device specification when requesting a repair
'lvchange --resync LV' or 'lvchange --syncaction repair LV' request the
RAID layout specific parity blocks in raid4/5/6 to be recreated or the
mirrored blocks to be copied again from the master leg/copy for raid1/10,
thus not allowing a rebuild of a particular PV.

Introduce repeatable option '--[raid]rebuild PV' to allow to request
rebuilds of specific PVs in a RaidLV which are known to contain corrupt
data (e.g. rebuild a raid1 master leg).

Add test lvchange-rebuild-raid.sh to test/shell doing rebuild
variations on raid1/10 and 5; add aux function check_status_chars
to support the new test.

 - Resolves rhbz1064592
2016-08-05 16:01:46 +02:00
91f866f786 raid: Tell lib whether stripesize was specified 2016-08-05 14:28:14 +01:00
7482ff93b8 raid: Turn lv_raid_change_image_count into wrapper
Eventually the separate entry point will disappear.
2016-08-05 14:17:54 +01:00
b66fa91c46 segtypes: Further segtype macros. 2016-08-05 14:00:40 +01:00
b1b0b134ec raid0: Validate presence of raid0 meta_areas more tightly. 2016-08-04 21:15:07 +01:00
d1a25fe597 lvconvert: add FIXME
operations are no longer identified correctly.
2016-08-04 13:01:48 -05:00
4a15abe865 striped: Add precise macros for original segtype.
The existing striped macros include raid0 segments.
2016-08-04 01:24:39 +01:00
5c3141a8b9 lvconvert: Improve error message when no -m. 2016-08-03 23:43:59 +01:00
be497175e0 man: minor corrections in pvscan 2016-08-03 15:49:43 -05:00
2b01dca28a man: include info about disabled lvmetad 2016-08-03 15:42:12 -05:00
8b1a368b59 lvconvert: Provide entry point for new functionality.
Prepare for new segment type conversion functionality in cases that
currently fail.  In the short-term, we need to do this while limiting
the changes to the code paths for the conversions that are already
supported.
2016-08-03 03:53:29 +01:00
fdc3fcbfce lvconvert: Pass region_size to lv_raid_convert. 2016-08-02 23:51:20 +01:00
a234cebbed lvconvert: Preserve mirror region size with --repair. 2016-08-02 19:50:04 +01:00
415c5fd5d8 lvconvert: Divide into 12 categories. 2016-08-02 16:44:21 +01:00
6361bc4734 lvconvert: Treat --repair as an independent case. 2016-08-02 16:22:12 +01:00
804a397643 lvconvert: Forbid stripe parameters with --repair. 2016-08-02 15:59:12 +01:00
d0d03f315b vg_validate: correct min_recovery_rate check message 2016-08-02 15:27:13 +02:00
5765a28456 vg_validate: new RAID segment checks in check_lv_segments()
introduced with commit 8f62b7bfe5 rely on complete
             defintions of the relations between the LVs of a VG.
             Hence only run these checks when the complete_vg flag
             is set on calls to check_lv_segments().

             lvconvert failed in test lvconvert-thin-raid.sh when
             calling check_lv_segments() from _read_segments() without
             providing a complete definition.
2016-08-01 22:42:05 +02:00
c490be9134 Revert "thin: when converting a thin pool data or metadata LV from"
This reverts commit 237f84e038.

This case failed:
    lvcreate --type raid1 -m1 -l2 vg99
    lvcreate -aey -l2 -s vg99/lvol0
    lvconvert -m2 vg99/lvol0
2016-08-01 15:17:44 +01:00
d0df1ff995 lvconvert: Set lp->segtype in only one place. 2016-07-30 18:20:04 +01:00
1ce958bc5e lvconvert: Rely upon lp->thin and lp->cache. 2016-07-30 15:58:09 +01:00
48d9c46daa lvconvert: Fix --type thin recognition.
lp->thin already holds the result of the cmdline arg resolution.
2016-07-30 15:08:50 +01:00
52d2fa7022 tools: Also recognise segtype with thin and cache.
(--type thin still needs this for lvcreate - more logic should be
shared between lvcreate and lvconvert)
2016-07-30 04:12:58 +01:00
d1ff254c3c tools: mirror also supports stripesize 2016-07-30 03:52:49 +01:00
b3fbcd1ff7 lvconvert: Move stripe validation code later.
Simpler to delay it all until the actual LV being changed is available,
rather than having it split in two parts.
2016-07-30 02:52:06 +01:00
4ffe15bf6a tools: Unify stripesize parameter validation.
Move it all into get_stripe_params().
Some code paths missed --stripesize checks.
E.g. lvcreate --type raid4 -i1
2016-07-30 02:05:50 +01:00
d01b1b6cc1 lvconvert: Rearrange code that decides segtype. 2016-07-30 00:22:13 +01:00
a8e4790810 lvconvert: Only obtain --type parameter once. 2016-07-29 21:45:22 +01:00
800c0d3dd6 lvconvert: Remove hard-coded segment names. 2016-07-29 21:11:12 +01:00
237f84e038 thin: when converting a thin pool data or metadata LV from
linear to raid1, the linear wasnt't switched to the
      raid1 mapping, thus creating the false impression of
      resilience.
2016-07-29 19:17:12 +02:00
6b6e258e0c post-release 2016-07-28 19:58:22 +01:00
6f47e79a88 pre-release 2016-07-28 18:36:45 +01:00
a579ba2ac2 vgsplit: ea90a3d622 added an unconditional call to lv_is_on_pvs()
on any thin snap external origin LV which caused a segfault
         when none existed as exposed by the vgsplit-thin.sh test.

         Only call lv_is_on_pvs() if an external origin LV actually
         exists and correct the related splitting logic.
2016-07-28 18:35:33 +02:00
4bc351d658 lvmdbusd: Add '-y' to lvconvert for lv cache create
When converting to a cache lv, tests were hanging with a prompt for
"Do you want wipe existing metadata of cache pool volume
To preserve cache metadata add option "--zero n".
WARNING: Reusing mismatched cache pool metadata MAY DESTROY YOUR DATA!"

This is new.
2016-07-28 11:13:29 -05:00
20b21f4fd8 lvmdbusd: Fix hang for Job.Wait(n)
When a client is doing a wait on a job, any other clients will hang
when trying to do anything with the service.  This is caused by
the wait code which  was placing the thread that handles
incoming dbus requests to sleep until either the timeout expired or
the job operation completed.

This change creates a thread for the wait request, so that the thread
processing incoming requests can continue to run.
2016-07-28 11:13:29 -05:00
8d959b6c75 man: lvcreate correction on --stripes explanation and examples
with respect to the changed, configurable default behaviour
     introduced with commit 7eb7909193.

     E.g. raid default of 2 stripes rather than number of PVs in the VG
     or on the command line minus one.
2016-07-28 17:34:42 +02:00
02ddd48c11 tests: updates for new raid allocation logic
(with backward compatible settings user as well to check old logic
is still available when needed).
2016-07-28 16:37:20 +02:00
edb5d12463 config: keep new setting commented out 2016-07-28 15:08:11 +02:00
43f4555893 vg_validate: only reject min_recovery_rate in case max_recovery_rate is set and smaller 2016-07-27 23:20:58 +02:00
d46de28a6c vg_validate: add missing check for raid6 segment types 2016-07-27 23:14:46 +02:00
df02917d7e vg_validate: fix seg->extents_copied check introduced with
commit 8f62b7bfe5 and add comment for the member
             to 'struct lv_segment'
2016-07-27 23:09:54 +02:00
ea90a3d622 vgsplit: restore check for thin pool external origin
Fix a regression from commit 4420d41f, in which the
check was skipped for splitting a thin pool and an
external origin.
2016-07-27 14:00:57 -05:00
17fb64b569 man: lvmthin clean up syntax example
The syntax for converting an LV to a thin LV
included an unnecessary --thin option.  I was
probably still confused about these options
when writing this.
2016-07-27 13:13:59 -05:00
c7b2654c25 lvcreate.c: respect DEFAULT_RAID_MAX_IMAGES on creation of any RaidLV 2016-07-27 18:20:48 +02:00
8f62b7bfe5 vg_validate: segment check enhancements for raids to catch bogus metadata
General RAID and RAID segment type specific checks are added
to merge.c. New static _check_raid_seg() is called on each segment
of a RaidLV (which have just one) from check_lv_segments().

New checks caught some unititialized segment members
which are addressed here as well:

- initialize seg->region_size to 0 in lvcreate.c for raid0/raid0_meta

- initialize list seg->origin_list in lv_manip.c
2016-07-27 18:17:29 +02:00
9ad30b0b38 tests: check we don't warn when converting to thin LV
Tool produced warning for non-zeroing thin-pools.
2016-07-27 16:20:57 +02:00
0c3a09f1d7 tests: adapt for new cache-pool zeroing 2016-07-27 16:20:57 +02:00
eaf7d06a82 lvconvert: support --zero for full cache pool conversion.
Add matching support for -Z option also we doing full conversion
to cache-pool.

Extending coversion message to show which pool type is created
and whether the metadata will be wiped or remain unmodified.
2016-07-27 16:20:57 +02:00
3c377f8334 lvconvert: tune cache-pool zeroing
Follow-up to 27a767d5e8.
Tunning behavior in a way we always prompt when option --zero is NOT specified.
Without -Z lvm expects user wants to 'reset' cache-pool metadata
(they could have been splitted from some cached LV)

If user doesn't want to zero metadata he needs to specify -Zn.

User may also avoid prompting for zeroing by using -Zy for
cache-pool (basically equals using --yes  without -Z being given)
(unlike full convert case, there is no cache-pool being converted,
so there is not 'uncoditional' prompt in this case).
2016-07-27 16:20:57 +02:00
5636bfd83d lvconvert: suppress zeroing warning when converting to thin
When volume was lvconvert-ed to a thin-volume with external origin,
then in case thin-pool was in non-zeroing mode
it's been printing WARNING about not zeroing thin volume - but
this is wanted and expected - so nothing to warn about.

So in this particular use case WARNING needs to be suppressed.

Adding parameter support for lvcreate_params.

So now lvconvert creates 'normal thin LV' in read-only mode
(so any read will 'return 0' for a moment)
then deactivate regular thin LV and reacreate in 'final R/RW' mode
thin LV with external origin and activate again.
2016-07-27 16:20:57 +02:00
f66ae6e80f tests: add pv-ext-update.sh test
Tests automatic update of PV header (its "extension" part) to recent
version.
2016-07-27 12:17:21 +02:00
070c0d31ab metadata: fix automatic updates of PV extension headers to newest version
Before, the automatic update from older to newer version of PV extension
header happened within vg_write call. This may have caused problems under
some circumnstances where there's a code in between vg_write and vg_commit
which may have failed. In such situation, we reverted precommitted metadata
and put back the state to working version of VG metadata.

However, we don't have revert for PV write operation at the moment. So
if we updated PV headers already and we reverted vg_write due to failure
in subsequent code (before vg_commit), we ended up with lost VG metadata
(because old metadata pointers got reset by the PV write operation).

To minimize problematic situations here, we should put vg_write and
vg_commit that is done after PV header rewrites as close to each
other as possible.

This patch moves the automatic PV header rewrite for new extension
header part from vg_write to _vg_read where it's done the same way
as we do any other VG repairs if detected during VG read operation
(under VG write lock).
2016-07-26 16:22:55 +02:00
f9697ea006 libdm: report: fix json reporting to escape '"' character that may appear in reported string 2016-07-26 12:27:41 +02:00
d180bf6311 lvconvert: --trackchanges requires --splitmirrors 1 2016-07-25 21:15:25 +01:00
d0e15b86b5 lvmlockd: improve error message about missing global lock
If the VG holding the global lock is removed, we can indicate
that as the reason for not being able to acquire the global
lock in subsequent error messages, and can suggest enabling
the global lock in another VG.  (This helpful error message
will go away if the global lock is enabled in another VG,
or if lvmlockd is restarted.)
2016-07-25 14:49:01 -05:00
1efb1c2343 lvconvert: --trackchanges requires --splitmirrors 2016-07-25 19:32:10 +01:00
7b1daa248f lvconvert: remove warnings about deprecated split option
A warning seems too severe for this message, so leave it
out until there's a better idea.
2016-07-25 11:01:56 -05:00
70bad99894 lvmlockd: improve message for lock-start
Only print this for shared VGs, and include the
time it may take for sanlock.
2016-07-25 10:43:06 -05:00
94141c7797 man: add note about 'lastlog' built-in command 2016-07-25 15:05:08 +02:00
5397837a9f segtype: Fix unrecognised flag message.
Show in hex not decimal.
2016-07-25 12:59:50 +01:00
e4e29add68 conf: regenerate example.conf.in 2016-07-25 13:54:59 +02:00
3bc1adc404 raid_manip: Some validation functions. 2016-07-24 01:40:24 +01:00
ea543b5c6f raid_manip: Fix stripe_size type to uint32_t. 2016-07-24 01:35:04 +01:00
4a544ae272 raid_manip: Reorder some functions. 2016-07-24 01:31:30 +01:00
f6acf922e6 lvmlockd: improve activation locking error message
to include the LV type
2016-07-22 14:50:33 -05:00
2c3b92b550 lvconvert: change error message
for implicit pool conversion since it's also used
when the lv is already a pool
2016-07-22 10:00:24 -05:00
7fc1617819 tests: check thin resize of raid10 2016-07-22 14:41:47 +02:00
5bb113c204 man: drop .R
Avoid using .R as its not a valid man macro.
2016-07-22 14:41:47 +02:00
27a767d5e8 lvconvert: reusing old cache pool metadata needs -Zn
When cache pool is reused for a new cached volume, there is
normally no need to 'keep' old cache-pool metadata as this
could cause major data lose.

Unlike with 'lvcreate -H -LX --cachepool' conversion, this lvconvert
path left the metadata unzeroed - partly for making easier some
debugging, but this was rather a bug.

So to keep possible reattach of 'unzeroed' metadata, user
now has to use 'lvconvert -Zn' for such conversion. In this case
the prompt will appear about possibe data loss and to proceed,
user has to confirm such operation. Without -Zn metadata are wiped.
2016-07-22 14:40:26 +02:00
259f9dd718 lvcreate: conditionally set stripesize
Stripe size may not be set unconditionally in
_read_mirror_and_raid_params() or creation of
striped LV will fail
2016-07-21 02:33:28 +02:00
b203d5e745 lvconvert: allow implied cache pool convert
Just as with the implied thin pool convert when
given ambiguous command line options.
2016-07-20 10:44:28 -05:00
6ea250e2d0 lvmetad: fix use committed metadata to update
In some cases, the command will update VG metadata
in lvmetad without writing it.  In these cases there
is no vg->vg_committed and it should use 'vg' directly.
This happens when the command finds that the lvmetad
VG has been invalidated, rereads the metadata from disk,
then updates lvmetad with that metadata.  This happens
often with lvmlockd or foreign VGs, and can happen without
lvmlockd if a previous command fails after invalidating
the VG in lvmetad.
2016-07-20 10:25:26 -05:00
7eb7909193 lvcreate: raid0 needs default number of stripes
Commit 3928c96a37 introduced
new defaults for raid number of stripes, which may cause
backwards compatibility issues with customer scripts.

Adding configurable option 'raid_stripe_all_devices' defaulting
to '0' (i.e. off = new behaviour) to select the old behaviour
of using all PVs in the VG or those provided on the command line.

In case any scripts rely on the old behaviour, just set
'raid_strip_all_devices = 1'.

- resolves rhbz1354650
2016-07-20 17:20:15 +02:00
19e652b182 scripts: blkdeactivate: fix typo for DEV_DIR when executing blkdeactivate -m disablequeueing 2016-07-20 13:48:59 +02:00
9d19c1075f tests: enforce flush of cache target
Since now  lvm command no longer is flushing cache target with status
query - enforce it with extra status.
2016-07-19 17:39:46 +02:00
6dc4d03508 lvconvert: enable work with partial LVs
Fix printed message and enable handling of missing PVs.
2016-07-19 17:39:41 +02:00
f8872578e9 lvmetad: use committed metadata to update
This fixes a regression from commit a7c45ddc5, which moved
the lvmetad VG update from vg_commit() to unlock_vg().

The lvmetad VG update needs to send the version of metadata
that was committed rather than sending the state of struct 'vg'.
The 'vg' may have been partially modified since vg_commit(),
and contain non-committed metadata that shouldn't be sent
to lvmetad.
2016-07-18 16:18:53 -05:00
94207dfd68 lvconvert: raid0 replace attempt segfaults
Any failing stripes in raid0/raid0_meta type LVs cause data loss,
thus replacement via 'lvconvert --replace...' does not make sense.

Patch prohibits replacement on raid0/raid0_meta LVs.

- resolves rhbz1356734
2016-07-18 20:16:40 +02:00
da49d4d54e dmstats: fix bounds leak in _do_stats_create_regions() (Coverity) 2016-07-18 18:48:34 +01:00
d2bf6742f8 dmstats: check uuid, major, and alldevices before argc (Coverity)
The --uuid, --major and --alldevices arguments were incorrectly tested
after confirming argc is > 0, in a branch that only executes if argc
== 0 (i.e. they were unreachable).

Move all device checks before the test for argc and log an appropriate
error before returning.
2016-07-18 18:48:34 +01:00
252952ff33 libdm: document use of dm_free() with histogram bounds 2016-07-18 18:48:34 +01:00
da146ae9b9 dmstats: free bounds string in _stats_create_file() (Coverity) 2016-07-18 18:48:34 +01:00
4ef1f34549 libdm: free hist_arg in _stats_create_file_regions() (Coverity) 2016-07-18 18:09:21 +01:00
4b4d467004 lvmetad: free memory on exit
This is unnecessary but it quiets complaints (valgrind).
2016-07-18 11:31:00 -05:00
9c6a26f50a post-release 2016-07-15 22:02:58 +01:00
3d717b52c1 pre-release 2016-07-15 21:55:38 +01:00
c425cdd115 Revert "lvcreate: raid0 needs default number of stripes"
This reverts commit 3928c96a37.

A new setting is required in lvm.conf to control this.
2016-07-15 21:53:37 +01:00
081e569e14 man: drop lvmraid references from lvconvert 2016-07-15 15:08:02 -05:00
e96d1ad3ef cleanup: local static functions with _ 2016-07-15 15:49:01 +02:00
4de7a843eb coverity: close socket before closing app
Opened socket descriptor goes out-of-sight still opened.
Close it - but since this happens before app exit, it
just fixed valgrind report.
2016-07-15 15:49:01 +02:00
d2bb19e883 tests: check fail path on cache creation 2016-07-15 15:49:01 +02:00
a57bf37cdb tests: require better cache driver
Version 1.4 can't handle this test without killing itself.
2016-07-15 15:49:01 +02:00
12925d8b70 string: Add first_substring(). 2016-07-14 14:46:38 +01:00
5af311ddd8 macros: Add lv_is_not_synced. 2016-07-14 14:21:01 +01:00
07be2b864f lvmdump: include major and minor numbers for pvs and lvs reports
Including major and minor numbers in pvs and lvs output when calling
lvmdump -a makes it a bit easier to match these items with possible
system log/journal.
2016-07-14 14:33:33 +02:00
4e1bf7acd3 coverity: add some tests for function results
Even though they cannot normally happen...
2016-07-13 21:52:14 +02:00
4661c6b6fb coverity: cleaning some PW.NOT_COMPATIBLE_WITH_PREVIOUS_DECL
Some very low-prio warns....
2016-07-13 21:52:14 +02:00
bbf574ab90 coverity: easier to follow set-up of vsn variable
Helping coverity to see 'vsn' really can't be NULL.
2016-07-13 21:52:14 +02:00
0b773eecd9 tests: skip more cache tests for older driver 2016-07-13 21:52:14 +02:00
07587c2699 tests: resize of filesystem
Test for https://bugzilla.redhat.com/1354396
2016-07-13 21:52:14 +02:00
deb6f6a06c cleanup: add some dots to messages 2016-07-13 21:52:14 +02:00
e1112227d1 lvresize: fix zero size extension
Commit ca878a3426 changed behavior
or resize operation. Later the code has been futher changed
to skip fs resize completely when size of LV is already matching
and finaly at the most recent resize changeset for resize the
check for matching size has been eliminated as well so we ended
with a request call to resize fs to 0 size in some cases.

This commit reoders some test so the prompt happens just once before
resize of possibly 2 related volumes.

Also extra test for having LV already given size is added, and
whole metadata update is skipped for this case as the only
result would be an increment of seqno.

However the filesystem is still resized when requested,
so if the LV has some size and the resize is resolved to
the same size, the filesystem resize is called so in case FS
would not match, the resize will happen.
2016-07-13 21:52:04 +02:00
3928c96a37 lvcreate: raid0 needs default number of stripes
raid0/raid0_meta type LVs don't have a default number of stripes when
created without '-i/--stripes Stripes' whereas other raid types have one.

Patch sets the default for raid0/raid0_meta to 2 stripes.

The default amount of stripes for raid4/5/10 is changed to 2 and for raid6 to 3
rather than using all PVs in the VG or those provided on the command line.

This is to avoid unintended high number of stripes in case of many PVs.

To select a different amount of stripes from the default,
use 'lvcreate -i/--stripes Stripes'.

- resolves rhbz1354650
2016-07-13 21:45:49 +02:00
26f3b321f9 man: changes to lvconvert
Generally include more information about options.
2016-07-13 13:13:05 -05:00
df5021a201 lv_manip: extension of raid0 causes livelock
A livelock occurs on extension in lv_manip when adjusting the region size,
which doesn't apply to any raid0/raid0_meta LVs (these don't have a bitmap).

Fix by prohibiting the region size adjustment on any such LVs.

- resolves rhbz1354604
2016-07-13 15:17:24 +02:00
9c27573493 raid_manip: 'vgreduce --removemissing --force ...' segfaults on raid0 LV
An unconditional access to the non-existing MetaLV of a raid0 LV in
lv_raid_remove_missing() was causing the segfault.

Only call log_debug() on replacements of existing MetaLVs.

- resolves rhbz1354646
2016-07-12 17:55:01 +02:00
c77c59f3d9 lvchange: resync attempts on raid0 cause segfaults
Resync attempts on raid0/raid0_meta via 'lvchange --resync ...'
cause segfaults.

'lvchange --syncaction ...' doesn't get rejected either.

Prohibit both on raid0/raid0_meta LVs.

- resolves rhbz1354656
2016-07-12 17:23:05 +02:00
dcbcc65dc2 Revert "man: restore lost synopsis for lvconvert"
This reverts commit 80394ae7cd.

Anything that was missing or in error will be handled differently.
2016-07-12 09:48:59 -05:00
c32f96f277 vgsplit: use dm_list_next() 2016-07-12 16:25:12 +02:00
4ca55192e0 vgsplit: temporary list pointer may be invalid
4420d41fea introduced recursive split of lvs which
splits a top-level LV together with it's sub LVs.

This lead to invalid temporary list pointers
causing hangs/OOM situations.

Patch updates the temporary list pointer
referencing a moved sub LV.

- resolves rhbz1354686
2016-07-12 16:15:32 +02:00
d5be748341 man: lvcreate: try to be clearer about -W|--wipesignatures
There was still some confusion report about -W|--wipesignatures
lvcreate option so try to be even clearer. Hopefully, the last edit
here.
2016-07-12 15:23:29 +02:00
957480f4b9 tests: remove more test
Try to remove more tests before confusing older driver to death.
2016-07-12 13:20:56 +02:00
1891fa8272 tests: cache error message changes too often
Until lvconvert stabilize, avoid testing resulting error message.
2016-07-12 13:20:56 +02:00
80394ae7cd man: restore lost synopsis for lvconvert
Synopsis are very useful for quick orientation and also
we provide then for all remaining command.

Also list ALL supported options in a single ordered list,
user should not seek for them.
2016-07-12 13:20:56 +02:00
5254971418 cleanup: lvconvert display_lvname and indent updates
Use display_lvname() for printing vg/lv names.
Add some missing dots.
Some indents.
2016-07-12 13:20:20 +02:00
fd53d86eea cleanup: gcc warns removal
Ensure vars have always defined value.
2016-07-12 10:39:33 +02:00
42e76a1920 blkdeactivate: add -m|--mpathoption disablequeueing and use it for blk-availability systemd service and initscript
blkdeactivate -m disablequeueing causes "multipathd disablequeueing maps"
call inside blkdeactivate script before deactivating devices. This
avoids a situation where blkdeactivate may wait for paths to appear if
multipath is set to queueing and there's a stack of other devices and/or
mount points on top of such multipath device.

See also https://bugzilla.redhat.com/show_bug.cgi?id=1344381.
2016-07-12 10:01:07 +02:00
9f7e8f22dc lvconvert: remove some FIXME comments 2016-07-11 10:29:10 -05:00
c526c327d7 man: lvconvert changes 2016-07-11 10:29:07 -05:00
06a9dab730 tests: skip some tests for older cache driver
Cache target 1.4 on f19 kernel shows error, skipping some tests...
2016-07-11 15:45:28 +02:00
6336b5dedf tests: reduce amount of pvcreates
Reduce number of evualted pvcreate commands.
Since 0 is default value used to fill missing params,
and 0 is also 1st. value in array, it's being tested.

Drop unused data_alignment_offset.
2016-07-11 15:29:28 +02:00
8756297a8d tests: increase max lines for clvmd
Clvmd is a bit more verbose long time running process so
let it live with more logged lines.

Also fix typo in warn message from last commit.
2016-07-11 14:45:25 +02:00
34c55d98ee tests: add LVM_LOG_FILE_MAX_LINES
When logging to epoch files we would like to prevent creating too large
log files otherwise a spining command could fulfill available space
very easily and quickly.

Limit for to 100000 per command.
2016-07-11 12:43:28 +02:00
309bdfa224 libdm: add configure.in checks for fiemap.h and magic.h 2016-07-08 23:42:32 +01:00
61cb58e549 libdm: use 'goto_bad' if extent pool allocation fails
Generate a backtrace if unable to extend the extent table.
2016-07-08 22:28:50 +01:00
feb69966d4 libdm: use macro for boundary test in _stats_get_extents_for_file() 2016-07-08 22:21:14 +01:00
74565e41fc doc: update --filemap usage in dmstats.8.in 2016-07-08 22:05:36 +01:00
6a77a40501 dmstats: accept multiple arguments to --filemap
Make the --filemap switch take no arguments and instead accept one
or more files on the command line to be mapped and placed into
groups.

This allows --filemap to be used with a glob:

  # dmstats create --filemap *
  rhel5.10-1.qcow2: Created new group with 87 region(s) as group ID 1564.
  rhel5.10.qcow2: Created new group with 8 region(s) as group ID 1651.
  rhel7.0-1.qcow2: Created new group with 11 region(s) as group ID 1659.
  rhel7.0.qcow2: Created new group with 1454 region(s) as group ID 1670.
  vm.img: Created new group with 2 region(s) as group ID 3124.
2016-07-08 22:05:36 +01:00
2d1f03b616 libdm: use a constant for FIEMAP buffer size 2016-07-08 22:05:36 +01:00
58bfea6a6e libdm: use SECTOR_SHIFT constant in _stats_add_extent() 2016-07-08 22:05:36 +01:00
7771793a56 man: lvconvert changes 2016-07-08 14:34:36 -05:00
3951ca9320 lvconvert: allow splitcache on hidden/used cache pool
lvconvert --splitcache VG/CachePool_corig

Allow the split via the hidden/used cache pool for the time being,
since the new lvconvert code did intend to allow it, but was just
missing the exception in the list of hidden LVs that were allowed.

The preferred method for splitcache is to run it on the visible
cache LV, not the hidden cache pool.  That may eventually become
the only method since we try to avoid running commands on
hidden LVs.
2016-07-08 14:34:36 -05:00
39921284a0 lvconvert: don't show aliases in error output
We want to consistently use the standard command form.
The aliases are now mentioned in the man page for reference.
2016-07-08 14:34:36 -05:00
5cd39f1dc4 dmstats: use canonical path when reporting errors
When a 'dmstats create --filemap' operation fails (e.g. during
open(2), close(2), or dm_stats_create_regions_from_fd()), use the
canonical version of the path. This avoids cryptic/confusing error
messages when symbolic links exist in the path argument given:

  # findmnt /var/lib/libvirt/images -otarget,source
  TARGET                  SOURCE
  /var/lib/libvirt/images /dev/mapper/vg_hex-lv_images

  # readlink /var/lib/libvirt/images/my.img
  /boot/my.img

  # dmstats create --filemap /var/lib/libvirt/images/my.img
  Cannot map file: not a device-mapper device.
  Could not create regions from file /var/lib/libvirt/images/my.img
  Command failed

Using the canonical path the error is immediately obvious:

  # dmstats create --filemap /var/lib/libvirt/images/my.img
  Cannot map file: not a device-mapper device.
  Could not create regions from file /boot/my.img
  Command failed
2016-07-08 17:27:52 +01:00
17cbcc85bd doc: remove obsolete --statstype references from dmstats.8.in 2016-07-08 17:27:52 +01:00
008c57714a WHATS_NEW_DM: add --segments grouping and resource leak fix 2016-07-08 17:27:52 +01:00
6cb0c7bb5c doc: mention --segments grouping in dmstats.8.in 2016-07-08 17:27:52 +01:00
bd1f4987eb dmstats: group regions by default with --segments
Grouping is also useful in combination with --segments: creating a
group allows both individual segment data and data for the device
as a whole to be presented in the same report.

Support grouping for 'create --segments' in the same manner as for
'create --filemap'; group regions by default, applying an optional
alias specified with --alias, unless the user specifies --nogroup.
2016-07-08 17:27:52 +01:00
db63587ce2 WHATS_NEW_DM: add --filemap and histogram aggregation 2016-07-08 17:27:52 +01:00
bce1bc4ca3 dmstats: allow --bounds with 'create --filemap' 2016-07-08 17:27:52 +01:00
4bb57341bd libdm: enable creation of filemap regions with histograms 2016-07-08 17:27:52 +01:00
c3caf4b80b doc: mention group histogram restrictions in dmstats.8.in 2016-07-08 17:27:52 +01:00
db73d756e9 libdm: allow regions with histograms in dm_stats_create_group()
Allow regions with histograms to be grouped if all histograms have
the same number of bins and matching bounds.
2016-07-08 17:27:52 +01:00
ae9cffba52 libdm: add aggregation support to dm_stats_get_histogram()
Support aggregate group and region histograms by allocating a new
histogram from the pool and populating it with a sum of the histogram
data for the areas contained in the region or group.

To avoid repeatedly summing the same histogram data, cache the pointer
in the group and regions structs for subsequent access. The aggregate
histograms are allocated from the same pool as the area histograms in
the corresponding handle and will be discarded at each list or populate
operation.
2016-07-08 17:27:52 +01:00
d901468a27 doc: update dmstats.8.in for --filemap and --nogroup 2016-07-08 14:34:41 +01:00
7ebe630b69 dmstats: add create --filemap
Add a new option to the create command to create regions that map the
extents of a file:

  # dmstats create --filemap /path/to/file
  /path/to/file: Created new group with 10 region(s) as group ID 0.

When performing a --filemap no device argument is required (and
supplying one results in error) since the device to bind to is implied
by the file path and is obtained directly from an fstat().

Grouping may be optionally disabled by the --nogroup switch: in this
case the command will report each region individually:

  # dmstats create --nogroup --filemap /path/to/file
  /path/to/file: Created new region with 1 area as region ID 0.
  /path/to/file: Created new region with 1 area as region ID 1.
  /path/to/file: Created new region with 1 area as region ID 2.

When grouping regions the group alias is automatically set to the
basename (as returned by dm_basename()) of the provided file.

This can be overridden to a user-defined value at the command line by
use of the --alias option.

If grouping is disabled no alias can be set.

Use of offset and subdivision options (--start, --length, --segments,
--areas, --areasize).

Setting aux_data and histograms for groups is possible but is not
currently implemented.
2016-07-08 14:34:41 +01:00
e104825916 libdm: add dm_stats_create_regions_from_fd()
Add a call to create dmstats regions that correspond to the extents
present in a file descriptor open on a file in a local file system.
The file must reside on a file system type that correctly supports
physical extent location data in the FIEMAP ioctl.

Regions are optionally placed into a group with a user-defined alias.

File systems that do not support physical offsets in FIEMAP (btrfs
currently) are detected via fstatfs() - although attempting to map
a --filemap group on btrfs will fail anyway with the generic error
"Not on a device-mapper device" this is confusing; the file system
mount is on a device-mapper device, but btrfs' volume layer masks
this in the returned st_dev field since the returned logical file
extents may span multiple physical devices.
2016-07-08 14:34:41 +01:00
12ecd95965 man: enhance lvconvert 2016-07-08 15:18:18 +02:00
ebc7fc67c8 libdm: fix group resource leak in dm_stats_delete_region()
The function _stats_remove_region_id_from_group() incorecctly set
the group_id to DM_STATS_GROUP_NOT_PRESENT _before_ the call to
_stats_group_destroy(). This will cause the destroy function to
return immediately without doing anything:

 339 static void _stats_group_destroy(struct dm_stats_group *group)
 340 {
 341         if (!_stats_group_present(group))
 342                 return;

Invalidating the ID in _stats_region_region_id_from_group() is
redundant anyway; it is rightly done as the last operation in
_stats_group_destroy (and it is not possible for anything to see
the old value between the two calls).

Remove the change to group_id to ensure that the alias and bitset
resources are correctly freed.
2016-07-08 12:30:09 +01:00
005adb0a0a dmstats: ensure dm_stats_delete_region() return is checked 2016-07-08 12:26:34 +01:00
cc4f036d36 libdm: improve comments in stats grouping functions
Add more detailed comments to dm_stats_create_group() and
_stats_group_check_overlap().
2016-07-08 11:16:12 +01:00
059a383cf8 libdm: fix resource leak in dm_stats_set_alias()
When we fail to update aux_data the newly allocated group->alias must
be freed before reinstating old_alias.
2016-07-08 11:14:29 +01:00
5e06b33c51 libdm: enclose dm_stats_walk_do/while() body in do..while
The call to dm_stats_walk_start() before the do statement makes
dm_stats_walk_do() behave inconsistently depending on context;
wrap them in an additional do { } while (0) so that the macro
always expands to a valid statement.
2016-07-08 11:14:22 +01:00
6233bcf52d man: more lvcreate size rewording 2016-07-07 17:21:05 -05:00
589b752eeb man: rewrite lvconvert
Based on the new enumeration of all possible commands.
2016-07-07 17:12:37 -05:00
0de56eeaad man: more rewording for lvcreate size 2016-07-07 13:11:43 -05:00
13cd3ff5a0 lvconvert: allow converting type raid1 to type linear
The code could perform this conversion but ironically
did not recognize the standard command form, only the
the unpreferred "implication-based" command form.

"lvconvert --type linear VG/RaidLV" would fail, but
"lvconvert --mirrors 0 VG/RaidLV" would succeed.
2016-07-06 16:44:18 -05:00
37d1b7b745 lvconvert: allow converting type mirror to type linear
The code could perform this conversion but ironically
did not recognize the standard command form, only the
the unpreferred "implication-based" command form.

"lvconvert --type linear VG/MirrorLV" would fail, but
"lvconvert --mirrors 0 VG/MirrorLV" would succeed.
2016-07-06 16:33:25 -05:00
4d1c4e1f73 vgcreate: allow pvcreate force option
Commit a9940bd3c9 began disallowing the -f (force) option
to apply to the implicit pvcreate.  Make it allowed again.
2016-07-06 14:10:53 -05:00
351bcf5f82 man: clarify lvcreate size in extents 2016-07-06 11:35:50 -05:00
f6b98ec7ca post-release 2016-07-06 17:04:25 +01:00
8ca874bc1f pre-release 2016-07-06 16:55:44 +01:00
bf1dfea393 libdm: check for empty aux_data in _parse_aux_data_group()
If after extracting stats arguments and group tags nothing remains
of aux_data but '-' set the region->aux_data field to the empty
string to match behaviour for non-grouped regions.
2016-07-06 16:31:30 +01:00
c1a66d4fc6 coverity: Fixes for recent changes. 2016-07-06 16:09:32 +01:00
a497b95db1 libdm: use log_err_once() for group histogram message 2016-07-06 11:16:12 +01:00
28658541da libdm: do not permit grouping regions with histograms
Although not harmful do not allow a group containing regions with
histograms since it is not currently possible to present histogram
data aggregated for the group.
2016-07-06 11:10:23 +01:00
1faa208067 dmstats: simplify nr_areas calculation (CWE-561)
Eliminate dead conditional (step cannot be zero).

Fixes commit 988ca74.
2016-07-06 09:59:45 +01:00
21b946dfb7 dmstats: fix 'obj_type' field width
The header for 'obj_type' was changed from 'Object Type' to
'ObjType': update the minimum field width to match this change.
2016-07-06 09:37:59 +01:00
95ef0cdb46 libdm: check non-zero io count in _average_{rd,wr}_wait_time (Coverity)
Although a non-zero value for the number of ticks spent doing IO
should imply a non-zero number of IOs in the interval test for
this explicitly to avoid a divide-by-zero in the event of bad
counter data.
2016-07-06 09:23:13 +01:00
03e03e9c11 libdm: test for zero interval_ns in _utilization() (Coverity)
It's possible for interval_ns to be zero if the interval is not
set or the clock is misconfigured. Test for this before using the
value as the divisor in the utilisation calculation.
2016-07-06 09:14:43 +01:00
5d3b136d38 libdm: restore missing braces in _stats_walk_end_areas
Jumping to the end of the region table must only happen if there
are no more present, non-skipped regions, and no group walk is
configured to begin.
2016-07-06 09:04:13 +01:00
69c721dd68 libdm: fix mask leak in dm_bitset_parse_list
If an unexpected '-' is found jump to the error branch so that the
mask is properly freed before returning.
2016-07-06 08:59:09 +01:00
fb0a671419 post-release 2016-07-06 01:14:33 +01:00
6022715c81 pre-release 2016-07-06 00:59:28 +01:00
dfcdfa057b vgsplit: Don't skip moving internal snapshot LV.
Also place snapshot LV handling back at the end, after all possible
origin and cow LVs got dealt with.
2016-07-05 23:08:14 +01:00
4d4f48af9f libdm: cast walk flags to uint64_t when logging.
Walk flags are ULL constants; cast the result to a uint64_t before
logging with a FMTx64 format specifier to avoid a compiler warning:

  warning: format ‘%lx’ expects argument of type ‘long unsigned int’,
  but argument 5 has type ‘long long unsigned int’
2016-07-05 20:45:24 +01:00
f1dd0258f1 libdm: ensure flags constants have ULL suffix
The walk flags used by libdm-stats use the upper portion of a 64b
value: use the ULL suffix to ensure the compiler knows the expected
size.
2016-07-05 20:21:49 +01:00
93034d0b69 doc: document --area, --region, and --group in dmstats.8.in 2016-07-05 19:53:17 +01:00
e9c6fd3cff dmstats: fix <backtrace> in _display_info_cols()
Remove a false <backtrace> in _display_info_cols(): it is not an
error if there are no regions to display.

Fixes commit e6724f03.
2016-07-05 19:53:17 +01:00
0f64f2d5fc libdm: fix <backtrace> in dm_stats_populate 2016-07-05 19:53:17 +01:00
53e92441a6 libdm: fix <backtrace> in dm_stats_get_nr_regions 2016-07-05 19:53:17 +01:00
cf0fa3d693 dmstats: rename --auxdata to --userdata 2016-07-05 19:53:17 +01:00
14b74c360f dmstats: rename 'aux_data' to 'user_data'
Make it clear that the "aux data" presented in reports is the user
data stored in the field (and does not include any library-internal
state such as group descriptors) by renaming the field to user_data
and changing the heading to "UserData".
2016-07-05 19:53:17 +01:00
fef4832a85 libdm: clarify library's use of aux_data
Make it clear in libdevmapper.h, and in function argument names, that
libdm-stats uses the aux_data field internally and that any values set
for user_data are appended to the library values before being stored
with a region, and similarly, that internal data fields will be stripped
prior to returning any previously stored user_data.
2016-07-05 19:53:17 +01:00
2b0dd0b051 dmstats: replace --statstype with separate object switches
Replace --statstype=area,region,group with a separate switch for
each object type: --area, --region, --group. Omitting any object
type switch will use the defaults for the current command (regions
and groups for list, and regions, groups and areas for verbose list).
2016-07-05 19:53:17 +01:00
b926511b4b dmstats: add 'statsname' and 'obj_type' to default stats fields 2016-07-05 19:53:17 +01:00
0b05e4a874 dmstats: rename 'type' field to 'obj_type'
Rename the field and remove whitespace from the column heading:

  "Object Type" -> "ObjType"
2016-07-05 19:53:17 +01:00
c014425b6f dmstats: use 'statsname' and 'groupid' in default fields
Replace the 'name' field with 'statsname' in order to report alias
names for groups, and include the 'group_id' field between statsname
and the 'region_id' field to make it clear to the user when groups
are in use.
2016-07-05 19:53:17 +01:00
b0964acadf dmstats: convert 'delete' to dm_stats_foreach_region() 2016-07-05 19:53:16 +01:00
01cc11d9f8 dmstats: convert 'print' to dm_stats_foreach_region() 2016-07-05 19:53:16 +01:00
2047b8e565 dmstats: convert 'clear' to dm_stats_foreach_region() 2016-07-05 19:53:16 +01:00
f403ac8bf0 doc: update dmstats.8.in for groups 2016-07-05 19:53:16 +01:00
cf6c1665f1 dmstats: fix region deletion message
Make the use of 64-bit format macros consistent with other usage
and end the message with a '.'.
2016-07-05 19:53:16 +01:00
e554e375ae dmstats: accept --groupid for 'dmstats delete'
Allow deletion of a group and all the regions it contains with a
single 'dmstats delete' command.
2016-07-05 19:53:16 +01:00
837e7e513b dmstats: allow --statstype to override report defults 2016-07-05 19:53:16 +01:00
a2bf3c6ee8 dmstats: report a list of members as a group's region_id
Instead of '-' print the member list in range notation (as stored
in aux_data).
2016-07-05 19:53:16 +01:00
ca0a4cecec dmstats: report groups and region summaries
Walk avaiable groups and regions (in addition to areas) and report
aggregate statistics and properties.

A new switch is added to filter the type of obects inclued in the
report:

  --statstype={all,area,region,group}

The type of the current row is also available in a new
DR_STATS_META field 'type'.
2016-07-05 19:53:16 +01:00
8b179e09a4 dmstats: do not walk regions if deleting a single id 2016-07-05 19:53:16 +01:00
402d840aa7 dmstats: add stats_name field
To allow the names used to describe statistics report objects to
change (for e.g to support groups and region and group aliases)
introduce a new "stats_name" field that evaluates to the correct
name for the object being reported.
2016-07-05 19:53:16 +01:00
b55daa28e8 dmstats: add group alias support 2016-07-05 19:53:16 +01:00
0761863e28 dmstats: add 'group' and 'ungroup' commands
Add a pair of commands to create and delete stats groups:

  dmstats group --regions REGIONS

  dmstats ungroup --groupid ID

REGIONS specifies a list of regions to be included in the group.
Regions are specified as a comma separated list in order of
increasing region ID. Ranges may be specified as a hypen separated
pair of values giving the first and last member of the range.
2016-07-05 19:53:16 +01:00
b4cbc8f283 dmstats: add group_id report field type 2016-07-05 19:53:16 +01:00
cda1622fef libdm: allow deleting regions with dm_stats_delete_group()
Add a flag to dm_stats_delete_group() to allow optional deletion
of all regions belonging to the group being removed.
2016-07-05 19:53:16 +01:00
f1f2df7bc0 libdm: add stats group and region iterators and properties
Add support do dm_stats_walk*() to walk over the set of
available groups using the cursor embedded in the dm_stats
handle, and to obtain the type of the object at the current
stats cursor location. A set of flags is introduced to
control which objects are visited:

    DM_STATS_WALK_AREA
    DM_STATS_WALK_REGION
    DM_STATS_WALK_GROUP
    DM_STATS_WALK_ALL

A final flag suppresses visits to regions that contain only a
single area - since the aggregate of such a region is idential
to the area it contains this allows these duplicates to be
filtered out:

    DM_STATS_WALK_SKIP_SINGLE_AREA

If flags are not initialised before beginning a walk the default
set matches the behaviour of previous versions of the library.

Also accept group identifiers as immediate arguments to the
counter, metric, and property functions by adding control
flags to the region and area identifiers passed in.

Region and area properties are mapped to their equivalents for
the group (for example: group size is reported as the sum of
all regions contained in the group). Counter and metric values
are aggregated for the region or group.
2016-07-05 19:53:16 +01:00
62050760aa libdm: use defined constants for buffer sizes
Introduce constants for the buffer sizes that libdm-stats uses:
one for messages sent to the kernel, one for rows of response data
returned, and a pair for the "start+len" range and histogram bounds
strings.
2016-07-05 19:53:16 +01:00
2cb9794da2 libdm: add statistics groups
Add a grouping facility to the libdm-stats library that allows the
user to bind several regions together as a group. Groups may be
used to aggregate data from several regions for reporting, or to
select and sort among large sets of regions.

A textual descriptor ("group tag") is associated with each group
and is stored in the first group member's aux_data field. The
tag contains the group member list and an optional alias for the
group, allowing the user to assign meaningful names to groups of
regions.

These descriptors are parsed in @stats_list message responses and
populate the resulting region and area tables with the group
structure.

Groups with overlapping regions are permitted but since this will
result in some events being counted more than once a warning is
printed in this case.

Nested and overlapping groups are not currently supported and
attempting to create these configurations results in error.
2016-07-05 19:53:16 +01:00
4cd3dcbbc2 libdm: rename 'region' to 'skip_region' in _stats_walk_next
In libdm-stats.c 'region' usually refers to a 'struct region*'.
Rename the argument to _stats_walk_start to avoid confusion.
2016-07-05 19:53:16 +01:00
82e5766062 libdm: add enum based counter and metric calls
Add a new enum based interface for accessing counter and metric
values that uses a single function for each:

uint64_t dm_stats_get_counter(const struct dm_stats *dms,
                              dm_stats_counter_t counter
                              uint64_t region_id, uint64_t area_id);

int dm_stats_get_metric(const struct dm_stats *dms, int metric,
                        uint64_t region_id, uint64_t area_id,
                        double *value);

This simplifies the implementation of value aggregation for
groups of regions. The named function interface now calls the
enum interface internally so that all new functionality is
available regardless of the method used to retrieve values.
2016-07-05 19:53:16 +01:00
69f808ac8d libdm: cache dm name in stats handle
Cache the device-mapper name of a bound device in the dm_stats
handle.

This will be used by stats groups to report a device name or
user defined alias for groups.
2016-07-05 19:53:16 +01:00
4a66f02f88 libdm: rename dm_stats name, devno and uuid members
The device-mapper name, device numbers and uuid stored in the
dm_stats handle are used only to bind the handle to a specific
device in order to issue ioctls.

Rename them to "bind_*" to reflect this usage in preparation
for caching the device-mapper name of the bound device in the
dm_stats handle.

This will be used to allow optional aliases to be set for
dmstats groups.
2016-07-05 19:53:16 +01:00
81fad9e853 libdm: add dm_bitset_parse_list()
Add a function to parse a list of integer values and ranges into
a dm_bitset representation. Individual values signify that that bit
is set in the resulting mask and ranges are given as a pair of
start and end values, M-N, such that M and N are the first and
last members of the range (inclusive).

The implementation is based on the kernel's __bitmap_parselist()
that is used for cpumasks and other set configuration passed in
string form from user space.
2016-07-05 19:53:16 +01:00
d382e66035 libdm: fix histogram pool user-after-free (CWE-825) 2016-07-05 19:53:15 +01:00
4420d41fea vgsplit: fix moving RAID LVs to split off VG and check for LVs not to skip moving with other LV types 2016-07-05 19:49:44 +01:00
e5d1f3d6c5 tests: using mkfs config file
Use more predictable local config when creating ext4.
2016-07-04 17:41:10 +02:00
2063d6bb06 tests: add line for mixing dmeventd with log
TODO: it might be better to log dmeventd messages with test output
just like we do with clvmd - maybe we will switch to this one
instead of extra  DMEVENTD log file in future....
2016-07-04 17:41:09 +02:00
b91390c211 tests: add mke2fs.conf
Add config for mkfs to get more predicatable results
when using mkfs across variety of distributions.

In future maybe use this per all tests as default.
For now user has to specify in a test MKE2FS_CONFIG envvar to use it.
2016-07-04 17:40:25 +02:00
2981d1e798 tests: try to force remove higher minor first
When force removing thin-pool we loose 'real' access to hidden device,
and if such pool is in suspended state, any thin volume cannot be
dropped. It likely should be also checked by dmsetup, but meanwhile
apply simple logic -  try to force remove first all higher minors first
with assumption we first create thin-pool and then thin volume
and there are usually not being released lower dm numbers to
get the order wrong.
2016-07-04 17:40:24 +02:00
c0a505b0bb cleanup: drop unused header files 2016-07-04 17:40:24 +02:00
adc1fe4b3f dmeventd: improved logged messages from thin plugin
Show better names in logged messages.
2016-07-04 17:40:24 +02:00
52be93c54b dmsetup: fix timestamp leak
With a single report (--count=1) no timerfd is set up and the cycle
and current timestamps should be freed during the single call to
_update_interval_times().
2016-07-04 12:16:51 +01:00
62dce13c7a dmstats: fix RgStart and RgSize field widths 2016-07-04 12:16:51 +01:00
f27e95b25a docs: remove obsolete note from dmstats.8.in 2016-07-04 12:16:50 +01:00
d8c2677ab9 raid0: Add raid0_meta segment type. 2016-07-01 22:20:54 +01:00
1df9822224 lvconvert: improve arg checks in new operation routing code
Use defines for segment types, and test args directly
instead of indirectly.
2016-07-01 11:24:41 -05:00
b0d8a524a2 tests: test foreign users of thin-pool
Note: dmeventd should not need any notification and automatically
try to resize again when there is some metadata change.
2016-07-01 00:44:49 +02:00
37a33d7414 cleanup: warns from older gcc 2016-07-01 00:44:48 +02:00
3fd4584886 cleanup: lvchange uses display_lvname
Convert messages to report vg/lv name consistently.

Also drop unneeded 'info_obtaned' variable since the
obtained info is not reused in any code path.
2016-07-01 00:44:48 +02:00
b9d3e8c8a8 cleanup: drop unused assignments
In all code paths we set a value for these variables, so drop
their initial unused assign.
2016-07-01 00:44:48 +02:00
1e3411aa37 cleanup: add extra test for argc==0
Cleaup some compiler warning about posibility to allocate 0 size.
2016-07-01 00:44:48 +02:00
458918b319 thin: fix link validation for unused thin-pool
This patch fixes link validation for used thin-pool.
Udev rules correctly creates symlinks only for unused new thin-pool.
Such thin-pool can be used by foreing apps (like Docker) thus
has  /dev/vg/lv link.
However when thin-pool becomes used by thinLV - this link is no
longer exposed to user - but internal verfication missed this
and caused messages like this to be printed upon 'vgchange -ay':

The link /dev/vg/pool should have been created by udev but it was not
found. Falling back to direct link creation.

And same with 'vgchange -an':
The link /dev/vg/pool should have been removed by udev but it is still
present. Falling back to direct link removal.

This patch ensures only unused thin-pool has this link.
2016-07-01 00:44:46 +02:00
2f638e07e8 dmeventd: thin plugin umount over 95%
Run umount code only when either thin data or metadata are
above 95% - so if there are resize failures with 60%.
system fill keep running.

Also umount will only be tried with lvm2 LVs.
Foreign users are ATM unsuppored.
2016-07-01 00:43:45 +02:00
103c188681 lvconvert: add comments describing conversions 2016-06-30 17:08:50 -05:00
aed8bc8ae7 macros: Use is_power_of_2. 2016-06-30 17:59:44 +01:00
a8e39530ef lvconvert: add missing alias for a thin-pool conversion
The case of converting a cache volume to a thin pool missed
recognizing the --thinpool alias for --type thin-pool.
2016-06-30 10:09:54 -05:00
802ed9d459 lvconvert: remove unused code
This code became unused with the previous commit 2282f5.
2016-06-29 16:59:32 -05:00
2282f53ac7 lvconvert: rework routing of operations
Add new logic to identify each unique operation and route
it to the correct function to perform it.  The functions
that perform the conversions remain unchanged.

This new code checks every allowed combination of LV type
and requested operation, and for each valid combination
calls the function that performs that conversion.

The first stage of option validation which checks for
incompatible combinations of command line options, is done
done before process_each is called.  This is unchanged.
(This new code will allow that first stage validation to
be simplified in a future commit.)

The second stage of checking options against the specific
LV type is done by this new code.  For each valid combination
of operation + LV type, the new code calls an existing
function that implements it.

With this in place, the ad hoc checks for valid combinations
of LV types and operations can be removed from the existing
code in a future commit.

(The #if 0 is used to keep the patch clean, and the
disabled code will be removed by a following patch.)
2016-06-29 16:55:27 -05:00
eac0706761 libdm: do not issue 'Failed to create directory' message for failure in dm_create_dir
There are detailed messages inside _create_dir_recursive that
dm_create_dir calls (except EROFS which where the message is not
generated, like anywhere else in the code).
2016-06-29 15:58:18 +02:00
686acce23f lvconvert: Conversions between striped and raid0. 2016-06-28 23:44:15 +01:00
6f216692b4 lvmdbustest: Comment out refresh check for LV create
When we test Vg.LvCreateRaid some of the hidden LVs volume type go from
'I' to 'i' between the time it takes us to create the LV and
the time it takes to call into refresh to verify the service is up to date.
This is a fairly rare occurance.
2016-06-28 13:36:32 -05:00
1d3532d0a7 lvmdbusd: Add --nojson command line option
Add ability to not use the JSON output even if available.
2016-06-28 13:32:39 -05:00
e6e5c3d3ec lvmdbusd: Remove WARNING for 'lvm help'
We call 'lvm help' to find out if fullreport is supported.  Lvm
dumps help to stderr.  Common code prints a warning if we exit
with 0, but have something in stderr so we are skipping the warning
message.
2016-06-28 12:54:48 -05:00
7c5a08521b lvmdbusd: Remove unneeded comment 2016-06-28 12:45:55 -05:00
9e3ad37828 lvmdbusd: Clean up ws 2016-06-28 12:45:28 -05:00
c11003c860 lvmdbusd: Remove unused imports and function parameter 2016-06-28 12:44:45 -05:00
dd5d865020 lvmdbusd: Fix hang when lvm compiled with 'enable-notify-dbus'
The following operations would hang if lvm was compiled with
'enable-notify-dbus' and the client specified -1 for the timeout:

* LV snapshot merge
* VG move
* LV move

This was caused because the implementation of these three dbus methods is
different.  Most of the dbus method calls are executed by gathering information
needed to fulfill it, placing that information on a thread safe queue and
returning.  The results later to be returned to the client with callbacks.
With this approach we can process an arbitrary number of commands without any
of them blocking other dbus commands.  However, the 3 dbus methods listed
above did not utilize this functionality because they were implemented with a
separate thread that handles the fork & exec of lvm.  This is done because these
operations can be very slow to complete.  However, because of this the lvm
command that we were waiting on is trying to call back into the dbus service to
notify it that something changed.  Because the code was blocking the process
that handles the incoming dbus activity the lvm command blocked.  We were stuck
until the client timed-out the connection, which then causes the service to
unblock and continue.  If the client did not have a timeout, we would have been
hung indefinitely.

The fix is to always utilize the worker queue on all dbus methods.  We need to
ensure that lvm is tested with 'enable-notify-dbus' enabled and disabled.
2016-06-28 12:09:28 -05:00
5274c2f11b lvmdbusd: request.py, initialize _job to None
_job is a job object, not a boolean so initialize it to None instead.
2016-06-28 12:09:28 -05:00
4f26eae40f lvmdbusd: Correct pv_seg_start -> pvseg_start
Code was using the incorrect column names for pvseg_start which only
became apparent when utilizing the JSON.
2016-06-28 12:09:28 -05:00
0aadd6b0fb lvmdbusd: Correct command line args for JSON
Use the updated syntax.
2016-06-28 12:09:28 -05:00
4b337b20d4 lvmdbusd: Remove sorting in db layer
When using the JSON this does not yield a totally sorted list as we don't
have a complete set of LVs, so remove this sort.
2016-06-28 12:09:28 -05:00
e514284c65 lvmdbusd: Add hidden in for json too 2016-06-28 12:09:28 -05:00
ec45be9976 lvmdbusd: Initial support for json output 2016-06-28 12:09:28 -05:00
79446ffad7 raid: Infrastructure for raid takeover. 2016-06-28 02:42:30 +01:00
ff3c4ed1c0 lvmetad: two phase vg_remove
Apply the same idea as vg_update.
Before doing the VG remove on disk, invalidate
the VG in lvmetad.  After the VG is removed,
remove the VG in lvmetad.  If the command fails
after removing the VG on disk, but before removing
the VG metadata from lvmetad, then a subsequent
command will see the INVALID flag and not use the
stale metadata from lvmetad.
2016-06-28 02:30:36 +01:00
a7c45ddc59 lvmetad: two phase vg_update
Previously, a command sent lvmetad new VG metadata in vg_commit().
In vg_commit(), devices are suspended, so any memory allocation
done by the command while sending to lvmetad, or by lvmetad while
updating its cache could deadlock if memory reclaim was triggered.

Now lvmetad is updated in unlock_vg(), after devices are resumed.
The new method for updating VG metadata in lvmetad is in two phases:

1. In vg_write(), before devices are suspended, the command sends
   lvmetad a short message ("set_vg_info") telling it what the new
   VG seqno will be.  lvmetad sees that the seqno is newer than
   the seqno of its cached VG, so it sets the INVALID flag for the
   cached VG.  If sending the message to lvmetad fails, the command
   fails before the metadata is committed and the change is not made.
   If sending the message succeeds, vg_commit() is called.

2. In unlock_vg(), after devices are resumed, the command sends
   lvmetad the standard vg_update message with the new metadata.
   lvmetad sees that the seqno in the new metadata matches the
   seqno it saved from set_vg_info, and knows it has the latest
   copy, so it clears the INVALID flag for the cached VG.

If a command fails between 1 and 2 (after committing the VG on disk,
but before sending lvmetad the new metadata), the cached VG retains
the INVALID flag in lvmetad.  A subsequent command will read the
cached VG from lvmetad, see the INVALID flag, ignore the cached
copy, read the VG from disk instead, update the lvmetad copy
with the latest copy from disk, (this clears the INVALID flag
in lvmetad), and use the correct VG metadata for the command.

(This INVALID mechanism already existed for use by lvmlockd.)
2016-06-28 02:30:31 +01:00
cc3e7c7c31 lvmetad: remove unused code for other format types
lvmetad is no longer used at all with the lvm1 format,
so the text format is the only one that uses lvmetad.
2016-06-28 02:30:25 +01:00
5a327755b4 WHATS_NEW: add recent changes 2016-06-28 02:28:57 +01:00
17ad29ebba lvmlockd: fix coverity report 2016-06-28 02:28:49 +01:00
3985b12a2d libdm: report: fix field width calculation when using dm_report_column_headings
This fixes commit 0ba5f4b8e9 which moved
field recalculation (field width and sort position) from
dm_report_object to dm_report_output but it didn't handle the case when
dm_report_column_headings was used separately to report headings (before
dm_report_outpout call) and hence we ended up with intial widths for
fields in the headings.

If we're using dm_report_column_headings, we need to recalculate
fields if we haven't done so yet, the same way as we do in
dm_report_output.
2016-06-28 02:28:40 +01:00
1b11f09d2a reporter: simplify --configreport handling for -S|--select and fix an issue reported by coverity
Simplify code around _do_get_report_selection - remove "expected_idxs[]"
argument which is superfluous and add "allow_single" switch instead to
allow for recognition of "--configreport <report_name> -S" as well as
single "-S" if needed.

Null pointer dereferences  (FORWARD_NULL) /safe/guest2/covscan/LVM2.2.02.158/tools/reporter.c: 961 in _do_report_get_selection()
Null pointer dereferences  (FORWARD_NULL) Dereferencing null pointer "single_args".
2016-06-28 02:27:19 +01:00
f0768f636e coverity: fix issues detected in recent code
Uninitialized variables  (UNINIT) /safe/guest2/covscan/LVM2.2.02.158/tools/toollib.c: 3520 in _process_pvs_in_vgs()
Uninitialized variables  (UNINIT) Using uninitialized value "do_report_ret_code".

Null pointer dereferences  (REVERSE_INULL) /safe/guest2/covscan/LVM2.2.02.158/libdm/libdm-report.c: 4745 in dm_report_output()
Null pointer dereferences  (REVERSE_INULL) Null-checking "rh" suggests that it may be null, but it has already been dereferenced on all paths leading to the check.

Incorrect expression  (MISSING_COMMA) /safe/guest2/covscan/LVM2.2.02.158/lib/log/log.c: 280 in _get_log_level_name()
Incorrect expression  (MISSING_COMMA) In the initialization of "log_level_names", a suspicious concatenated string ""noticeinfo"" is produced.

Null pointer dereferences  (FORWARD_NULL) /safe/guest2/covscan/LVM2.2.02.158/tools/reporter.c: 816 in_get_report_options()
Null pointer dereferences  (FORWARD_NULL) Comparing "mem" to null implies that "mem" might be null.
2016-06-28 02:26:54 +01:00
a46f524247 post-release 2016-06-25 20:47:49 +01:00
887f071b25 pre-release 2016-06-25 20:35:14 +01:00
15b932a70e doc: Resync kernel docs. 2016-06-25 19:59:49 +01:00
d914151591 man: lvs: move doc about --all so it's ordered alphabetically in the man page 2016-06-24 14:57:09 +02:00
a910052a2e man: document --configreport, --logonly, --reportformat 2016-06-24 14:51:20 +02:00
9a414245b9 commands: help: add missing --reportformat references 2016-06-24 14:49:13 +02:00
14da3cc793 commands: fix typo in arg assignment 2016-06-24 11:10:10 +02:00
e88e9ee9ed cleanup: clean warns from older gcc
Don't report uninitialized use by older gcc.
2016-06-24 01:10:04 +02:00
5070e7fcf7 tests: update test for modified output
We now print  vg/lv  for lv resized volume
2016-06-24 00:39:15 +02:00
fc174f6b74 tests: smaller number of devs created to fill metadata 2016-06-24 00:39:14 +02:00
1c212371fa cleanup: type cleanup
Fix return code 1.
Since we always check for !() - this fix has no other effect.
2016-06-24 00:39:14 +02:00
7c921f18e2 lvresize: let pass even protected names like _tmeta
Only later validation can decide if the volume is actually restricted
from being resized  (unlike in lvcreate time).
2016-06-24 00:39:14 +02:00
1bb7a155d1 lvresize: fixes for recent commit
Merging process and patch rework missed some bits - fix them.
2016-06-24 00:39:14 +02:00
e99a31c950 Revert "locking: trace errors from dir creation"
This reverts commit fa69ed0bc8.

This code sometimes expects to be presented with a read-only filesystem
(during some boot sequences for example) and copes appropriately with
this and it should not lead to expected error messages that might cause
unnecessary alarm.
2016-06-23 21:31:49 +01:00
a67a5d4655 tests: aux prepare_thin_metadata 2016-06-23 14:59:29 +02:00
83d483269d cleanup: drop setting lv_name
lv_name arg is only used without known LV for resolving '*lv'.
Once we know *lv, never use  lv_name ever again.

So setting it when passing *lv has not needed.
2016-06-23 14:59:29 +02:00
e5b7ebcdda cleanup: remove unused code 2016-06-23 14:59:29 +02:00
5a919e4805 cleanup: remove unused sizearg variable
It's not used for anything now.
2016-06-23 14:59:29 +02:00
4de15aa58d lvresize: return 0/1
Returning locking LV is no longer used from here, so return 1/0.
2016-06-23 14:59:29 +02:00
7092c6ba10 lvresize: support more resized LVs
Add code to support more LVs to be resized through a same code path
using a single lvresize_params struct.
(Now it's used for thin-pool metadata resize,
next user will be snapshot virtual resize).

Update code to adjust percent amount resize for use_policies.

Properly activate inactive thin-pool in case of any pool resize
as the command should not 'deffer' this operation to next activation.
2016-06-23 14:59:27 +02:00
d44e653fe1 lvresize: do not pass struct cmd
Use common API design and pass just LV pointer to lv_manip.c functions.
Read cmd struct via    lv->vg->cmd when needed.
Also do not try to return EINVALID_CMD_LINE error when we
have already openned VG - this error code can only be returned before
locking VG.
2016-06-23 14:57:09 +02:00
5013999c8b lvresize: pass only needed params to _fsadm_cmd
Do not pass whole lvresize_params into _fsadm_cmd,
and give it only needed args.
2016-06-23 14:57:09 +02:00
d30c2cec88 lvresize: check pvh list is vg->pvs
Instead of checking lp->argc for arg count, compare directly whether
passed pvh is vg->pvs.
2016-06-23 14:57:09 +02:00
f45b689406 lvresize: update lvresize_params struct
Reorganise  struct lvresize_params to better fit lvresize needs to be
able to resize more then just a single LV.
2016-06-23 14:57:09 +02:00
698082e678 cleanup: use display_lvname 2016-06-23 14:57:08 +02:00
6268d0a080 cleanup: add dots to some messages
Add missing dots and one comment.
2016-06-23 14:57:08 +02:00
0a525832f9 cleanup: code lines reodered 2016-06-23 14:57:08 +02:00
3a4107c982 lvresize: drop extra sigint handling
yes_no_prompt() now already handles signal checking,
so drop redundant test.
2016-06-23 14:57:08 +02:00
d578d8d3a1 lvresize: inform about ignored args with --use-polices
When --use-polices is specified, all size args are meaningless,
as the resize is based upon policy. So just keep user informed.
2016-06-23 14:57:08 +02:00
58d414f7f5 lvresize: move and extend resizefs ignoring check
Move check for 'ignoring' --resizefs option and extend check
for some more types.
2016-06-23 14:57:08 +02:00
fa69ed0bc8 locking: trace errors from dir creation 2016-06-23 14:57:06 +02:00
dc8c5c1886 monitoring: preserve monitoring status during update
Ignore monitoring during whole update (suspend/resume) of thin-pool.
2016-06-23 14:56:10 +02:00
eb51be4fbe activation: _lv_active returns 0 on error
We have only 2 users of _lv_active() - one was already checking for ==1
while the other use (_lv_is_active()) could have take '-1' as a sign of having
an LV active. So return 0 and log_debug also the reason while detection
has failed (i.e. in case  --driverload n  - it's kind of expectable,
but might have confused user seeing just <backtrace>).
2016-06-23 14:55:35 +02:00
af36f5ad36 activation: switch to warning
Since this function does not have a way to return error use correct
reporting level as warning.
2016-06-23 14:53:59 +02:00
751163a743 libdm: log: remove log_print_bypass_report calls and register new print_log_libdm for libdm during lvm initialization instead
This fixes commit f50d4011cd which
introduced a problem when using older lvm2 code with newer libdm.
In this case, the old LVM didn't recognize new _LOG_BYPASS_REPORT flag
that libdm-report code used. This ended up with no output at all
from libdm where log_print_bypass_report was called because the
_LOG_BYPASS_REPORT was not masked properly in lvm2's print_log fn
which was called as callback function for logging.

With this patch, the lvm2 registers separate print_log_libdm logging
function for libdm instead. The print_log_libdm is exactly the same
as print_log (used throughout lvm2 code) but it checks whether we're
printing common line on output where "common" means not going to stderr,
not a warning and not an error and if we are, it adds the
_LOG_BYPASS_REPORT flag so the log_print goes directly to output, not
to any log report.

So this achieves the same goal as in f50d4011cd,
just doing it in a way that newer libdm is still compatible with older
lvm2 code (libdm-report is the only code using log_print).

Looking at the opposite mixture - older libdm with newer lvm2 code,
that won't be compilable because the new log report functionality
that is in lvm2 also requires new dm_report_group_* libdm functions
so we don't need to care here.
2016-06-23 14:45:52 +02:00
6eeb66e51d log: move original print_log code to _vprint_log and make print_log a wrapper over _vprint_log
Move code from original print_log fn to a separate _vprint_log function
that accepts va_list and make print_log a wrapper over _vprint_log.
The print_log just initializes the va_list and uses it for _vprint_log
call now. This way, we can reuse _vprint_log if needed.
2016-06-23 14:45:52 +02:00
79eaaee50a filters: add comments about internal filter position in filter chain 2016-06-23 09:37:51 +02:00
6513a7a449 lvconvert: Fix --stripes handling.
Only treat --stripes as meaning --type striped if no other type was
first detected.  If a segtype got selected, don't override it later.
2016-06-22 22:10:42 +01:00
ebd2758dab vgimportclone: add native command
This is cleaner and more efficient than the script.
The args and usage are unchanged.
2016-06-22 13:13:10 -05:00
dfc516f9bf lvconvert: Refactor argument handling code.
Begin disentangling the different lvconvert modes of operation
from each other.
2016-06-22 18:40:22 +01:00
7e671e5dd0 tools: Use arg_is_set instead of arg_count. 2016-06-21 22:24:52 +01:00
6c269e639a vgcfgrestore: rescan to reenable lvmetad on error path
In commit 6ae22125, vgcfgrestore began disabling lvmetad
while running, and rescanned to enable it again at the end,
but missed the rescanning/enabling in the error case.
2016-06-21 11:40:42 -05:00
f96de67490 vgcfgrestore: check for missing device
The missing device will generally be seen earlier
and cause the command to not reach this point, but
check anyway for completeness.
2016-06-20 16:02:07 -05:00
47a29f6b2e lvmlockd: always try to connect to lvmetad
Reconnect to lvmetad if either the send fails (e.g. lvmetad
was restarted since lvmlockd last connected), or if no
lvmetad connection exists (e.g. lvmetad was started after
lvmlockd so no previous connection existed.)
2016-06-20 14:01:46 -05:00
b12961e7eb lvmetad: process new connections after shutdown signal
Currently, a shutdown signal will cause lvmetad to quit
responding to new connections, but not actually exit until
all connections are gone.  If a program is maintaining a
long running connection (e.g. lvmlockd, or even an lvm
command) when lvmetad gets a shutdown signal, then all
further commands will hang indefinately waiting for a
response that won't be sent.

With this patch, make lvmetad continue handling new
connections even after a shutdown signal.  It will exit
once all connections are gone.
2016-06-20 13:19:02 -05:00
6ae22125c6 vgcfgrestore: use lvmetad disabled state
Previously, vgcfgrestore would attempt to vg_remove the
existing VG from lvmetad and then vg_update to add the
restored VG.  But, if there was a failure in the command
or with vg_update, the lvmetad cache would be left incorrect.
Now, disable lvmetad before the restore begins, and then
rescan to populate lvmetad from disk after restore has
written the new VG to disk.
2016-06-20 11:19:49 -05:00
cae6591b9d vgscan: fix process_each args
zero/null args were mixed up.
2016-06-20 11:18:36 -05:00
d1d3820219 conf: add more comments for new settings related to output format and log report 2016-06-20 16:21:38 +02:00
99ea03571a cleanup: log: use hex numbers instead of decimal for _LOG_* 2016-06-20 14:22:31 +02:00
a77732c180 log: add 'label' log report object type; annotate process_each_label with log_set_report_object_{type, id_and_name} and report_log_ret_code 2016-06-20 14:05:13 +02:00
db6b4c1eef report: compare --configreport value with basic report type
Reporting commands can be of different types (even if the command name
is the same):
  - pvs command can be either of PVS, PVSEGS or LABEL report type,
  - vgs command is of VGS report type,
  - lvs command is of LVS or SEGS report type.

Use basic report type when looking for report prefix used for
--configreport option.

This means that:
  - 'pvs --configreport pv' applies to PVS, PVSEGS or LABEL report type
  - 'vgs --configreport vg' applies to VGS report type
  - 'lvs --configreport lv' applies to LVS and SEGS report type
2016-06-20 14:04:37 +02:00
2593cab5c4 commands: add --configreport arg for all relevant commands 2016-06-20 11:57:24 +02:00
083e538030 conf: regenerate profile templates 2016-06-20 11:33:43 +02:00
92caebab95 report: add --logonly arg to report only log for a command 2016-06-20 11:33:43 +02:00
3e8e8ddb46 report: use report type description for report's name if using DM_REPORT_GROUP_BASIC output format 2016-06-20 11:33:43 +02:00
5b93db6566 libdm: select: recognize special selection string 'all' as an alias for blank selection string 2016-06-20 11:33:43 +02:00
1127b090bd conf: add log/command_log_selection config setting 2016-06-20 11:33:43 +02:00
cee1aedf12 log: use separate 'orphan' report object type for orphan VGs 2016-06-20 11:33:43 +02:00
89e2aef63a tools: add 'lvm lastlog' command for interactive query and display of last command's log
If we're running in lvm shell, we can keep last command's log report
for further query with possible different selection criteria for easy
log lookup.
2016-06-20 11:33:43 +02:00
c33c0545af refactor: move 'interactive' field from struct command_line to struct cmd_context as 'is_interactive' switch 2016-06-20 11:33:43 +02:00
0ab1187740 log: annotate processing code with report_current_object_cmdlog 2016-06-20 11:33:43 +02:00
6ca28ca4c6 log: annotate processing code with log_set_report_{context,object_type,id_and_name} 2016-06-20 11:33:43 +02:00
1b107adc1d report: add 'multiple_output' arg to report_init
Some reports may be reported several times with possible different
selection criteria, just like command log report.
2016-06-20 11:33:43 +02:00
2078b842fb libdm: report: add dm_report_set_selection
Since we can do repeated dm_report_output calls now, we also like
to be able to set selection for each of these outputs.
2016-06-20 11:33:43 +02:00
f2facdc1d0 libdm: report: add DM_REPORT_OUTPUT_MULTIPLE_TIMES report flag to keep report data even after output is done
The DM_REPORT_OUTPUT_MULTIPLE_TIMES instructs reporting code to
keep rows even after dm_report_output call - the rows are not
destroyed in this case which makes it possible to call dm_report_output
multiple times.
2016-06-20 11:33:43 +02:00
0ba5f4b8e9 refactor: move field width calculation and sort preparation from _do_report_object to dm_report_output
This also prepares code for repeated dm_report_output calls.
2016-06-20 11:33:42 +02:00
102cc4c1e2 libdm: report: remember special field to display selection status in struct row's field_sel_status variable
This allows for moving parts of the code from dm_report_object to
dm_report_output which is important for subsequent patches that allow
for repeated dm_report_output, not destroying rows on each
dm_report_output call.
2016-06-20 11:33:42 +02:00
f50d4011cd log: also pass log_print through report and add log_print_bypass_report for use in libdm-report for direct print without report
log_print is used during cmd line processing to log the result of the
operation (e.g. "Volume group vg successfully changed" and similar).

We don't want output from log_print to be interleaved with current
reports from group where log is reported as well. Also, the information
printed by log_print belongs to the log report too, so it should be
rerouted to log report if it's set.

Since the code in libdm-report which is responsible for doing the report
output uses log_print too, we need to use a different kind of log_print
which bypasses any log report currently used for logging (...simply,
we can't call log_print to output the log report itself which in turn
would again reroute to report - the report would never get on output
this way).
2016-06-20 11:33:42 +02:00
fe63715f25 report: add report_current_object_cmdlog fn as a shortcut for reporting current object's log item 2016-06-20 11:33:42 +02:00
7d4a15e53a log: log warnings and errors via report if set; add log_set_report* fns
This patch adds structures and functions to reroute error and warning
logs to log report, if it's set.

There are 5 new functions:
  - log_set_report
    Set log report where logging will be rerouted.

  - log_set_report_context
    Set context globally so any report_cmdlog call will use it.

  - log_set_report_object_type
    Set object type globally so any report_cmdlog call will use it.

  - log_set_report_object_name_and_id
    Set object ID and name globally so any report_cmdlog call will use it.

  - log_set_report_object_group_and_group_id
    Set object group ID and name globally so any report_cmdlog call will use it.

These functions will be called during LVM command processing so any logs
which are rerouted to log report contain proper information about current
processing state.
2016-06-20 11:33:42 +02:00
8cfc385491 toollib: make it possible to also process internal VGs, add 'include_internal' switch to process_each_vg fn
The lvm fullreport works per VG and as such, the vg, lv, pv, seg and
pvseg subreport is done for each VG. However, if the PV is not part of
any VG yet, we still want to display pv and pvseg subreports for these
"orphan" PVs - so enable this for lvm fullreport's process_each_vg call.
2016-06-20 11:33:42 +02:00
31aaa3be71 report: check report type and options used for full report's subreports
If we have fullreport, make sure that the options/sort keys used for
each report doesn't change its type - we want to preserve the original
type so it's always 5 different subreports within fullreport (vg, lv, pv,
seg, pvseg). Since we have all report types within fullreport, users
should add fields under proper subreport type - this minimizes
duplication of info displayed on output.
2016-06-20 11:33:42 +02:00
b864a06221 report: recognize selection (-S|--select) for each subreport; make -S|--select groupable 2016-06-20 11:33:42 +02:00
e081203f3e report: recognize list of keys to sort report by (-O|--sort) for each subreport; make -O|--sort groupable 2016-06-20 11:33:42 +02:00
bd26684d5d report: recognize list of fields to report (-o|--options) for each subreport 2016-06-20 11:33:42 +02:00
80ffaefb88 report: add _get_report_idx_from_name and _should_process_report_idx helper fns
Prepare for recognition of cmd line options for each subreport within
one command.
2016-06-20 11:33:42 +02:00
28b4c48e2a args: add --configreport arg 2016-06-20 11:33:42 +02:00
d23c5b9318 args: add priorities for grouping args
Groupable args (the ones marked with ARG_GROUPABLE flag) start a new
group of args if:
  - this is the first time we hit such a groupable arg,
  - or if non-countable arg is repeated.

However, there may be cases where we want to give priorities when
forming groups and hence force new group creation if we hit an arg
with higher grouping priority.

For example, let's assume (for now) hypothetical sequence of args used:

  lvs -o lv_name --configreport log -o log_type --configreport lv -o +vg_name

Without giving any priorites, we end up with:

  lvs -o lv_name --configreport log -o log_type --configreport lv -o +vg_name
     |                            | |                           | |          |
     \__________GROUP1___________/   \________GROUP2___________/   \_GROUP3_/

This is because we hit "-o" as the first groupable arg. The --configreport,
even though it's groupable too, it falls into the previous "-o" group.

While we may need to give priority to the --configreport arg that should
always start a new group in this scenario instead:

  lvs -o lv_name --configreport log -o log_type --configreport lv -o +vg_name
      |         | |                            | |                           |
      \_GROUP1_/   \_________GROUP2___________/   \_________GROUP3__________/

So here "-o" started a new group but since "--configreport" has higher
priority than "-o", it starts fresh new group now and hence the rest of
the command line's args are grouped by --configreport now.
2016-06-20 11:33:42 +02:00
9c37b7ed7c conf: add report/{vgs,pvs,lvs,pvsegs,segs}_{cols,sort}_full config settings 2016-06-20 11:33:42 +02:00
26c43c6ce5 commands: report: add lvm fullreport command
lvm fullreport executes 5 subreports (vg, pv, lv, pvseg, seg) per each VG
(and so taking one VG lock each time) within one command which makes it
easier to produce full report about LVM entities.

Since all 5 subreports for a VG are done under a VG lock, the output is
more consistent mainly in cases where LVM entities may be changed in
parallel.
2016-06-20 11:33:42 +02:00
f1e7f35bb5 commands: recognize --reportformat option for other commands
Enables --reportformat option for all command using processing_handle
(and process_each_* fn variant), that is: lvchange, lvcreate, lvdisplay,
lvextend, lvreduce, lvremove, lvrename, lvresize, lvscan, pvchange,
pvresize, pvcreate, pvdisplay, pvmove, pvremove, pvscan, vgcfgbackup,
vgchange, vgck, vgconvert, vgcreate, vgdisplay, vgexport, vgextend,
vgimport, vgmknodes, vgreduce, vgremove, vgrename command.
2016-06-20 11:33:42 +02:00
f8a93763e5 commands: recognize --reportformat option for pvs,vgs,lvs and devtypes command
Enables --reportformat options for pvs, vgs, lvs, devtypes command.
2016-06-20 11:33:41 +02:00
10a1b9e182 report: add current report to existing group
Add any report (pvs/vgs/lvs) currently processed to current report group
which is part of processing handle and which already contains log
report. This way both log report and pvs/vgs/lvs report will be
reported as a whole within a group, thus having same output format as
selected by --reportformat option.
2016-06-20 11:33:41 +02:00
f752a95302 toollib: add 'parent' field to processing_handle; init report format only if there's no parent
If there's parent processing handle, we don't need to create completely
new report group and status report - we'll just reuse the one already
initialized for the parent.

Currently, the situation where this matter is when doing internal report
to do the selection for processing commands where we have parent processing
handle for the command itself and processing handle for the selection
part (that is selection for non-reporting tools).
2016-06-20 11:33:41 +02:00
c099f531fb toollib: add report_group and log_rh to processing_handle and initialize cmd processing log report
Wire up report group creation with log report in struct
processing_handle and call report_format_init during processing handle
initialization (init_processing_handle fn) and destroy it while
destroing processing handle (destroy_processing_handle fn).

This way, all the LVM command processing using processing handle
has access to log report via which the current command log
can be reported as items are processed.
2016-06-20 11:33:41 +02:00
213434d426 report: separate common report and per-report args
Separating common report and per-report arguments prepares the code for
handling several reports per one command (for example, the command log
report and LVM command report itself).

Each report can have sort keys, options (fields), list of fields to
compact and selection criteria set individually. Hooks for setting these
per report within one command will be a part of subsequent patches, this
patch only separates new struct single_report_args out of existing
struct report_args.
2016-06-20 11:33:41 +02:00
bd0a0ae36b conf: add log/report_command_log config setting 2016-06-20 11:33:41 +02:00
a08e02afbf conf: add report/output_format config setting
New report/output_format configuration sets the output format used
for all LVM commands globally. Currently, there are 2 formats
recognized:
   - basic (the classical basic output with columns and rows, used by default)
   - json (output is in json format)
2016-06-20 11:33:41 +02:00
79a74e9aae toollib: add report_format_init fn to create report group and to create/add log report handle
Add new --reportformat option and new report_format_init function that
checks this option and creates new report group accordingly, also
preparing log report handle and adding it to the report group just
created.
2016-06-20 11:33:41 +02:00
c36d4632a6 conf: add log/command_log_{sort,cols} config settings 2016-06-20 11:33:40 +02:00
99c2a2b960 report: add CMDLOG report type
This is a preparation for new CMDLOG report type which is going to be
used for reporting LVM command log.

The new report type introduces several new fields (log_seq_num, log_type,
log_context, log_object_type, log_object_group, log_object_id, object_name,
log_message, log_errno, log_ret_code) as well as new configuration settings
to set this report type (report/command_log_sort and report/command_log_cols
lvm.conf settings).

This patch also introduces internal report_cmdlog helper function
which is a wrapper over dm_report_object to report command log via
CMDLOG report type and which is going to be used throughout the code
to report the log items.
2016-06-20 11:33:08 +02:00
094fce3776 libdm: report: implement DM_REPORT_GROUP_JSON for JSON report output
This patch introduces DM_REPORT_GROUP_JSON report group type. When using
this group type and when pushing a report to such a group, these flags
are automatically unset:

   DM_REPORT_OUTPUT_ALIGNED
   DM_REPORT_OUTPUT_HEADINGS
   DM_REPORT_OUTPUT_COLUMNS_AS_ROWS

...and this flag is set:

   DM_REPORT_OUTPUT_BUFFERED

The whole group is encapsulated in { } for the outermost JSON object
and then each report is reported on output as array of objects where
each object is the row from report:

  {
     "report_name1": [
         {field1="value", field2="value",...},
         {field1="value", field2="value",...}
         ...
     ],
     "report_name2": [
         {field1="value", field2="value",...},
         {field1="value", field2="value",...}
         ...
     ]
     ...
  }
2016-06-20 10:42:26 +02:00
230b7ff0f6 libdm: report: implement DM_REPORT_GROUP_BASIC for extended report output
This patch introduces DM_REPORT_GROUP_BASIC report group type. This
type has exactly the classical output format as we know from before
introduction of report groups. However, in addition to that, it allows
to put several reports into a group - this is the very basic grouping
scheme that doesn't change the output format itself:

  Report: report1_name
  Header1  Header2 ...
  value    value   ...
  value    value   ...
  ...      ...     ...

  Report: report2_name
  Header1  Header2 ...
  value    value   ...
  value    value   ...
  ...      ...     ...
2016-06-20 10:42:26 +02:00
a9fe57db1c libdm: report: implement DM_REPORT_GROUP_SINGLE for a group containing single report only
There's no change in output for this report group type - with this type,
we only make sure there's always only one report in a group at a time,
not more.
2016-06-20 10:42:18 +02:00
9c8f912ea7 libdm: report: introduce dm_report_group
This patch introduces DM report group (represented by dm_report_group
structure) that is used to group several reports to make a whole. As a
whole, all the reports in the group follow the same settings and/or
formatting used on output and it controls that the output is properly
ordered (e.g. the output from different reports is not interleaved
which would break readability and/or syntax of target output format
used for the whole group).

To support this feature, there are 4 new functions:
  - dm_report_group_create
  - dm_report_group_push
  - dm_report_group_pop
  - dm_report_group_destroy

From the naming used (dm_report_group_push/pop), it's clear the reports
are pushed onto a stack. The rule then is that only the report on top
of the stack can be reported (that means calling dm_report_output).
This way we make sure that the output is not interleaved and provides
determinism and control over the output.

Different formats may allow or disallow some of the existing report
flags controlling output itself (DM_REPORT_OUTPUT_*) to be set or not so
once the report is pushed to a group, the grouping code makes sure that
all the reports have compatible flags set and then these flags are
restored once each report is popped from the report group stack.

We also allow to push/pop non-report item in which case such an item
creates a structure (e.g. to put several reports together with any
opening and/or closing lines needed on output which pose as extra
formatting structure besides formatting the reports).

The dm_report_group_push function accepts an argument to pass any
format-specific data needed (e.g. handle, name, structures passed
along while working with reports...).

We can call dm_report_output directly anytime we need (with the only
restriction that we can call dm_report_output only for the report that
is currently on top of the group's stack). Or we don't need to call
dm_report_output explicitly in which case all the reports in a stack are
reported on output automatically once we call dm_report_group_destroy.
2016-06-20 09:26:51 +02:00
029f51e1a8 vgreduce: fix location of lvmlockd global lock
The lvmlockd global lock was missing the non-repair case,
which caused the new orphan PV created by vgreduce to
not be seen by other hosts.
2016-06-17 12:22:58 -05:00
899a4ca275 lvmlockd: fix dropping PVs in rescanning VG
This fixes a problem in commit ae0a8740c.  The problem
in that commit was that all existing PVs are initially
dropped from lvmetad.  This works if the VG is updated
at the end, which replaces the dropped PVs, but if the
rescan finds that the VG seqno is unchanged, it leaves
the cached VG in place.  So, we should only drop the
existing PVs in lvmetad when the VG is going to be updated.
2016-06-17 12:21:09 -05:00
ab7ade4095 post-release 2016-06-17 14:10:20 +01:00
38cc03605c pre-release 2016-06-17 14:10:20 +01:00
a23655ab3b tools: add missing destroy_processing_handle in pvscan and vgreduce code 2016-06-17 13:29:33 +02:00
f77fe436af pvscan: don't activate LVs when use_lvmetad=0
commit 15da467b was meant to address the case where
use_lvmetad=1 in lvm.conf, and lvmetad is not available,
in which case, pvscan --cache -aay should activate LVs.

But the commit unintentionally also changed the case
where use_lvmetad=0 in lvm.conf, in which case
pvscan --cache -aay should not activate LVs, so fix
that here.
2016-06-16 12:04:05 -05:00
944ae4d2df pvscan: fix lvmlockd global lock
This should have been removed when pvscan was
recently converted to use process_each_pv which
does the lvmlockd locking.
2016-06-15 16:51:36 -05:00
15da467b52 pvscan: do activation when lvmetad is not running
When pvscan --cache -aay fails to connect to lvmetad it will
simply exit and do nothing.  Change this so that it will
skip the lvmetad cache step and do the activation step from
disk.
2016-06-15 14:19:18 -05:00
ae0a8740c5 lvmlockd: fix rescanning VG
Previously, new PVs that were added to the VG were not scanned.
2016-06-15 11:36:30 -05:00
49a8d1a85e post-release 2016-06-11 00:14:00 +01:00
f2d1f5e927 pre-release 2016-06-11 00:08:08 +01:00
2d384954ad lvmdbusd: Remove duplicate test code 2016-06-10 16:05:03 -05:00
a1febff857 lvmdbusd: Add test for DataLv & MetaDataLv
Added tests which expose an issue found with these properties.
2016-06-10 16:05:03 -05:00
cdf06044e1 lvmdbusd: Create correct LV object type
We were initially looking to see if an LV was hidden and if it was we were
creating an instance of a LvCommon object to represent it.  Thus if we
had a hidden cache pool for example we were missing the methods and
properties for the cache pool.  However, when we create the object path,
any hidden LVs, regardless of type/functionality will be placed in the
hidden path.
2016-06-10 16:05:03 -05:00
b81186e535 lvmdbusd: Add method get_object_path_by_lvm_id
The object manager method get_object_by_lvm_id was used in many cases for
the sole reason of getting the object path for the object.  Instead of
retrieving the object and then calling 'dbus_object_path' on the object, we
are adding a method which returns the object path.
2016-06-10 16:04:43 -05:00
b717e8fe1d lvmdbusd: Rename get_object_path_by_lvm_id
Renaming to get_object_path_by_uuid_lvm_id, to clarify that both the uuid
and the lvm id are required.
2016-06-10 15:28:42 -05:00
41ebed7077 lvmdbusd: Change print statement to py3 syntax 2016-06-10 15:28:42 -05:00
b717c5efae lvmdbusd: Bug fix for missing LV properties
When we are processing the LVs we need to build up dbus objects from least
dependent to most dependent, so that we have information available when
constructing.
2016-06-10 15:28:42 -05:00
e04705b305 lvmdbusd: Add data_lv and metadata_lv to cache pool interface
See: https://bugzilla.redhat.com/show_bug.cgi?id=1342558
2016-06-10 15:28:42 -05:00
3bf43a65fe lvmdbusd: Add roles property to LV common interface
See: https://bugzilla.redhat.com/show_bug.cgi?id=1342559
2016-06-10 15:28:42 -05:00
8a667f5887 WHATS_NEW: add recent changes 2016-06-10 13:39:23 -05:00
ad414e5ad6 cleanup: typo in WHATS_NEW_DM 2016-06-10 16:01:22 +02:00
35612bd27c display: yes no prompt improvement
Original code missed to catch all apperances of SIGINT.
Also enhance logging when running in shell without tty.
Accept this regex as valid input:
'^[ ^t]*([Yy]([Ee]([Ss]|)|)|[Nn]([Oo]|))[ ^t]*$'
2016-06-10 16:00:31 +02:00
cfdc87b623 lvmdump: also collect output from lsblk command when running lvmdump -s
lsblk provides nice and quick overview of the storage/sysfs structure
that is useful for debugging - collect its output when running lvmdump -s.
2016-06-09 13:54:15 +02:00
86f9271457 vgcreate, pvcreate, vgextend: don't use a device with duplicates
If duplicate orphan PVs exist, don't allow one of them to be
used for vgcreate/pvcreate/vgextend.
2016-06-07 15:21:07 -05:00
199b7b55c2 lvmcache: fix duplicate handling with multiple scans
Some commands scan labels to populate lvmcache multiple
times, i.e. lvmcache_init, scan labels to fill lvmcache,
lvmcache_destroy, then later repeat

Each time labels are scanned, duplicates are detected,
and preferred devices are chosen.  Each time this is done
within a single command, we want to choose the same
preferred devices.  So, check for existing preferences
when choosing preferred devices.

This also fixes a problem with the list of unused duplicate
devs when run in an lvm shell.  The devs had been allocated
from cmd memory, resulting in invalid list entries between
commands.
2016-06-07 15:15:51 -05:00
01156de6f7 lvmcache: add optional dev arg to lvmcache_info_from_pvid
A number of places are working on a specific dev when they
call lvmcache_info_from_pvid() to look up an info struct
based on a pvid.  In those cases, pass the dev being used
to lvmcache_info_from_pvid().  When a dev is specified,
lvmcache_info_from_pvid() will verify that the cached
info it's using matches the dev being processed before
returning the info.  Calling code will not mistakenly
get info for the wrong dev when duplicate devs exist.

This confusion was happening when scanning labels when
duplicate devs existed.  label_read for the first dev
would add an info struct to lvmcache for that dev/pvid.
label_read for the second dev would see the pvid in
lvmcache from first dev, and mistakenly conclude that
the label_read from the second dev can be skipped
because it's already been done.  By verifying that the
dev for the cached pvid matches the dev being read,
this mismatch is avoided and the label is actually read
from the second duplicate.
2016-06-07 15:15:47 -05:00
ed6ffc7a34 lvmetad: handle update failures
If a command gets stuck during an lvmetad update, lvmetad
will cancel that update after the timeout.  The next command
to check the lvmetad will see that lvmetad needs to be
populated because lvmetad will return token of "none" after
a timed out update (same as when lvmetad is not populated
at all after starting.)

If a command gets an error during an lvmetad update, it
will now just quit and leave its updating token in place.
That update will be cancelled after the timeout.
2016-06-07 10:17:00 -05:00
851ccfccaf lvmetad: remove disabled case for "scan error"
Failures while populating lvmetad will be handling
differently in a subsequent commit.
2016-06-07 10:17:00 -05:00
0e7f352c70 lvmetad: define special update in progress string 2016-06-07 10:17:00 -05:00
7ae05adf46 blkdeactivate: fix regression in blkdeactivate causing dm and md devices to be skipped.
Commit #5b3a4a9 caused the "name" variable to be cleared if
declaration and assignment is on two lines so put it back
so it's on one line for it to work again.
2016-06-06 14:57:46 +02:00
7c894911ae post-release 2016-06-03 23:20:43 +01:00
767c9d653e pre-release 2016-06-03 23:16:50 +01:00
b321d2b1b9 pvmove: disallow tag args
pvmove began processing tags unintentionally from commit,
6d7dc87cb pvmove: use toollib

pvmove works on a single PV, but tags can match multiple PVs.
If we allowed tags, but processed only the first matching PV,
then the resulting PV would be unpredictable.

Also, the current processing code does not allow us to simply
report an error and do nothing if more than one PV matches the tag,
because the command starts processing PVs as they are found,
so it's too late to do nothing if a second PV matches.
2016-06-03 09:56:48 -05:00
68e0979724 man: fixed typo in lvcreate.8
It's supposed to be "smaller than" instead of "smaller then".
2016-06-03 12:46:47 +02:00
8e4db009b8 cleanup: compile fixes for --disable-devmapper
Make lvm2 compilable when configured with: --disable-devmapper.
2016-06-03 12:46:43 +02:00
8012c223e0 man: lvmconfig: add note about --type diff and --mergedconfig 2016-06-02 14:07:07 +02:00
687bc5cecf lvmconfig: fix lvmconfig --type diff to display complete diff if config cascade used
If configuration consists of several sources in config cascade
("config cascade" defined in man lvmconfig(8)), lvmconfig displayed
only difference from defaults of the topmost config in the cascade.
Fix lvmconfig to display complete difference, considering all
the configuration in the cascade.

For example, before this patch:

	(use_lvmetad=0 set in lvm.conf which differs from defaults)
	$ lvmconfig --type diff
	global {
		use_lvmetad=0
	}

	(compact_output=1 set on cmd line)
	$ lvmconfig --type diff --config report/compact_output=1
	report {
		compact_output=1
	}

	(headings=0 set in profile)
	$ lvmconfig --type diff --commandprofile test
	report {
		headings=0
	}

	(difference in topmost configuration source is displayed)
	$ lvmconfig --type diff --commandprofile test --config report/compact_output=1
	report {
		compact_output=1
	}

With this patch applied (the config cascade is merged before looking for
difference from defaults in configuration):

	$ lvmconfig --type diff
	global {
		use_lvmetad=0
	}

	$ lvmconfig --type diff --config report/compact_output=1
	report {
		compact_output=1
	}
	global {
		use_lvmetad=0
	}

	$ lvmconfig --type diff --profile test
	report {
		headings=0
	}
	global {
		use_lvmetad=0
	}

	$ lvmconfig --type diff --profile test --config report/compact_output=1
	report {
		headings=0
		compact_output=1
	}
	global {
		use_lvmetad=0
	}
2016-06-02 13:49:38 +02:00
fc37ee63c0 make: add generated parts of lvmdbusd to DISTCLEAN_TARGETS for make distclean 2016-06-02 11:58:54 +02:00
21cefd3f07 cleanup: use display_name 2016-06-01 17:40:26 +02:00
a5d65b4a51 tests: check losetup -P is correctly handled
Validate pvcreate will not overwrite partitioned loop device.
2016-06-01 17:37:52 +02:00
d73a83e8cf tests: extend prepare_loop
Treat args after size  as 'extra' params for losetup.
2016-06-01 17:37:52 +02:00
d37a26b680 devices: handle partscan loop devices
Treat loop device created with 'losetup -P' as regular
partitioned device - so if it has partition table,
prevent its usage in commands like 'pvcreate'.

Before 'pvcreate /dev/loop0' could have erased and formated as PV,
after this patch, device is filtered out and cannot be used.
2016-06-01 17:37:47 +02:00
3d333e5a29 coverity: fix warnings about missing return value check for sscanf
All the variables for sscanf in lvmlockctl.c and lvmlockd-sanlock.c are
zeroed before sscanf call so the failure is detected by seeing the zero
value instead of proper one in subsequent code - so use (void) for
sscanf calls to ignore return value here.
2016-05-31 10:06:25 +02:00
48877e215d coverity: missing check for id_write_format return value 2016-05-31 09:56:10 +02:00
5b3a4a9595 coverity: blkdeactivate: separate format and args for printf and declare and assign separately to avoid masking return values 2016-05-31 09:39:06 +02:00
02d67848eb coverity: fix possible resource leak of descendants_buffer in _print_historical_lv fn 2016-05-31 09:36:58 +02:00
cfe7d2368c tests: add dmstats to CLEAN_TARGETS for make clean 2016-05-31 09:14:23 +02:00
4fb224a553 toollib: properly reset selection handle on selection failure in select_match_{pv,vg,lv} 2016-05-31 09:08:59 +02:00
e4ec6bcdd3 report: fix lvm devtypes internal error if -S is used with field name from pvs/vgs/lvs
Before this fix, when reporting 'lvm devtypes', the report was
initialized with incorrect reserved values - the ones used for
pvs/vgs/lvs report were used instead of NULL value (because devtypes
doesn't have any reserved values).

For example, trying to (incorrectly) use lv_name for the -S|--select
with lvm devtypes which doesn't have this field at all:

Before this patch (internal error issued):

$ lvm devtypes -S 'lv_name=lvol0'
  Internal error: _check_reserved_values_supported: field-specific reserved value of type 0x0 for field  not supported
  Internal error: dm_report_init_with_selection: trying to register unsupported reserved value type, skipping report selection
  DevType       MaxParts Description
  aoe                 16 ATA over Ethernet
  ataraid             16 ATA Raid
  bcache               1 bcache block device cache
  ...

With this patch applied (correct error displayed about
unrecognized selection field):

$ lvm devtypes -S 'lv_name=lvol0'
  Device Types Fields
  -------------------
    devtype_name           - Name of Device Type exactly as it appears in /proc/devices. [string]
    devtype_max_partitions - Maximum number of partitions. (How many device minor numbers get reserved for each device.) [number]
    devtype_description    - Description of Device Type. [string]

  Special Fields
  --------------
    selected               - Set if item passes selection criteria. [number]
    help                   - Show help. [unselectable number]
    ?                      - Show help. [unselectable number]

  Unrecognised selection field: lv_name
  Selection syntax error at 'lv_name=lvol0'.
  Use 'help' for selection to get more help.
2016-05-30 16:46:18 +02:00
815f1ee26d toollib: simplify internal selection calls for non-reporting tools
Some of the variables were set superfluously - we can just use existing
"struct processing_handle" which includes "struct selection_handle".
2016-05-30 16:44:18 +02:00
7d4d0ff606 tests: check thin is not flushed for status
We finally approach a moment where we generally avoid
flushing thin-pool with every lvs command...
2016-05-27 17:25:52 +02:00
88eeb004e9 snapshot: for invalid snapshot show 100%
Recent commit 92eba53a79 started to report
empty "" data usage of invalid snapshot, restore 100% to be shown.
2016-05-27 17:25:37 +02:00
43dfc2011c tests: stacked snapshot merge 2016-05-27 15:47:24 +02:00
a67adbfe2e tests: check cache_mode change on cachepool 2016-05-27 15:47:24 +02:00
090ecaabed debug: use display_lvname 2016-05-27 15:47:24 +02:00
04003cf1ff cache: add log_error on error path
Validate and report error when lv_cache_status is called
for inactive LV, or pending delete or unused cache_pool.
2016-05-27 15:47:24 +02:00
ecfb90de74 report: convert more options to use single status
Convert fields into using a single status ioctl call per LV.
This is a bit tricky since when there are more complicated
stacks, at this moment its undefined which values should be shown.

It's clear we need to cache more then single ioctl per LV,
but also we need to define more explicitely relation between
reported values for snapshots.

This patch is not a final state, rather a transitional step.
It should not be giving more 'worst' values then previous
many-ioctl-calls-per-lv solution.
2016-05-27 15:47:24 +02:00
80603ad49a snapshot: use seg_status for attrs 2016-05-27 15:47:24 +02:00
92eba53a79 lv: introduce lvseg_percent_with_info_and_seg_status
Add function to obtain percentage value for cache lv_seg_status.
This API is rather evolving 'middle' step as the ultimate goal
is segment API fuctionality.

But first we need to be clear at reporting level which values
are needed to be reported for which LVs and segments.
2016-05-27 15:47:24 +02:00
f7f395667e lvstatus: enhance seg_status to handle snapshot
Add more code to properly store status for snapshot segment
maintaining lvm2 fiction of COW and snapshot internal volumes.

The key issue here is however not though-through reporting
logic - as there is no single answer for whole line state.
It not counting with layer and we may need few more ioctl to
cover all reporting needs depending upon what is actually
needed.

In reality we need to 'cache' more ioctl status queries for
individual LVs and their segments (so they checked at most once).

The other 'hard' topic for conversion is mirror segment handling.

Also we definitelly need to relocate some logic into segment's methods,
yet it might be complex as we have not clear border between targets.

TODO: define more clearly how are reporting fields defined in case
we 'stack' volumes like   -   cache of stacked  thin LV snapshot origin.
2016-05-27 15:47:24 +02:00
067c0a23e5 refresh: call resume after failing suspend
lv_refresh_suspend_resume() has escaped with fail ret code
after failing suspend and could have left many volumes in suspend state.

So always unconditionally call resume also  when suspend has failed.
2016-05-27 15:47:24 +02:00
98b41db324 cleanup: drop cmd and constify lv for lv_refresh_suspend_resume()
Like with most other lv_manip* functions take just LV arg and get cmd
from embeded pointer when needed.
2016-05-27 15:47:24 +02:00
cb49ceeaba cleanup: substract integers
Instead of doing float arithmetic, do integer math first and
convert result to float.
2016-05-27 15:47:24 +02:00
1c07e67462 cache: enhance lv_cache_wait_for_clean
Handle passthrough mode when checking cache mode state explicitely.
2016-05-27 15:47:24 +02:00
0424277c00 cache: call status only on cache pool in use
Check show cache status only for cache pool in use.
2016-05-27 15:47:24 +02:00
a4f8d1165c setup_task: add with_flush
To get better control when flushing is used add extra arg when
setting up dm task.

By default now check dm device status without flush.
(At this moment this should effect only thin and cache volumes).

Also switch dev_manager_thin_pool_status() to use more
readable 'flush' parameter instead of 'no_flush'.
2016-05-27 15:47:24 +02:00
26889b3bb6 snapshot: check merging_cow is cow
Check first the LV is cow before even checking it's a merging COW.
Note: previosly merging_cow was also merging origin, so without
this explicit check it used to return '1' also when passed
LV has been merging origin.
2016-05-27 15:47:24 +02:00
e9ee2cb6b6 report: fix report copy_percent value
When mirror/raid called copy_percent function to return,
when 100% was supposed to be returned, wrong float 100.0 value
could have been reported back instead of dm_percent_t DM_PERCENT_100.

There is broken API somewhere, since the function here rely on
actively being modifid VG content even when doing 'lvs' operation.
(extents_copies)
2016-05-27 15:47:24 +02:00
780424639a Revert "libdm: trace missing settings"
This reverts commit 8fd886f735.

This was a deliberate omission because logging token-by-token metadata
parsing greatly increases the amount of logging for hardly any benefit.

In general, only LVM config file settings need to be logged, and in
places where it's considered important to log particular elements of
metadata that should be done using specific log_* lines.

This area can be revisited.
2016-05-27 14:35:11 +01:00
b762c37555 WHATS_NEW: include recent changes 2016-05-26 09:13:30 -05:00
5dc2ed0c71 vgreduce: use process_each_vg 2016-05-25 16:41:59 -05:00
2f2b3c9100 lvconvert: use process_each_lv
In the same way that process_each_vg() can be passed
a single VG name to process, also allow process_each_lv()
to be passed a single VG name and LV name to process.
2016-05-25 15:05:49 -05:00
7fffcce924 raid: Revert _lv_extend_layered_lv non-raid0 area_multiple. 2016-05-24 14:27:05 +01:00
adeb624c3b refactor: split _report fn further into init and config part 2016-05-24 10:56:57 +02:00
8c872852cd metadata: Tidy merge.c 2016-05-24 00:57:48 +01:00
498da2414b raid10: Fix new use of area multiple calc. 2016-05-24 00:41:09 +01:00
b896f7de1e raid0: Standardise meta_areas checks before access. 2016-05-23 22:55:13 +01:00
757f7d5508 test: lvmetad-disabled 2016-05-23 12:01:11 -05:00
3d3efd7ab8 test: lvmetad-pvscan-filter
update for pvscan changes
2016-05-23 12:00:25 -05:00
9b640c3684 pvscan: use process_each_vg for autoactivate
This refactors the code for autoactivation.  Previously,
as each PV was found, it would be sent to lvmetad, and
the VG would be autoactivated using a non-standard VG
processing function (the "activation_handler") called via
a function pointer from within the lvmetad notification path.

Now, any scanning that the command needs to do (scanning
only the named device args, or scanning all devices when
there are no args), is done first, before any activation
is attempted.  During the scans, the VG names are saved.
After scanning is complete, process_each_vg is used to do
autoactivation of the saved VG names.  This makes pvscan
activation much more similar to activation done with
vgchange or lvchange.

The separate autoactivate phase also means that if lvmetad
is disabled (either before or during the scan), the command
can continue with the activation step by simply not using
lvmetad and reverting to disk scanning to do the
activation.
2016-05-23 11:57:32 -05:00
55683a659f toollib: add vg name list arg to process_each_vg 2016-05-23 11:18:16 -05:00
bf8d00985a raid0: Add raid0 segment type.
This remains experimental and quite restrictive so should only be used
for testing at this stage.  (E.g. lvreduce is not supported.)
2016-05-23 16:46:38 +01:00
ad4ca55543 tools: improve error message about VG name and select 2016-05-19 15:06:56 -05:00
6247364caf tests: test change of cache mode 2016-05-19 18:40:14 +02:00
9c083d34af debug: use display_lvname
Add some tracing message
2016-05-19 18:40:14 +02:00
197066c863 lvchange: allow change of cache mode
Add support for active cache LV.
Handle --cachemode args validation during command line processing.
Rework some lvm2 internal to use lvm2 defined  CACHE_MODE  enums
indepently on libdm defines and use enum around the code instead
of passing and comparing strings.
2016-05-19 18:40:14 +02:00
8fd886f735 libdm: trace missing settings
These settings have been missed in very verbose log.
2016-05-19 18:27:34 +02:00
e8ba5c9bd4 libdm: cache status reports passthrough cache mode
Report passthrough mode instead of 'Unknown feature'.
2016-05-19 18:26:07 +02:00
e694e0896b WHATS_NEW: include recent changes 2016-05-18 09:20:52 -05:00
591ef307b3 lvm2_activation_generator: don't create full context for liblvm2app
Don't use lvm_init() to create a full command context, which
does a lot of command setup (like connecting to daemons), which
is unnecessary for simply reading a value from lvm.conf.

Passing a NULL context arg to the lvm_config_ function is now
allowed, in which case lvm.conf is read without doing lvm
command setup.
2016-05-18 09:05:26 -05:00
7fd4119d24 liblvm: allow config settings to be read without full lvm cmd
A program may be using liblvm2app for simply checking a config
setting in lvm.conf.  In this case, a full lvm context is not
needed, only cmd->cft (which are the config settings read from
lvm.conf).

lvm_config_find_bool() can now be passed a NULL lvm context
in which case it will only create cmd->cft, check the config
setting asked for, and destroy the cmd.
2016-05-18 09:04:25 -05:00
ba9b7b69d9 pvremove: allow clearing a duplicate PV
Add a special case to allow modifying a duplicate PV
to erase it with pvremove -ff.
2016-05-16 14:40:43 -05:00
e0c22df5c4 lvmetad: remove old thread locking
The old thread locking is very fine grained and complex,
and appears to have no concurrency advantage.
2016-05-16 14:38:25 -05:00
9f72a52302 lvmetad: add request level thread locking
Use an rwlock for requests that read/write cache state.
Use a mutex for requests that read/write global info.
2016-05-16 14:38:04 -05:00
7ef152c072 python: move lvm_init
Only call lvm_init() when it's needed so that simply
loading the lvm python code in another program doesn't
make that program do lvm initialization.

The version call doesn't need a handle.

The garbage collection can just do lvm_quit to destroy
the command.  The next call that needs lvm_init will
do it first.
2016-05-16 14:36:55 -05:00
57e9df7dc5 post-release 2016-05-14 02:12:23 +01:00
15ca5883fb pre-release 2016-05-14 01:57:42 +01:00
87d9406725 lib: fix init error handling
When setting up a toolcontext, the lib init function
was detecting an error when there was none, and then
it was returning an incompletely initialized cmd struct
instead of NULL.  The effect was that the lib would try
to use the uninitialized cmd struct and segfault.
This would happen if a non-fatal error occurred during
cmd setup, e.g. user permission failed on lvmetad socket,
causing cmd to fall back to scanning and not use lvmetad.

The only real error condition is when create_toolcontext
returns NULL.  If cmd is returned, the lib can use it.
2016-05-12 13:07:52 -05:00
a6203657a0 lvmetad: Fix client error when socket access fails. 2016-05-12 01:54:09 +01:00
e6cafdad36 libdm: Show lib vsn even if driver vsn unavailable. 2016-05-12 01:14:25 +01:00
b5314c2a6a device: Retry open without O_NOATIME if it fails. 2016-05-12 01:05:52 +01:00
f3d508630d test: process-each-duplicate-pvs
skip on RHEL5 where DEV_USED_FOR_LV doesn't work
because it depends on a newer bit of sysfs.
2016-05-11 09:35:42 -05:00
5c18b0ce9c refactor: separate original _report fn into _report and _do_report fn
The _report fn is getting big - separate it in two:

  - _report fn to get all the options and arguments
  - _do_report fn for reporting itself

Also, place all the variables/arguments in one structure for easier
handling of the variables around.
2016-05-10 14:00:13 +02:00
04987e7f49 post-release 2016-05-07 00:48:40 +01:00
e4caf0beeb pre-release 2016-05-07 00:36:59 +01:00
1202713f94 activation: activation check is mandatory
Make missing activation() check before calling target_persent
an INTERNAL_ERROR.
2016-05-06 16:48:16 +02:00
2842a645fd cleanup: drop tracing
When activation is disabled, avoid tracing it in cache target.
2016-05-06 16:48:16 +02:00
db606591c0 segtype: check for activation2
Previous patch 8857b22764 missed
to check for activation for raid target.
2016-05-06 16:48:16 +02:00
144169b9b7 WHATS_NEW: duplicate PVs 2016-05-06 09:30:01 -05:00
e2d823eced metadata: move warning message about repairing VG
Move the message to just before the repair is going
to happen to avoid printing the message in cases
where repair is skipped.
2016-05-06 09:00:00 -05:00
fa130722cb test: vgcfgbackup-lvm1
The lvm1 part of vgcfgbackup-usage.
2016-05-06 09:00:00 -05:00
f194d5f169 test: vgcfgbackup-usage
Split the lvm1 part into a separate test.
2016-05-06 09:00:00 -05:00
4c5ad5a04c test: vgsplit-usage
Restart clvmd between testing each mdatype to
avoid a problem with dev state being kept from
one test to the next.
2016-05-06 09:00:00 -05:00
29a8012724 test: lvmetad-ambiguous
update for duplicate changes
2016-05-06 09:00:00 -05:00
d4d1d5ac3e test: pv-duplicate-uuid
update for duplicate changes
2016-05-06 09:00:00 -05:00
708eca39ea test: process-each-duplicate-pvs
Update for new duplicate processing.
2016-05-06 09:00:00 -05:00
e84fb639f0 lvmetad: add duplicate resolution advice 2016-05-06 09:00:00 -05:00
b1ea27b1e2 lvmetad: disable if device scan fails
If a command begins repopulating the lvmetad cache,
and fails part way through, it should set the disabled
state in lvmetad so other commands don't use bad data.
If a subsequent scan succeeds, the disabled state is
cleared.
2016-05-06 09:00:00 -05:00
49d9582bed lvmcache: use active LVs and device sizes to choose between duplicates
If duplicate devices exist for a PV, and one device's
size matches the PV size, but the other doesn't, then
prefer the matching device.

If one device is used by an active LV, prefer that device.
2016-05-06 09:00:00 -05:00
d4e434d1e6 pvs: new attr and field for unchosen duplicate device
When there are duplicate devices for a PV, one device
is preferred and chosen to exist in the VG.  The other
devices are not used by lvm, but are displayed by pvs
with a new PV attr "d", indicating that they are
unchosen duplicate PVs.

The "duplicate" reporting field is set to "duplicate"
when the PV is an unchosen duplicate, and that field
is blank for the chosen PV.
2016-05-06 09:00:00 -05:00
d3d13e134a lvmcache: process duplicate PVs directly
Previously, duplicate PVs were processed as a side effect
of processing the "chosen" PV in lvmcache.  The duplicate
PV would be hacked into lvmcache temporarily in place of
the chosen PV.

In the old way, we had to always process the "chosen" PV
device, even if a duplicate of it was named on the command
line.  This meant we were processing a different device than
was asked for.  This could be worked around by naming
multiple duplicate devs on the command line in which case
they were swapped in and out of lvmcache for processing.

Now, the duplicate devs are processed directly in their
own processing loop.  This means we can remove the old
hacks related to processing dups as a side effect of
processing the chosen device.  We can now simply process
the device that was named on the command line.

When the same PVID exists on two or more devices, one device
is preferred and used in the VG, and the others are duplicates
and are not used in the VG.  The preferred device exists in
lvmcache as usual.  The duplicates exist in a specical list
of unused duplicate devices.

The duplicate devs have the "d" attribute and the "duplicate"
reporting field displays "duplicate" for them.

'pvs' warns about duplicates, but the formal output only
includes the single preferred PV.

'pvs -a' has the same warnings, and the duplicate devs are
included in the output.

'pvs <path>' has the same warnings, and displays the named
device, whether it is preferred or a duplicate.
2016-05-06 09:00:00 -05:00
8b7a78c728 lvmcache: improve duplicate PV handling
Wait to compare and choose alternate duplicate devices until
after all devices are scanned.  During scanning, the first
duplicate dev is kept in lvmcache, and others are kept in a
new list (_found_duplicate_devs).

After all devices are scanned, compare all the duplicates
available for a given PVID and decide which is best.

If the dev used in lvmcache is changed, drop the old dev
from lvmcache entirely and rescan the replacement dev.
Previously the VG metadata from the old dev was kept in
lvmcache and only the dev was replaced.

A new config setting devices/allow_changes_with_duplicate_pvs
can be set to 0 which disallows modifying a VG or activating
LVs in it when the VG contains PVs with duplicate devices.
Set to 1 is the old behavior which allowed the VG to be
changed.

The logic for which of two devs is preferred has changed.
The primary goal is to choose a device that is currently
in use if the other isn't, e.g. by an active LV.

. prefer dev with fs mounted if the other doesn't, else
. prefer dev that is dm if the other isn't, else
. prefer dev in subsystem if the other isn't

If neither device is preferred by these rules, then don't
change devices in lvmcache, leaving the one that was found
first.

The previous logic for preferring a device was:

. prefer dev in subsystem if the other isn't, else
. prefer dev without holders if the other has holders, else
. prefer dev that is dm if the other isn't
2016-05-06 09:00:00 -05:00
67da017fd2 lvmetad: remove client side altdev code
This is no longer used since lvmetad no longer
keeps track of alternate devices for duplicate PVs,
but is simply disabled when duplicates appear.
2016-05-06 09:00:00 -05:00
3d2fbfe243 lvmetad: set disabled flag when duplicate PVs are seen
When duplicate PVs are detected, set the disabled
flag so that commands will disable use of lvmetad.

This duplicate detection is done by lvmetad itself
when it's told about a single new PV with a PVID
that matches an existing PV on another device.
(This is different from the case where the command
is scanning all devices and detects the duplicate.)

Remove the "altdev" logic that attempted to keep
track of multiple devices for a single PV.  It
is no longer used since lvmetad is disabled in
this case.
2016-05-06 08:59:59 -05:00
9539ee8098 lvmetad: set disabled flag in lvmetad if duplicate PVs are found
When devices are being scanned, if duplicate PVs are seen,
tell lvmetad to set its disabled flag because of duplicate PVs.
2016-05-06 08:59:59 -05:00
a1dbd54885 pvscan: fix errors for single dev scan while lvmetad is disabled
While lvmetad was disabled, 'pvscan --cache dev' would produce
confusing error messages.
2016-05-06 08:59:59 -05:00
08aeea6a12 tests: do not use EPOCH for get wrapper
Avoid poluting filesystem with debug.log_DEBUG for get wrapper
2016-05-05 23:55:20 +02:00
07c1694ff5 tests: update aux raid support
For raid1  use chunksize as bitmap-chunk specification.
Always enforce usage of bitmap - getting comparable outcome
as lvm2 raid support uses.
Add udev_wait after stopping  md array - as in fact leg-device
are still in use by target even command has finished.

(mdadm --stop causes WATCH rule wakeup, and
ioctl(STOP_ARRAY) returns IMHO to early - it should finish
and fsync work on leg devices first).
2016-05-05 23:55:20 +02:00
7bb39af036 tests: check default policy is used when unspecified
If the policy is not given with policy settings we assume
the default one is going to be used - it's users responsibility
to pair them properly.
2016-05-05 23:55:20 +02:00
95f0e25601 tests: check for thin tools
Test needs repair utils to be available.
2016-05-05 23:55:20 +02:00
673d4f7453 cleanup: use unsigned with EPOCH printf format 2016-05-05 23:55:20 +02:00
ed9162cd88 cleanup: enhance warning message
Add WARNING: for log_warn.
Show device name which is marked missing.
2016-05-05 23:55:18 +02:00
f6575ec824 cleanup: just switch error path
Check for error case in if() like we normally do.
Let code continue on success.
2016-05-05 23:52:06 +02:00
d1ecbfa52d lvcreate: improve --chunksize support for cached volume.
Support parsing --chunksize option also when converting.
Now user can use cache pool created with i.e. 32K chunksize,
while in caching user can select 512K blocks.
Tool is supposed to validate cache metadata size is big enough
to support such chunk size. Otherwise error is shown.
2016-05-05 23:50:10 +02:00
d3b15674df lvcreate: check for lv type and created segtype
When creating LV - in some case we change created segment type
(ATM for cache and snapshot) and we then manipulate with
lv segment according to 'lp' segtype.
Fix this by checking for proper type before accessing segment members.

This makes command like:

lvcreate --type cache-pool -L10 vg/cpool
lvcreate -H -L10 --cachesettings migtation_threshold=10000  vg/cpool

to pass since now tool correctly selects default cache policy.
2016-05-05 23:34:35 +02:00
d0111563c2 debug: enhance debug msg for cache 2016-05-05 23:34:35 +02:00
fd79027cae cache: use target_present_version
Using new function.
Also add trace for error path.
2016-05-05 23:34:35 +02:00
4d116d7a28 cleanup: gather version info with single check
As we already collect version info anyway, allow to use it through
a single call (can makes logs shorter and saves ioctl).
2016-05-05 23:34:30 +02:00
def65507e6 cache: add cache_set_params function
Wrapping function to handle setup of various cache related params.
Reusable with lvcreate & lvconvert.
2016-05-05 23:30:49 +02:00
ae805eea50 cache: add validate_lv_cache_chunk_size 2016-05-05 23:30:49 +02:00
00dfca034c cache: function for min metadata size estimation
Move min code into reusable function.
2016-05-05 23:30:02 +02:00
7c1e601164 pvcreate: improve debug message
state what the printed UUID is.
2016-05-04 12:11:13 -05:00
1df6769aca pvcreate, pvremove: translate arg name to device once
Rather than doing repeated translations from name to
device when comparing args to existing PVs, do one
translation of the arg names and saving the device,
before checking existing PVs.
2016-05-04 11:28:28 -05:00
795e47cec5 post-release 2016-04-30 01:12:33 +01:00
e53ecf91f7 pre-release 2016-04-30 01:07:26 +01:00
c76df666c9 raid: Use inherited tags when wiping rmeta.
If there's an activation volume_filter, it might not be possible
to activate the rmeta LVs to wipe them.  At least inherit any
LV tags from the parent LV while attempting this.
2016-04-29 19:49:21 +01:00
e3efcdc9f5 datastruct: Add str_list_wipe. 2016-04-29 19:47:15 +01:00
16019b518e libdm: Add dm_udev_wait_immediate.
dm_udev_wait() waits inside the library.
dm_udev_wait_immediate allows the caller to do other things if the
cookie isn't yet ready to be decremented.
2016-04-28 00:54:27 +01:00
a2d2a61339 pvscan: autoactivation should ignore some VGs
pvscan autoactivation has its own VG processing implementation,
so it can't properly handle things like foreign or shared VGs,
so make it ignore those VG types (or errors from them) as best
as possible.

Add a FIXME stating that pvscan autoactivation must really be
moved to the standard VG processing by calling process_each_vg
to do activation once the scanning / cache update is finished.
2016-04-27 15:45:38 -05:00
263c1a4db5 lvmetad: improve warning after lvmetad message fails
Make it more consistent with the other similar warning.
2016-04-27 15:38:34 -05:00
3c53acb378 metadata: fix segfault when filters reject devices
Checking for devices uses is_missing_pv() to check
if there is a device for the PV.  is_missing_pv()
is based on the MISSING_PV flag, which does not
always correspond to !pv->dev.  When using lvmetad,
a command like:

pvs --config 'devices/filter=["a|/dev/sdb|", "r|.*|"]'

will cause a number of PVs to have NULL pv->dev, but
not the MISSING_PV flag.  So, NULL pv->dev needs to
also be checked.
2016-04-27 12:13:26 -05:00
49f32e4859 cache: better support for alias check
To still support disabling of policies for test we need
better logic for alias detection introduced in
588455d03e.
2016-04-27 00:20:37 +02:00
2a2efab0b1 cleanup: use log_debug_activation 2016-04-27 00:01:08 +02:00
c81005dcc4 cleanup: smaller timeout
1s -> 0.5s
Also indent fix.
2016-04-26 23:59:20 +02:00
07d92322c1 man: lvcreate doc passthrough
Add few more words about passthough mode.
2016-04-26 23:29:58 +02:00
d90d99b23d man: lvchange updates
Drop never existing --degrade.
2016-04-26 23:29:58 +02:00
e77b6968b6 lvchange: use better arg functions 2016-04-26 23:29:58 +02:00
c215e1be5c lvchange: always check for sigint
Check sigint() state during process_each_lv.
2016-04-26 23:29:08 +02:00
d8bdc7af37 lvchange: fix return code
We already opened VG for this - so not an invalid cmdline.
2016-04-26 23:28:01 +02:00
84a5b19539 thin: zero and transaction_id also with thin volumes
Show trasaction_id when thin volume was created.
Also show zeroing state of thin-pool with thin volume (so user
doesn't need to lookup thin-pool).
2016-04-26 23:24:51 +02:00
8b5967e1e3 cache: check for clean cache as separete function 2016-04-26 23:24:17 +02:00
588455d03e cache: with cache target 1.9 mq is alias to smq
Avoid useless check for mq policy, it's loaded as smq
and aliased.
2016-04-26 23:24:05 +02:00
aa91fe3d3c modprobe: check /sys/module entry first
Before executing modprobe for given module name, just check
if the module is not already present in /sys/module.

Useful when checking dm-cache-policy modules as we do not
having matching interface like for targets.
2016-04-26 23:23:03 +02:00
ecae76c713 udev: rules: add comments explaining subsystem-specific rules 2016-04-26 12:57:37 +02:00
2bb33aaf55 udev: rules: remove mpath from 10-dm.rules, superseded by 11-dm-mpath.rules (mpath>=0.6.0)
Multipath 0.6.0 contains new 11-dm-mpath.rules which supersede the rule
that was in 10-dm.rules. The 11-dm-mpath.rules are also more complete,
fixing several other issues. Using the new 11-dm-mpath.rules from
multipath-tools >= 0.6.0 is strongly recommended for proper
DM multipath functionality!

See also:
  http://christophe.varoqui.free.fr
  http://git.opensvc.com/gitweb.cgi?p=multipath-tools/.git;a=blob;f=multipath/11-dm-mpath.rules
2016-04-25 14:55:54 +02:00
379874a2d0 cleanup: do not mention segment in warning message if device not found for a PV when checking used/assumed devs for an LV
[0] fedora/~ # pvs --config 'devices/filter=["a|/dev/sda|", "r|.*|"]'
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  WARNING: Couldn't find device for segment belonging to fedora/root while checking used and assumed devices.
  WARNING: Couldn't find device for segment belonging to fedora/swap while checking used and assumed devices.
  PV         VG     Fmt  Attr PSize   PFree
  /dev/sda          lvm2 ---  128.00m 128.00m
  [unknown]  fedora lvm2 a-m   19.49g      0

Probably not worth mentioning "segments" here, just state that devices
for an LV can't be all found during the check - it's less mysterious for
user then:

[0] fedora/~ # pvs --config 'devices/filter=["a|/dev/sda|", "r|.*|"]'
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  WARNING: Couldn't find all devices for LV fedora/root while checking used and assumed devices.
  WARNING: Couldn't find all devices for LV fedora/swap while checking used and assumed devices.
  PV         VG     Fmt  Attr PSize   PFree
  /dev/sda          lvm2 ---  128.00m 128.00m
  [unknown]  fedora lvm2 a-m   19.49g      0
2016-04-25 11:44:24 +02:00
9d976c0002 metadata: log warning instead of error if device not found while checking used and assumed devs
When checking assumed PVs against real devices used for LVs and if
there's no device assigned for an assumed PV (e.g. due to filters),
do log_warn instead of log_error and continue checking LV segments
and associated assumed PVs further, just like we do log_warn elsewhere
in this situation.

This way user will see the warning for each LV which couldn't be
checked completely against real PVs used. Before, we logged only
the very first occurence of missing device for an LV in a VG and we
returned from the function doing this check for all the LVs in VG
immediately which may be a bit misleading because it didn't tell
user about all the other LVs and whether they could be checked
or not.

For example, we have this setup:

[0] fedora/~ # pvs
  PV         VG     Fmt  Attr PSize   PFree
  /dev/sda          lvm2 ---  128.00m 128.00m
  /dev/vda2  fedora lvm2 a--   19.49g      0

[0] fedora/~ # lvs -o+devices
  LV   VG     Attr       LSize   Devices
  root fedora -wi-ao----  19.00g /dev/vda2(0)
  swap fedora -wi-ao---- 500.00m /dev/vda2(4864)

Before this patch (only the very first LV in a VG is logged to have a
problem while checking used and assumed devices):

[0] fedora/~ # pvs --config 'devices/filter=["a|/dev/sda|", "r|.*|"]'
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  Couldn't find device for segment belonging to fedora/root while checking used and assumed devices.
  PV         VG     Fmt  Attr PSize   PFree
  /dev/sda          lvm2 ---  128.00m 128.00m
  [unknown]  fedora lvm2 a-m   19.49g      0

With this patch applied (all LVs where we hit problem while checking
used and assumed devices are logged and it's warning, not error):

[0] fedora/~ # pvs --config 'devices/filter=["a|/dev/sda|", "r|.*|"]'
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  WARNING: Device for PV Qcxpcy-XgtP-UD3s-PmG0-qLyE-Z0ho-DYsxoz not found or rejected by a filter.
  WARNING: Couldn't find device for segment belonging to fedora/root while checking used and assumed devices.
  WARNING: Couldn't find device for segment belonging to fedora/swap while checking used and assumed devices.
  PV         VG     Fmt  Attr PSize   PFree
  /dev/sda          lvm2 ---  128.00m 128.00m
  [unknown]  fedora lvm2 a-m   19.49g      0
2016-04-25 11:27:28 +02:00
eb8edccd58 post-release 2016-04-23 00:43:13 +01:00
546b2006dd pre-release 2016-04-23 00:41:55 +01:00
31b11d0228 tests: drop cluster testing with pvmove
Unwanteadly enabled in previous check-in.
2016-04-22 14:15:36 +02:00
a88828c845 coverity: check for sys error in clock call 2016-04-22 14:15:36 +02:00
bc239f15eb coverity: ignore some dm_strncpy results
Using them only for debug so ignorable.
Also don't mark stack char buffer alignment, compiler already knows
what's the best here.
2016-04-22 14:15:36 +02:00
d12ba022c8 coverity: keep expression using 64bit
Use 64bit input to remain with whole evaluation in 64bit.
2016-04-22 14:15:36 +02:00
d564d9f39c coverity: is_used_pv needs valid pv pointer 2016-04-22 14:15:36 +02:00
2dc6b97856 tests: make test independent on usage [] for hidden LVs 2016-04-22 12:53:09 +02:00
4ddf5a11cf cache: fix previous change and correct ()
412f09ca33 missed parentheses.
2016-04-22 12:52:53 +02:00
17ad884836 libdm-stats: check for empty region and area lists
Check that @stats_list and @stats_print returned data in the
_stats_parse_list() and _stats_parse_region() functions before
attempting to operate on region and area values.

This avoids a coverity warning since fgets() could potentially
return no data from the memory buffer returned by the ioctl.

In both cases the ioctl would return an error, preventing these
functions from running, however it is cleaner to test for the
condition explicitly and fail in those cases.
2016-04-22 10:35:07 +01:00
69c2f56005 tests: keep using [] for hidden volumes
Figure out which test needs to see hidden volumes without [].
But normally use [] for debug printing in tests.
It's confusing otherwise.
2016-04-22 01:14:56 +02:00
8c4b717f4d coverity: drop abadoing object
As mempool is destroyed on by caller don't bother for
mempool freeing here.
2016-04-22 01:13:35 +02:00
0bf5518626 coverity: avoid using signed types for single bits 2016-04-22 01:12:34 +02:00
412f09ca33 coverity: return non-null string with internal error
While we return internal error we should not let tool crash on NULL
access, so return valid string for such case.
2016-04-22 01:12:34 +02:00
447daa9179 coverity: use wider type for whole expression
Coverity likes when the types are same through the whole expression.
And since dev_t is 64b - widen int type early.
2016-04-22 01:12:34 +02:00
edcb3e65c6 coverity: drop unused header file 2016-04-22 01:12:34 +02:00
99e96f3ce9 coverity: fix error paths
Patch 74e704bb44 missed to update
error path. Since now we just need to 'return_0' as 'dmt is NULL
and thus may not be destroyed.
2016-04-22 01:12:34 +02:00
cbf99be43a coverity: fix memory access
Commit  52e0d0db44 introduced regression
as code may access   buf[0 - 1].

Reorder code to first remove '\n' and then check buffer size for
empty.
2016-04-22 01:11:57 +02:00
556eba1835 cleanup: use kdev_t header in lvm tree
Reuse libdm header in lvm so we have single definition
of MAJOR/MINOR/MKDEV macros in use.
2016-04-22 00:23:28 +02:00
9d4f9defc3 cleanup: simplify code
dm_strncpy() also check the size fits.
2016-04-22 00:22:02 +02:00
c9373a0c2a WHATS_NEW: disable lvmetad for lvm1 2016-04-21 16:40:44 -05:00
01181a299e activate: Hide errors when snapshot merge delayed. 2016-04-21 22:14:10 +01:00
4d095c2fbb poll daemon: only call lvmetad_connect when needed
When lvm is not using lvmetad, the lvmetad_connect()
in the forked polling process is not needed and was
generating unwanted warnings.
2016-04-21 15:58:34 -05:00
11dd362454 tests: GLIBC decided to obsolete readdir_r
Keep the code compilatible without warnings on newer glibc.
2016-04-21 17:48:19 +02:00
1134ab6324 lvmetad: warn about making changes while not using lvmetad
If lvmetad is running, and a command opts to not use it
(--config global/use_lvmetad=0), and the command changes
metadata, then the metadata change is not visible to
lvmetad.  Subsequent commands using lvmetad to change
metadata may cause corruption based on the invalid
lvmetad state.

Eventually we can set the disabled state in lvmetad
to prevent this problem, but for now print a warning
about the possibility.
2016-04-21 10:28:01 -05:00
6e6f8025ff lvmetad: fix compile without lvmetad
Last commit was missing stub function.
2016-04-21 10:06:47 -05:00
e44c4806db lvmetad: check pid for warning case
When command is not using lvmetad because
use_lvmetad=0 in the config, but the lvmetad
pidfile exists, print a warning (previously
this checked for the socket existing instead
of the pidfile existing.)
2016-04-21 09:50:59 -05:00
d00b70c789 lvmetad: check for socket in connect
We can connect if the socket is present, even
though the pidfile may not exist, since systemd
may start the process when the socket is opened.
2016-04-21 09:27:20 -05:00
0778d2e985 display: Avoid internal snapshot LV names in msgs.
vg/snapshotN should not appear anywhere.

No code should be showing this, but it was noticed in some logs last
week and we can deal with it in display_lvname().
2016-04-21 00:30:17 +01:00
2763b928de lvmetad: fix compilation without lvmetad# 2016-04-21 00:34:01 +02:00
7ce486e881 tests: minor update 2016-04-21 00:34:01 +02:00
545b58542c tests: still show systems stas when command has not produced debug.log file
When no debug.log* file is present whole stacktracking was skipped.
Add extra test the file exists to catch this case.
2016-04-21 00:34:01 +02:00
22a71e1119 tests: document make parametr for tracing aux scripts 2016-04-21 00:34:01 +02:00
509b2e5247 debug: move misplaced log_debug
It should log action before taking it instead of only in error path.
2016-04-21 00:34:01 +02:00
57f468a53e configure: respect --disable-lvmetad/lvmpolld
When user requested on cmdline disabling of lvmetad/lvmpoll,
respect it and when lvmlockd requires these daemon,
Error configure with clear message about misconfiguration.
2016-04-21 00:34:01 +02:00
600d7ca15f configure: detect for /var/lock dir
Detecs systems with /run/lock dir and use such path directly instead
of /var/lock.
2016-04-20 23:32:51 +02:00
5c104c5de9 lvmetad: connect from forked polling process
With commit 5e9e43074a, lvmetad connections are
now made explicitly, so a new connection must be
created from a child created for polling.
2016-04-20 09:04:39 -05:00
9553260673 test: lvmetad-override
Fix test case where a warning appears when it's not expected.
2016-04-19 14:26:05 -05:00
5e9e43074a lvmetad: rework command connection setup and checking
The lvmetad connection is created within the
init_connections() path during command startup,
rather than via the old lvmetad_active() check.

The old lvmetad_active() checks are replaced
with lvmetad_used() which is a simple check that
tests if the command is using/connected to lvmetad.

The old lvmetad_set_active(cmd, 0) calls, which
stopped the command from using lvmetad (to revert to
disk scanning), are replaced with lvmetad_make_unused(cmd).
2016-04-19 14:00:02 -05:00
593900b795 lvmetad: use defines for disabled reason strings 2016-04-19 11:45:24 -05:00
fa904a844f test: lvmetad-warning
The test was a weak attempt at verifying the special
combination of lvchange/vgchange -aay --sysinit, but
was only looking for lvmetad connection warnings.

Update the warning checks, and check the LV activation
state directly which is the main point.

Rename the test to reflect its purpose of checking
the -aay --sysinit combination.
2016-04-19 11:45:24 -05:00
6b1c0a4190 test: lvmetad-override 2016-04-19 11:45:24 -05:00
c5cd5b4b69 test: lvmetad-no-cluster
Update warning message check
2016-04-19 11:45:24 -05:00
a5722ed7e7 test: update lvmetad-disabled
Update the check about lvmetad running but not used.

Also add tests related to the new lvmetad disabled state.
lvm1 metadata is used here to test the disabled state
because lvm1 metadata is the first condition using the
disabled state.
2016-04-19 11:45:24 -05:00
c9cf85f606 test: update lvm1 test
Make it a generic lvm1 test, which should work
with or without lvmetad now that lvmetad is just
disabled when lvm1 is used.
2016-04-19 11:45:19 -05:00
2a17610899 lvmetad: disable if command uses lvm1
Alternatively, a command could return an error saying
that lvm1 and lvmetad are not compatible.
2016-04-19 09:41:18 -05:00
1e380864e5 lvmetad: clear the disabled flag in lvmetad
After a device rescan that repopulates lvmetad,
if no reason for disabling lvmetad was seen
(lvm1 metadata or duplicate PVs), then clear
the disabled flag in lvmetad.  This allows
commands to resume using the lvmetad cache
after the cause for disabling it has been removed.
2016-04-19 09:41:18 -05:00
04a83148ce lvmetad: use the disabled flag in commands
Commands already check if the lvmetad token is valid,
and if not, they rescan devices to repopulate lvmetad
before running.  Now, in addition to checking the
lvmetad token, they also check if the lvmetad disabled
flag is set.  If so, they do not use the lvmetad cache
and revert to disk scanning.
2016-04-19 09:41:18 -05:00
ff867c2ef6 lvmetad: set disabled flag in lvmetad if lvm1 metadata is found
When devices are being scanned, if lvm1 metadata is seen,
tell lvmetad to set its disabled flag because of lvm1 metadata.
2016-04-19 09:41:18 -05:00
a4ef8fa25e lvmetad: add disabled state
A global flag in lvmetad indicates it has been disabled.
Other flags indicate the reason it was disabled.
These flags can be queried using get_global_info.

The lvmetactl debugging utility can set and clear the
disabled flag in lvmetad.  Nothing else sets the
disabled flag yet.

Commands will check these flags after connecting to
lvmetad.  If the disabled flag is set, the command
will not use the lvmetad cache, but revert to disk
scanning.

To test this feature:

$ lvmetactl get_global_info
response = "OK"
global_invalid = 0
global_disable = 0
disable_reason = "none"
token = "filter:3041577944"

$ vgs
(should report VGs from lvmetad)

$ lvmetactl set_global_disable 1

$ lvmetactl get_global_info
response = "OK"
global_invalid = 0
global_disable = 1
disable_reason = "DIRECT"
token = "filter:3041577944"

$ vgs
  WARNING: Not using lvmetad because the disable flag was set directly.
(should report VGs without contacting lvmetad)

$ lvmetactl set_global_disable 0

$ vgs
(should report VGs from lvmetad)
2016-04-19 09:41:18 -05:00
e41ee70acc toollib: remove unneeded call in process_each_pv
process_each_pv was doing:

1. lvmcache_seed_infos_from_lvmetad()
   sends pv_list request to lvmetad.

2. get_vgnameids()
   sends vg_list request to lvmetad.

3. _get_all_devices()
   first calls lvmcache_seed_infos_from_lvmetad(),
   which is a no-op if it's already been called.

Because get_vgnameids() does not use the information
from lvmcache_seed_infos_from_lvmetad(), it does not
need to be called prior to get_all_devices where
it is actually needed.
2016-04-19 09:40:24 -05:00
a6a32a7c0e metadata: don't repair shared VGs
When the in-use flag looks like it needs to be repaired.
2016-04-19 09:19:32 -05:00
a400eba174 lvmlockd: skip unnecessary lvmetad cache update
In cases where a VG is reread from disk, but the
seqno matches what is currently in lvmetad, the
metadata in lvmetad doesn't need to be updated.
2016-04-19 09:19:32 -05:00
50633039bf tests: use should for failing test
It's better to use 'should' for failing test before it gets fixed,
when we ignore failing result.
2016-04-18 23:12:05 +02:00
59b0bd7b64 tests: use bigger raid size
To avoid problem with report of array in-sync use for now bigger
raid size 64M.
2016-04-18 23:09:17 +02:00
88c19d5d72 lvchange: improve refresh for merging thin volume
When running lvchange --refresh on merging thin volume,
try to deactivate snapshot thinLV in case it's preventing
startup of merge process.
2016-04-18 23:05:51 +02:00
7e5881dd13 snapshot: improve merge
Improve code for snapshot merge for readabilty
and also reduce number of tests needed to decide
if merging can or cannot be started.

(Further improving 9cccf5245a)
2016-04-18 23:05:17 +02:00
d1c1f60047 debug: use display_lvname 2016-04-18 12:32:56 +02:00
e2ceb90095 debug: update message in libdm
When dm_tree_find_node_by_uuid() fails to find passed uuid,
report in lof_debug the complete original uuid,
not the one stripped of LVM- prefix.

TODO: inspect manipulation with LVM- prefix here.
2016-04-18 12:32:56 +02:00
f5cf6cc9ed debug: fix error message
log_error is replaced with warn since the result
of function is not result in command error.
2016-04-18 12:32:56 +02:00
9cccf5245a thin: improve recognizing of merge in progress
Rewrite too condensed condition in more readable form,
wher decision are clearly separated and commented and
also add debug messages for them.
2016-04-18 12:32:52 +02:00
e2cd882f2e thin: check runtime table line for merging
To recognize in runtime if we are merging or not
to make consistent decision between suspend and resume
add function to parse thin table line when add
merging thin device to the table.
2016-04-18 11:18:35 +02:00
662090e358 tests: fix check_lvmlockd_test 2016-04-15 12:35:20 -05:00
6954de22e2 activate: Improve snapshot merge initiation
A snapshot merge into its origin cannot be initiated while the devices
are in use.  If there is outside interference (such as from udev),
the suspend (preload) and resume stages can reach conflicting decisions
about whether or not to proceed.

Try to make the logic more robust by checking the inactive or live
table during resume.  (This is still not perfect.)
2016-04-15 02:33:38 +01:00
150cff9cce activation: Log when pending snap merge postponed. 2016-04-14 23:42:56 +01:00
7ae5f6fc5c WHATS_NEW for lvmetad scanning changes 2016-04-14 16:55:34 -05:00
ff09bda7d5 activation: Add LV name to a debug message. 2016-04-14 22:41:25 +01:00
f0179fac31 snapshot: Don't deactivate fictional snapshot LV.
Commit 971ab733b7 ("thin: activation of
merging thin snapshot") also added an incorrect deactivation attempt
for non-thin LVs: find_snapshot(lv)->lv is not designed to be
activated and any attempt to deactivate it is incorrect.
2016-04-14 22:32:26 +01:00
c68fb55ac1 toollib: Fix misleading message when forking.
Commands like pvscan --background run entirely in the background,
but others fork only for polling.
2016-04-14 17:21:02 +01:00
3f6e7f90ca refactor: factor out vg/lv/pv handling part from report_for_selection fn
Functionality will be reused by future patches. Also, it makes the code
more readable.
2016-04-14 15:24:36 +02:00
9a299d2d7a tests: lvmetad-lvm1 fix
workaround this test failure until the proper
lvmetad/lvm1 fixes arrive shortly.
2016-04-13 15:07:53 -05:00
579bd92009 lvmetad: add FIXME to comment 2016-04-13 14:08:29 -05:00
56c68b3476 lvmetad: preemptively check and rescan in commands
Move checking the lvmetad state, and the possible rescan,
out of lvmetad_send() to the start of the command.

Previously, the token mismatch and rescan would occur
within lvmetad_send() for some other request.  Now,
the token mismatch is detected earlier, so the
rescan can be done before the main command is in
progress.  Rescanning deep within the processing of
another command will disturb the lvmcache state of
that other command.

A rescan already exists at the start of the command
for the case where foreign VGs are going to be read.
This same rescan is now also performed when there is
an lvmetad token mismatch (from a changed global_filter).

The commands pvscan/vgscan/lvscan/vgimport are excluded
from this preemptive checking/rescanning for lvmetad
because they want to do rescanning themselves explicitly.

If rescanning devices fails, then lvmetad has not been
correctly repopulated and should not be used, so make
the command revert to not using lvmetad.
2016-04-13 14:05:42 -05:00
a28c81cbae debug: unify some tracing messages
Introduce  FMTVGID - although it might be possibly better to ensure
vgid is always \0 ended string.

Unify some lvmcache reported messages.
2016-04-12 13:06:16 +02:00
1be74cfd7f cleanup: gcc warn about comparing int with uint 2016-04-12 11:47:51 +02:00
0f7975cb35 cleanup: avoid declaring var in the middle of code
Easier to read code.
2016-04-12 11:47:51 +02:00
147c9c01a2 rename function read_vgname to read_vgsummary
The name did not clearly represent what it does.
2016-04-11 13:07:48 -05:00
fe65a86cbc devcache: do not insert devices without device node
When not obtaining device from udev, we are doing deep devdir scan,
and at the same time we try to insert everything what /sys/dev/block
knows about. However in case  lvm2 is configured to use nonstardard
devdir this way it will see (and scan) devices from a real system.

lvm2 test suite is using its own test devdir with its
own device nodes. To avoid touching real /dev  devices, validate
the device node exist in give dir and do not insert such device
into a cache.

With obtain list from udev this patch has no effect
(the normal user path).
2016-04-11 10:33:14 +02:00
07a60b59f7 devcache: index devices also without udev
We have _insert_dirs() for  udev and non-udev compilation.
Compiling without udev missed to call dev_cache_index_devs().
Move the call after _insert_dirs() call so both compilation
gets it.
2016-04-11 10:32:19 +02:00
9e14abb887 post-release 2016-04-09 02:10:39 +01:00
3aab784aa5 pre-release 2016-04-09 02:08:44 +01:00
af148a9d77 cleanup: avoid gcc warns
Some older systems may had global declaration to cause gcc warning.
Rename for cases we don't care...
2016-04-08 20:20:16 +02:00
5cfa6cb347 cleanup: simplier to read condition
Make more readable what we are looking for and just test for
KERNEL version at one place.
2016-04-08 20:20:16 +02:00
74e704bb44 cleanup: reuse _setup_task
Shorten code and use common code from _setup_task.
Reorder naming of major:minor sscanf (as later it's been
also used swapped there was no real bug).
2016-04-08 20:20:16 +02:00
a09d65891f dev_manager: device_is_usable does not flush
When scanning if device is being usable as PV,
we call STATUS - but this status should not cause
any flushing.
Skip also open_count information as it's not needed.
2016-04-08 20:20:04 +02:00
f40dfb48ad activation: Skip another non-prefixed info ioctl.
_percent() also does a lookup by dm uuid.
Also get kernel version from cmd->kernel_vsn.
2016-04-08 16:27:12 +01:00
e6768997e1 test: Fix testing of installed lvmdbusd
If lvmdbusd is missing expression triggers ERR trap instead of skipping
the test.
2016-04-08 16:26:25 +02:00
ed0c779bd1 report: remove superfluous SEGSSTATUS report type
We don't have any report field of this type yet. Return this patch into
the play if we really need that. Currenly we always report status
(result of "status" dm ioctl) for an LV as a whole where we choose
segment which represents the LV, not calling status for each possible
segment it contains - we don't need this now so I'm removing it to
not make the code more complex uselessly.
2016-04-08 14:21:47 +02:00
50866034a2 cleanup: use common init/destroy_processing_handle in _report fn and cleanup error paths 2016-04-08 11:01:19 +02:00
f2e59e05ed cleanup: use #define for field's quote and pair character and also for the error msg while extending output line 2016-04-08 10:55:13 +02:00
248f47d489 tests: require newer cache target
Older cache target is likely not updating status at all...
2016-04-08 00:04:26 +02:00
9ab53dddf5 tests: use mkfs.ext3
mkfs.ext4 is not really needed so use more widespread mkfs.ext3
so test runs on older system.
2016-04-07 22:32:09 +02:00
8b2108e6b1 activation: do not check for devs without LVM-
Devices without "LVM-" uuid prefix have been generated by very old
version of lvm2 2.00 and 2.01.
Since version 2.02 all lvm2 devices are using prefix "LVM-".

However checking for present of ancient non prefixed devices does
take extra IOCTL per every call and for majority of todays user
it will not find anything new.

So use the assumption that users with kernel 3.X and newer are not
really using such old versions of lvm2 (year <2005) and with their
new kernel they are also using new version of lvm2 and skip
checking for them.

This change also makes trace logs more readable.
2016-04-07 22:32:08 +02:00
097a724bda lvcreate: %FREE -> %PVS
This is hotfix for RHBZ: https://bugzilla.redhat.com/1324537
However already the %FREE is not a good fit and we need something
better. Meanwhile make  -l%PVS work at least as good as %FREE
for thin-pool.

TODO: this needs rework - it should be allocator to do all the size
decisions at one place.
2016-04-07 22:32:08 +02:00
e2d4f53c82 WHATS_NEW: update
doc for previous commits.
2016-04-07 22:31:40 +02:00
7dcbf1dfd0 libdm: Correct typo. 2016-04-07 01:51:09 +01:00
f19ec0e36d lvmdump: If dir exists check dir perms too. 2016-04-06 22:56:45 +01:00
55001ae9ec lvmdump: Allow dir to exist already if it is empty 2016-04-06 22:36:42 +01:00
307ab2c179 tests: do not break teardown on failing losetup
Ignore failing 'losetup -d' - i.e. device may have disappeared...
2016-04-06 11:54:37 +02:00
07c25429e2 tests: verify repair of failing mirror
Improved test script to verify lost mirror image does not
cause mirror corruption while mirror is in use.

TODO: add more cases (lost mlog...), lost image from 3leg mirror...
2016-04-06 11:54:36 +02:00
9be7bca4be cleanup: indent 2016-04-06 11:31:02 +02:00
0584e85736 lvconvert: show percent with %.2
lvm2 shows percent values with 2 decimal digits elsewhere so use
it consistently also for this output.
2016-04-06 11:31:02 +02:00
261a85ced9 libdm: improve debug message with ioctl
Make the debug message a less difficult to read:
Ioctl shows  [ noopencount flush ] instead of cryptic [NF].
2016-04-06 11:31:02 +02:00
5b2227c2c1 preload: preserve flushing state
When leaving preload routine it should not altet state of flush required
when it's been already set to 1 and drop it to 0.

The API here is unclean, but current usage expects the same
variable pointer is for all preload calls and combines 'flush_required'
across all of them.
2016-04-06 11:31:02 +02:00
7c1937f8df suspend: fix suspend with noflush limitation
Commit 844b009584 tried to move
limit for usage of noflush to 'preload' however this was not
correctly processed.

Intead explicitly check for which types we do not want noflush
and also add debug message in this case.
2016-04-06 11:31:02 +02:00
d4c03cf7b2 mirror: fix flushing for mirror target
Fix regression caused by commit ba41ee1dc9.
The idea was to use no_flush for changed device only for thin volumes
and thin pools but also to merge this with change made in commit
844b009584.

However the resulting condition has caused misbehavior for the mirror
suspend - as that has been before the ONLY allowed target type
that could have been suspended with noflush.

Result was badly working repair for --type mirror that has been
passing 'flush' to the repaired mirror target whenever preload
wrongly set flush_required.

The origin code has required the flush_required to be set whenever
deivce size is changed.

Now it first detects if device size got smaller
'dm_tree_node_size_changed(root) < 0' - this requires flush.
Otherwise it checks device is not thin volume nor thin pool and its
size has changed (got bigger) and requires flush.

This mean upsize of thin-pool or thin volume will not require flush.
2016-04-06 11:31:02 +02:00
76fc41fb9d post-release 2016-04-01 20:36:40 +01:00
2d0d58b867 pre-release 2016-04-01 20:29:52 +01:00
60befab773 Revert "thin: display highest mapped sector"
This reverts commit fc7dacaa4c.

Let's put this information into a separate field.  It doesn't meet the
definition of the existing field.
2016-04-01 20:09:38 +01:00
42f04a0f77 dev-cache: skip VGID/LVID indexing if /sys/dev/block is not present
/sys/dev/block is available since kernel version 2.2.26 (~ 2008):
https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-dev

The VGID/LVID indexing code relies on this feature so skip indexing
if it's not available to avoid error messages about inability to open
/sys/dev/block directory.

We're not going to provide fallback code to read the /sys/block/
instead in this case as that's not that efficient - it needs extra
reads for getting major:minor and reading partitions would also
pose further reads and that's not worth it.
2016-04-01 17:09:15 +02:00
9f28eb4c20 fix: make udev_get_library_context available also for non-udev compilations
If compiling without udev_sync support, udev_get_library_context simply
returns NULL so we don't need to remember putting ifdef UDEV_SYNC_SUPPORT
in the code all the time we just need to check whether there's any udev
context initialized or not.
2016-04-01 15:35:22 +02:00
15d1824fac dev-cache: iterate devices in sysfs for VGID/LVID index if obtain_device_list_from_udev=0
If obtain_device_list_from_udev=0, LVM can make use of persistent .cache
file. This cache file contains only devices which underwent filters in
previous LVM command run. But we need to iterate over all block devices
to create the VGID/LVID index completely for the device mismatch check
to be complete as well.

This patch iterates over block devices found in sysfs to generate the
VGID/LVID index in dev cache if obtain_device_list_from_udev=0
(if obtain_device_list_from_udev=1, we always read complete list of
block devices from udev and we ignore .cache file so we don't need
to look in sysfs for the complete list).
2016-04-01 14:49:39 +02:00
7ed5a65ee5 dev-cache: also add dev name for device found in sysfs only
For the case when we print device name associated with struct device
that was not found in /dev, but in sysfs, for example when printing
devices where LV device mismatch is found.
2016-04-01 14:48:56 +02:00
91d32f9d1b refactor: dev-cache: move code adding sysfs-only device into separate fn 2016-04-01 11:47:06 +02:00
0e774d5ae7 refactor: dev-cache: use btree instead of hash table for sysfs-only devices
major:minor btree is more convenient and more suitable than dev name
hash table here.
2016-04-01 11:42:25 +02:00
c577984630 tests: fixed cache target reacts faster
After kernel fixed in 4.6 cache target reacts promptly
and switches to Fail-ed state when disk error is detected.

Handle both cases in test...
2016-03-31 12:21:40 +02:00
bc5376b151 tests: do not test settings when MQ is emulated by SMQ 2016-03-31 12:21:40 +02:00
5034bb8d18 cleanup: use local var to read struct 2016-03-31 12:21:40 +02:00
b10253ab4d cleanup: use TARGET define 2016-03-31 12:21:40 +02:00
86db143307 cleanup: debug message fix
Reported-by: Ming-Hung Tsai <mingnus gmail com>
2016-03-31 12:21:25 +02:00
fc7dacaa4c thin: display highest mapped sector
Use  meta%  to expose highest mapped sector in thinLV.
so showing there 100.00% means thinLV maps latest sector.

Currently using a 'trick' with total_numerator to pass-in
device size when  'seg==NULL'

TODO: Improve device status API per target - current 'percentage'
is not really extensible.
2016-03-31 12:20:43 +02:00
8bbec41bd4 thin: no thin-pool flush when reading metadata status
Previous fix missed the fact the we do query for 'percent' with
seg value either set or unset (API overload...)
When 'seg' was unset, we still issue flush with status.
Fix it by cheking segtype by target_type.

As we check for segtype - we could also skip whole percentage
if the 'segtype' is unknown by code directly.

Reported-by: Ming-Hung Tsai <mingnus gmail com
2016-03-31 12:15:47 +02:00
fe7ae37f5e tests: vg-check-devs-used requires driver version 4.15 at least 2016-03-31 10:38:05 +02:00
9a086a6607 dev-cache: fix check for already indexed dev in _index_dev_by_vgid_and_lvid 2016-03-30 15:57:57 +02:00
06ef7ba876 doc: describe lvmlockd/lvmpolld features as available if LVM compiled with lockd/polld support 2016-03-30 14:10:56 +02:00
8b258a005b dev-cache: dev_cache_index_devs fn is available unconditionally
The new dev_cache_index_devs fn was under ifdef UDEV_SYNC_SUPPORT by mistake,
move it out of this ifdef.
2016-03-30 13:06:20 +02:00
52e0d0db44 dev-cache: remove spurious error msg if no value found in /sys/dev/block/<major>:<minor>/dm/uuid during dev scan
It's correct to have a DM device that has no DM UUID assigned
so no need to issue error message in this case. Also, if the
device doesn't have DM UUID, it's also clear it's not an LVM LV
(...when looking for VGID/LVID while creating VGID/LVID indices
in dev cache).

For example:

$ dmsetup create test --table "0 1 linear /dev/sda 0"
And there's no PV in the system.

Before this patch (spurious error message issued):
$ pvs
  _get_sysfs_value: /sys/dev/block/253:2/dm/uuid: no value

With this patch applied (no spurious error message):
$ pvs
2016-03-30 11:30:09 +02:00
8c27c52749 dev-cache: also index VGIDs and LVIDs if using persistent .cache file
If we're using persistent .cache file, we're reading this file instead
of traversing the /dev content. Fix missing indexing by VGID and LVID
here - hook this into persistent_filter_load where we populate device
cache from persistent .cache file instead of scanning /dev.

For example, inducing situation in which we warn about different device
actually used than what LVM thinks should be used based on metadata:

$ lsblk -s /dev/vg/lvol0
NAME     MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
vg-lvol0 253:4    0  124M  0 lvm
`-loop1    7:1    0  128M  0 loop

$ lvmconfig --type diff

global {
	use_lvmetad=0
}
devices {
	obtain_device_list_from_udev=0
}

(obtain_device_list_from_udev=0 also means the persistent .cache file is used)

Before this patch - pvs is fine as it does the dev scan, but lvs relies
on persistent .cache file and it misses the VGID/LVID indices to check
and warn about incorrect devices used:

$ pvs
  Found duplicate PV B9gXTHkIdEIiMVwcOoT2LX3Ywh4YIHgR: using /dev/loop0 not /dev/loop1
  Using duplicate PV /dev/loop0 without holders, ignoring /dev/loop1
  WARNING: Device mismatch detected for vg/lvol0 which is accessing /dev/loop1 instead of /dev/loop0.
  PV          VG Fmt  Attr PSize   PFree
  /dev/loop0 vg lvm2 a--  124.00m    0

$ lvs
  Found duplicate PV B9gXTHkIdEIiMVwcOoT2LX3Ywh4YIHgR: using /dev/loop0 not /dev/loop1
  Using duplicate PV /dev/loop0 without holders, ignoring /dev/loop1
  LV    VG Attr       LSize
  lvol0 vg -wi-a----- 124.00m

With this patch applied - both pvs and lvs is fine - the indices are
always created correctly (lvs just an example here, other LVM commands
that rely on persistent .cache file are fixed with this patch too):

$ pvs
  Found duplicate PV B9gXTHkIdEIiMVwcOoT2LX3Ywh4YIHgR: using /dev/loop0 not /dev/loop1
  Using duplicate PV /dev/loop0 without holders, ignoring /dev/loop1
  WARNING: Device mismatch detected for vg/lvol0 which is accessing /dev/loop1 instead of /dev/loop0.
  PV          VG Fmt  Attr PSize   PFree
  /dev/loop0 vg lvm2 a--  124.00m    0

$ lvs
  Found duplicate PV B9gXTHkIdEIiMVwcOoT2LX3Ywh4YIHgR: using /dev/loop0 not /dev/loop1
  Using duplicate PV /dev/loop0 without holders, ignoring /dev/loop1
  WARNING: Device mismatch detected for vg/lvol0 which is accessing /dev/loop1 instead of /dev/loop0.
  LV    VG Attr       LSize
  lvol0 vg -wi-a----- 124.00m
2016-03-30 11:00:01 +02:00
91bb202ded dev-cache: handle situation where device is referenced in sysfs, but the node is not yet in dev dir
It's possible that while a device is already referenced in sysfs, the node
is not yet in /dev directory.

This may happen in some rare cases right after LVs get created - we sync
with udev (or alternatively we create /dev content ourselves) while VG
lock is held. However, dev scan is done without VG lock so devices may
already be in sysfs, but /dev may not be updated yet if we call LVM command
right after LV creation (so the fact that fs_unlock is done within VG
lock is not usable here much). This is not a problem with devtmpfs as
there's at least kernel name for device in /dev as soon as the sysfs
item exists, but we still support environments without devtmpfs or
where different directory for dev nodes is used (e.g. our test suite).

This patch covers these situations by tracking such devices in
_cache.sysfs_only_names helper hash for the vgid/lvid check to work still.

This also resolves commit 6129d2e64d
which was then reverted by commit 109b7e2095
due to performance issues it may have brought (...and it didn't resolve
the problem fully anyway).
2016-03-30 10:56:46 +02:00
bc0372cf9d test: Add missing directory
Fix commit bb93a28bc1
2016-03-29 08:24:52 +02:00
d6e8f18e4d post-commit 2016-03-26 09:07:21 +00:00
b9d07f7a12 pre-release 2016-03-26 09:04:50 +00:00
a5d53aec83 libdm: Raid status region units are sectors 2016-03-24 17:42:36 +00:00
d243db5466 lvmdbusd: Add '-' to allowable PV device path chars 2016-03-24 12:27:02 -05:00
109b7e2095 revert: 6129d2e64d
Unfortunately, commit 6129d2e64d may
cause performance issue. There's going to be a better fix...
2016-03-24 14:06:12 +01:00
37b548c6b5 WHATS_NEW: commit 6129d2e64d 2016-03-24 12:47:35 +01:00
6129d2e64d monitoring: sync /dev content before contacting dmeventd for monitor/unmonitor
dmeventd daemon may call further code itself that looks at /dev, e.g.
via dmeventd_lvm2_command call. We need to have a consistent view of
the /dev content at that time. Therefore, sync /dev content before
calling monitoring hook which contacts dmeventd.

This problem was quite hidden before, but now it has manifested itself
because of recent additions to dev-cache code where we started looking
at device holders as seen in sysfs. What happened here was that the
device was already in sysfs, but not yet under /dev and this triggered
the new error message sometimes:

  log_error("%s: failed to find associated device structure for holder %s.", devname, devpath);

This problem has manifested recently in our api/pytest.sh test from
testsuite where we create thin pool LVs and thin LVs and hence it also
causes dmeventd to be used as well and these error messages were
visible there.
2016-03-24 12:40:19 +01:00
82d92009ae test: Move bus configuration to prepare function 2016-03-23 12:27:34 +01:00
1b0775916b test: Remove pidfile after killing the process
Though unlikely keeping files in place may result in random process
killed.
2016-03-23 12:25:18 +01:00
bb93a28bc1 test: Fix lvmdbusd tests to work with installed testsuite 2016-03-23 11:59:04 +01:00
c1d376b1ab test: Fix checks to skip lvmdbusd tests
The executable is always present in the tree, need to check the
runtime dependencies.
2016-03-23 11:58:48 +01:00
c6d383a6da properties: use proper 'get' variant for unimplemented _pv_major_get and _pv_minor_get fns 2016-03-23 10:52:46 +01:00
1056894f1f raid: Tidy dm_get_status_raid. [HM] 2016-03-22 21:39:52 +00:00
cf39346697 libdm: Move _skip_fields within file. 2016-03-22 19:35:14 +00:00
65d2d66d02 libdm: Change _advance_to_next_word to _skip_fields 2016-03-22 19:26:13 +00:00
1216efdf15 activate: Use macros for target and module names. 2016-03-22 17:46:15 +00:00
94f78e0183 coverity: fix some issues reported by coverity for recent code 2016-03-22 16:03:55 +01:00
3d26d283ea tests: update vg-check-devs-used.sh
Snapshot needs to be activated exclusively in cluster...
2016-03-22 11:18:22 +01:00
6a915270fc tests: update vg-check-devs-used.sh 2016-03-22 11:13:28 +01:00
ed002ed22a dev: also count with suffixes in UUID for LVs when constructing VGID and LVID index
UUID for LV is either "LVM-<vg_uuid><lv_uuid>" or "LVM-<vg_uuid><lv_uuid>-<suffix>".
The code before just checked the length of the UUID based on the first
template, not the variant with suffix - so LVs with this suffix were not
processed properly.

For example a thin pool LV (as an example of an LV that contains
sub LVs where UUIDs have suffixes):

[0] fedora/~ # lsblk -s /dev/vg/lvol1
NAME              MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
vg-lvol1          253:8    0    4M  0 lvm
`-vg-pool-tpool   253:6    0  116M  0 lvm
  |-vg-pool_tmeta 253:2    0    4M  0 lvm
  | `-sda           8:0    0  128M  0 disk
  `-vg-pool_tdata 253:3    0  116M  0 lvm
    `-sda           8:0    0  128M  0 disk

Before this patch (spurious warning message about device mismatch):

[0] fedora/~ # pvs
  WARNING: Device mismatch detected for vg/lvol1 which is accessing /dev/mapper/vg-pool-tpool instead of (null).
  PV         VG     Fmt  Attr PSize   PFree
  /dev/sda   vg     lvm2 a--  124.00m    0

With this patch applied (no spurious warning message about device mismatch):

[0] fedora/~ # pvs
  PV         VG     Fmt  Attr PSize   PFree
  /dev/sda   vg     lvm2 a--  124.00m    0
2016-03-22 10:52:24 +01:00
2a47f0957f dev: also check for blank sysfs value containing only '\n' 2016-03-22 09:29:24 +01:00
e69e81388d report: Add pv_major, pv_minor to reports. 2016-03-22 00:12:08 +00:00
16b1272597 lvmdbusd: Change print statements to log_error
Should not be using print() in the service code.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-21 17:28:51 -05:00
ca28ea88be lvmdbusd: Add lvm flight recorder
To help out with debug, when an exception is thrown in the dbus service we
will dump all the information we have on the last 16 commands that were
executed along with the stack strace.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-21 17:28:51 -05:00
a0c7875c54 lvmdbusd: Allow PV devices to be referenced by symlink(s)
See: https://bugzilla.redhat.com/show_bug.cgi?id=1318754

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-21 17:28:51 -05:00
86e9d12b6f lvmdbusd: Remove --udev in service file
With commit 2d5dc6512e the dbus server
no longer needs to utilize udev to know when to update its internal
state.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-21 17:28:51 -05:00
cc57cd39ab tests: add vg-check-devs-used.sh 2016-03-21 16:21:30 +01:00
8fad9b9e5d dev: be safer when reading sysfs properties
Check if the value we read from sysfs is not blank and replace the '\n'
at the end only when needed ('\n' should usually be there for sysfs values,
but better check this).
2016-03-21 15:50:32 +01:00
ca7bac53cf test: Turn on dbus test
(cherry picked from commit f1ea96c6c1dc6414169bda1a18cf14cd9ebb1493)
2016-03-21 15:22:58 +01:00
f231bdb20b metadata: use own mem pool to report PV device mismatch in VG 2016-03-21 14:39:11 +01:00
03b0a78640 dev: detect mismatch between devices used and devices assumed for an LV
It's possible for an LVM LV to use a device during activation which
then differs from device which LVM assumes based on metadata later on.

For example, such device mismatch can occur if LVM doesn't have
complete view of devices during activation or if filters are
misbehaving or they're incorrectly set during activation.

This patch adds code that can detect this mismatch by creating
VG UUID and LV UUID index while scanning devices for device cache.

The VG UUID index maps VG UUID to a device list. Each device in the
list has a device layered above as a holder which is an LVM LV device
and for which we know the VG UUID (and similarly for LV UUID index).

We can acquire VG and LV UUID by reading /sys/block/<dm_dev_name>/dm/uuid.
So these indices represent the actual state of PV device use in
the system by LVs and then we compare that to what LVM assumes
based on metadata.

For example:

[0] fedora/~ # lsblk /dev/sdq /dev/sdr /dev/sds /dev/sdt
NAME         MAJ:MIN RM  SIZE RO TYPE  MOUNTPOINT
sdq           65:0    0  104M  0 disk
|-vg-lvol0   253:2    0  200M  0 lvm
`-mpath_dev1 253:3    0  104M  0 mpath
sdr           65:16   0  104M  0 disk
`-mpath_dev1 253:3    0  104M  0 mpath
sds           65:32   0  104M  0 disk
|-vg-lvol0   253:2    0  200M  0 lvm
`-mpath_dev2 253:4    0  104M  0 mpath
sdt           65:48   0  104M  0 disk
`-mpath_dev2 253:4    0  104M  0 mpath

In this case the vg-lvol0 is mapped onto sdq and sds becauset this is
what was available and seen during activation. Then later on, sdr and
sdt appeared and mpath devices were created out of sdq+sdr (mpath_dev1)
and sds+sdt (mpath_dev2). Now, LVM assumes (correctly) that mpath_dev1
and mpath_dev2 are the PVs that should be used, not the mpath
components (sdq/sdr, sds/sdt).

[0] fedora/~ # pvs
  Found duplicate PV xSUix1GJ2SK82ACFuKzFLAQi8xMfFxnO: using /dev/mapper/mpath_dev1 not /dev/sdq
  Using duplicate PV /dev/mapper/mpath_dev1 from subsystem DM, replacing /dev/sdq
  Found duplicate PV MvHyMVabtSqr33AbkUrobq1LjP8oiTRm: using /dev/mapper/mpath_dev2 not /dev/sds
  Using duplicate PV /dev/mapper/mpath_dev2 from subsystem DM, ignoring /dev/sds
  WARNING: Device mismatch detected for vg/lvol0 which is accessing /dev/sdq, /dev/sds instead of /dev/mapper/mpath_dev1, /dev/mapper/mpath_dev2.
  PV                     VG     Fmt  Attr PSize   PFree
  /dev/mapper/mpath_dev1 vg     lvm2 a--  100.00m      0
  /dev/mapper/mpath_dev2 vg     lvm2 a--  100.00m      0
2016-03-21 11:40:40 +01:00
65d9f742f8 device: add DEV_OPEN_FAILURE flag
DEV_OPEN_FAILURE flag is set if the most recent "open" for a device
failed and it's unset if any subsequent "open" succeeds.
2016-03-21 11:06:05 +01:00
e58d24293f post-release 2016-03-19 01:18:28 +00:00
0d4b6bdfc0 pre-release 2016-03-19 01:14:29 +00:00
6c10d1f3d9 fsadm: use stat to get major:minor pair for non-standard /dev layouts
If we're using non-standard /dev layout so we can't get the dm-X name
easily, we can't also look at the /sys/blocl/dm-X/dev to get the major:minor
pair. Use "stat" in this case even though it triggers automounts
(but there's no better way for now).
2016-03-18 17:21:47 +01:00
2879eff86e fsadm: if available, use /proc/self/mountinfo to detect mounted volume
The /proc/self/mountinfo is not bound to device names like /proc/mounts
and it uses major:minor pairs instead.

This fixes a situation in which a volume is mounted and then renamed
later on - that makes /proc/mounts unreliable when detecting mounted
volumes.

See also https://bugzilla.redhat.com/show_bug.cgi?id=1196910.
2016-03-18 13:42:06 +01:00
464ebe04db tests: stacked resize of thin on raid 2016-03-15 23:22:52 +01:00
51ed48f855 lvresize: fix stacked resize
Commit b64703401d cause regression
when handling stacked resize of pool metadata volume that would
be a raid LV.

Fix it by properly setting up size also for layer extension.
2016-03-15 23:21:16 +01:00
746f8af2a8 tests: update lvconvert test 2016-03-14 23:46:08 +01:00
0d5b9deff2 tests: use own PID path for lvmetad checking
Do not try to check PID of running lvmetad and use own path.
2016-03-14 23:45:45 +01:00
7daba90fa3 lvconvert: fix error path test
lvremove_single toollib function returns
ECMD_FAILED or ECMD_PROCESSED.
2016-03-14 23:37:42 +01:00
a39563c0b0 report: Use default vg_name field width too. 2016-03-14 09:30:51 +00:00
a78e696070 post-release 2016-03-11 00:21:53 +00:00
2159a1429d pre-release 2016-03-11 00:19:16 +00:00
6807eb8863 man: vgcreate shared 2016-03-10 15:40:37 -06:00
0f10823ec9 pvchange, pvresize: move exported VG check
Allow pvchange and pvresize to process exported VGs,
and have them check for the exported state in their
single function.

Previously, the exported VG state would trigger a
failure in vg_read()/ignore_vg() because the VGs are
being read with READ_FOR_UPDATE.  Because these commands
read all VGs to search for the intended PVs, any
exported VG would trigger a failure, even if it was
not related to the intended PV.
2016-03-10 13:37:42 -06:00
9f4451193b lvconvert: update --help
Use  <>  around user entered option parameters to make it visually
different (just like we use Italic style in man page).

TODO:

In the future we should consistently provide such notation and
possibly generate it automagically from some internal data structures.

Preferably for man pages as well so we report actual set of supported
options.
2016-03-10 18:38:54 +01:00
5bfc0edd12 tests: uncache with missing PV
For now repair of cache with missing PVs via usage of --uncache.
More will follow later.
2016-03-10 18:38:54 +01:00
00e641ef37 cleanup: display_lvname 2016-03-10 18:38:54 +01:00
8507db1924 cleanup: reoder lines 2016-03-10 18:38:54 +01:00
b36cf94318 cleanup: add backtrace 2016-03-10 18:38:54 +01:00
8e9deb2e70 gcc: cast time_t to 64bit
Value is printed as uint64, so make sure right type is passed on all
platforms. Fixes gcc warning on some 32bit platforms.
2016-03-10 18:38:54 +01:00
5aade9c402 topology: handle reported sizes smaller then sector
Recent kernel (4.4) start to report values smaller then sector size
(but in reporting size for SSD which support data zeroing on discard).

For now log warning and assume it really means 1 sector.

Addressing RHBZ:
https://bugzilla.redhat.com/show_bug.cgi?id=1313377
2016-03-10 18:38:54 +01:00
a494d85ef6 man: drop extra braces
doclifter tool noticed wrong brackets.
2016-03-10 18:38:54 +01:00
386208e593 man: updates
Continuing with lvconvert style updates.

Minimize usage of '\:' as zero-width break space, since html renderers
do not handle this groff sign well (some of them seems to even render
':' there).
But since we do not want see badly rendered man pages itself, prefer
the 'man visual' appearence over html page generation (man2html should
be actually fixed).

Start to use 'user input option' with Capitals more consistently.
2016-03-10 18:38:54 +01:00
86a23b2145 makefiles: avoid using vpath for rules files
Fixing vpath usage as it has been checking for existance of
generated file also in the $(scrdir) e.g.:

No need to remake target '10-dm.rules.in'; using VPATH name '...'

If the $(srcdir) had been also $(builddir) and contained already
generated rules file, it's been used instead generating new
one.

(See: http://make.mad-scientist.net/papers/how-not-to-use-vpath/)
2016-03-10 18:38:53 +01:00
70cbd8f1a5 lvconvert: improve vg parameter parsing
Commit abd9618dd8 tried to improve
parsing of vg name from logical path - but still missed couple
corner cases.

This patch further improves the logic and reuses
validate_lvname_param() for parsing of lv_name.

Also explicitly checks for LVM_VG_NAME in the right case.

So now also properly parses cases like:
  'lvconvert --repairt vg/'
and will provide correct error message.
2016-03-10 18:38:53 +01:00
5c415afd85 cache: check for cache fail during flush
Just WARN if the cache can't be flushed because it's failed.
2016-03-10 18:38:53 +01:00
569ba79abf lvconvert: uncache handles missing PV
Allow to process with --uncache when some PVs are missing in VG.

So it's now possible to --uncache cached LV if the cache-pool
has missing PV.
2016-03-10 18:38:53 +01:00
29d1533a49 libdm: parse more info from cache status
Parse Fail/Error/need_check/ro status info from cache.
2016-03-10 18:38:53 +01:00
9918d95490 metadata: do not issue warning message about PV dev size being 0 when the device has gone just after VG read
There's a window between doing VG read and checking PV device size
against real device size. If the device is removed in this window,
the dev cache still holds struct device and pv->dev still references
that and that PV is not marked as missing. However, if we're trying
to get size for such device, the open fails because that device
doesn't exists anymore.

We called existing pv_dev_size in _check_pv_dev_sizes fn. But
pv_dev_size assigned a size of 0 if the dev_get_size it called failed
(because the device is gone).

So call the dev_get_size directly and check for the return code
in _check_pv_dev_sizes and go further only if we really know the
device size. This is to avoid confusing warning messages like:

  Device /dev/sdd1 has size of 0 sectors which is smaller than corresponding PV size of 31455207 sectors. Was device resized?
  One or more devices used as PVs in VG helter_skelter have changed sizes.
2016-03-10 13:11:15 +01:00
8f01ee3035 remove unused define 2016-03-09 13:38:04 -06:00
18291fd016 test: Remove work-in-progress code from dbustest
(cherry picked from commit 3189d4d50492f5b78cf3920a7f499fd1020983c6)
2016-03-09 14:04:28 +01:00
e72184bb76 spec: Fix gobject dependency
Use python3-gobject-base instead of python3-gobject requiring xorg

(cherry picked from commit d929d82116759f53484e662b967165ef4fe4257c)
2016-03-09 14:00:05 +01:00
55d1105fc9 test: skip unrelated tests while testing lvmpolld 2016-03-09 12:59:45 +01:00
5434e9f5ea test: fix inverted condition 2016-03-09 12:59:42 +01:00
e655ccb418 test: Add prepare_lvmdbusd
- Check for running lvmdbusd at start
- Add teardown for lvmdbusd
2016-03-09 10:58:21 +01:00
d7ca164597 spec: Add missing dependency for dbusd
(cherry picked from commit 7435de21492f6b37ac7664d1f27b4a8dcc4d0dd4)
2016-03-09 10:58:21 +01:00
cb968ee875 test: Comment out incorrect lockd setup 2016-03-09 10:58:21 +01:00
c6e1845f76 test: Move udev-lvmlockd-test to check_system 2016-03-09 10:58:21 +01:00
2cf13b701a test: Update kernels to skip thin-flags with
See ed5e5c38b5
2016-03-09 10:09:29 +01:00
6d19c14c28 lvmdbus: Fix deprecated warnings for GObject use
While running on F24 a number of warnings were being emitted from using the
deprecated GObject instead of GLib.  Tested on python 3.4 and 3.5.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-08 16:07:35 -06:00
3f5629302a lvmdbus: Fix exception during exception handling
Python 3.5 in F24 was throwing the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.5/site-packages/lvmdbusd/main.py", line 73, in process_request
    req.run_cmd()
  File "/usr/lib/python3.5/site-packages/lvmdbusd/request.py", line 73, in run_cmd
    self.register_error(-1, st)
  File "/usr/lib/python3.5/site-packages/lvmdbusd/request.py", line 123, in register_error
    self._reg_ending(None, error_rc, error)
  File "/usr/lib/python3.5/site-packages/lvmdbusd/request.py", line 115, in _reg_ending
    self.cb_error(self._rc_error)
  File "/usr/lib64/python3.5/site-packages/dbus/service.py", line 669, in <lambda>
    keywords[error_callback] = lambda exception: _method_reply_error(connection, message, exception)
  File "/usr/lib64/python3.5/site-packages/dbus/service.py", line 293, in _method_reply_error
    exception))
  File "/usr/lib64/python3.5/traceback.py", line 136, in format_exception_only
    return list(TracebackException(etype, value, None).format_exception_only())
  File "/usr/lib64/python3.5/traceback.py", line 442, in __init__
    if (exc_value and exc_value.__cause__ is not None
AttributeError: 'str' object has no attribute '__cause__'

This was caused because we were calling the dbus error callback with a
string instead of an actual exception.  On python 3.4 this was apparently
OK, but not with 3.5.  Corrected to pass the exception to error callback.
Change tested on both python 3.4 and 3.5.

Reported-by: Vratislav Podzimek <vpodzime@redhat.com>
Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-08 16:06:45 -06:00
90c5d470c2 report: Tidy some field names, widths and headings.
Specifying an output width of 0 now leads to a default minimum width
taken from the width of the column heading.  (Most fields should use
this.)

Components of field names are generally separated by underscores (which
are optional at run-time).  (Dropped 3 duplicate fields now covered by
this rule.)

Each field heading must be unique and generally doesn't have spaces
between words (which get capitalised) unless they are already short and
the fields are normally longer or clarity demands it.
2016-03-08 19:50:22 +00:00
6cf1eff46d toollib: always process in use pvs
With the recent conversion of pvcreate/pvremove to the
common toollib processing function, skipping in-use PVs
in _process_pvs_in_vg prevented them from being protected
as intended by the in-use flag.

The processing code for pvcreate/pvremove checks for the
in-use state itself and prevents using an in-use PV.
If a PV is skipped, it looks like an unused device and
is not protected from being used in pvcreate/pvremove.
2016-03-07 14:15:33 -06:00
a8319e62c0 vgscan: add --notifydbus to send a notification
This command option can be used to trigger a D-Bus
notification independent of the usual notifications
that are sent from other commands as an effect of
changes to PV/VG/LV state.  If lvm is not built with
dbus notification support or if notify_dbus is disabled
in the config, this command will exit with an error.
2016-03-07 10:50:45 -06:00
2d5dc6512e dbus: add notification from commands
When a command modifies a PV or VG, or changes the
activation state of an LV, it will send a dbus
notification when the command is finished.  This
can be enabled/disabled with a config setting.
2016-03-07 10:06:09 -06:00
18cf5e8e67 raid_manip: allow for raid leg to be replaced when not both data and metadata image are on pvs
resolves rhbz#1130329
2016-03-07 15:25:30 +01:00
d03b1779b4 coverity: fix possible resource leak in _print_historical_lv function
The code in _print_historical_lv function works with temporary
"descendants_buffer" that is allocated and freed within this
function.

When printing text out, we used "outf" macro which called
"out_text" fn and it checked return value and if failed,
the macro called "return_0" automatically. But since we
use the temporary buffer, if any of the out_text calls
fails, we need to deallocate this buffer properly - that's
the "goto_out", otherwise we'll be leaking memory.

So add new "outfgo" helper macro which does the same as "outf",
but it calls "goto_out" instead of "return_0" so we can jump
to a cleanup hook at the end.
2016-03-07 10:43:50 +01:00
7b15ca5c9a post-release 2016-03-04 18:06:24 +00:00
68ec240b99 pre-release 2016-03-04 17:59:21 +00:00
6c78175126 lvmdbusd: Set locale
Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-04 10:13:04 -06:00
f94fe2c91f dbustest.sh: Get dbus test to work on buildbot
- stdout/stderr for test output
- debug.log* for daemon output
- use install instead of cp for DBus config
- use system bus
- DBus reloads on new file. Better having it created with correct
  permissions.

Notes:
- Squashed commits from mcsontos development branch
- Still disabled at this time

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-03-04 10:11:03 -06:00
9720898c8e libdm: config: fix dm_config_write_node and variants to properly return error on failures
The error was not propagated if _write_config (that is part of
dm_config_write_node and all its variants) was called recursively
for subsections.
2016-03-04 15:51:13 +01:00
67c5006e12 cleanup: previous patch with libdm config node buffer size 2016-03-04 15:19:09 +01:00
967a0889a0 libdm: config: remove 4096 char limit due to buffer size if writing dm_config_node 2016-03-04 14:59:22 +01:00
418b7c6be8 WHATS_NEW: historical LVs 2016-03-04 12:08:02 +01:00
e447ab87e9 man: lvrename: also mention possibility to rename historical logical volumes 2016-03-04 11:51:57 +01:00
fa06c2263b cleanup: comment in the code for renaming historical LVs 2016-03-04 11:46:29 +01:00
27245d97e5 lvrename: support renaming historical logical volumes 2016-03-04 11:36:24 +01:00
b114b4d723 commands: lvdisplay: recognize -H|--history switch 2016-03-04 10:27:45 +01:00
ad9cbe2714 tests: direct control of lvm1 usage in tests
Using lvm1 metadata with lvmetad is not generally allowed,
but nothing has prevented creating new lvm1 metadata with
lvmetad (missing error checking in pvcreate/vgcreate.)
Various tests are using lvm1 with lvmetad and happen to
work because of the missing error checks.

This commit fixes the tests so they won't fail when the
lvm1/lvmetad error checking is fixed.  A new variable
LVM_TEST_LVM1 is defined and is used in the scripts to
decide if lvm1 metadata should be tested.  LVM_TEST_LVM1
is not defined when lvmetad is being tested, and the
combination of LVM_TEST_LVM1 and LVM_TEST_LVMETAD can
be used to verify the desired lvmetad+lvm1 behavior.
2016-03-03 14:43:19 -06:00
5764c484ea man: Add some information about historical LVs. 2016-03-03 17:09:25 +00:00
9a78c258ba tests: add lv-ancestry.sh test 2016-03-03 13:50:59 +01:00
45c82260db tests: add "get lvh_field" for "lvs -H" 2016-03-03 13:50:59 +01:00
b39473a537 lvmdump: also list historical LVs in lvmdump 2016-03-03 13:50:59 +01:00
8a601454e1 metadata: automatically remove invalid (dangling) historical LVs
Historical LV is valid as long as there is at least one live LV among
its ancestors. If we find any invalid (dangling) historical LVs, remove
them automatically.
2016-03-03 13:50:59 +01:00
1297b0c8be metadata: also validate historical LVs in VG in vg_validate and check_lv_segments 2016-03-03 13:50:59 +01:00
fc628e92ba metadata: also look at historical LVs when checking LV name availability
Live LVs and historical LVs are in one namespace and the name needs to
be unique in whole VG.
2016-03-03 13:50:59 +01:00
0ab1110164 conf: regenerate example.conf.in 2016-03-03 13:50:59 +01:00
ff6e124a33 conf: add metadata/lvs_history_timeout configuration setting 2016-03-03 13:50:59 +01:00
74272e163d metadata: add vg_strip_outdated_historical_lvs fn and call it during VG read
The vg_strip_outdated_historical_lvs iterates over the list of historical LVs
we have and it shoots down the ones which are outdated.

Configuration hook to set the timeout will be in subsequent patch.
2016-03-03 13:50:59 +01:00
53b064b9ae commands: lvremove: also process historical LVs 2016-03-03 13:50:59 +01:00
f833a6d074 metadata: add historical_glv_remove 2016-03-03 13:50:57 +01:00
ccebf3100d conf: add metadata/record_lvs_history configuration setting
The metadata/record_lvs_history is global switch which enables or
disables recording historical LVs in metadata.

If both metadata/record_lvs_history=1 lvm.conf option and
--nohistory command switch is used at the same time, the
--nohistory prevails.
2016-03-03 13:49:15 +01:00
b1399090cd commands: lvremove: recognize --nohistory option 2016-03-03 13:49:15 +01:00
f545dd5952 metadata: honour 'nohistory' switch when removing thin LVs
When --nohistory switch is used with lvremove, the LV that is removed is
not recorded in metadata as 'historical LV'.
2016-03-03 13:49:15 +01:00
9a34de9cb9 cmd: add 'nohistory' option and wire it up in cmd_context
The --nohistory switch will cause historical LVs to not be recorded
in metadata on demand.
2016-03-03 13:49:15 +01:00
8f47119f6f report: add new 'none' lv_layout and 'history' lv_role and mark historical LVs that way
Report proper values for historical LVs in lv_layout and lv_role fields.
Any historical LV doesn't have any layout anymore and the role is "history".

For example:

$ lvs -H -o name,lv_attr,lv_layout,lv_role vg/-lvol1
  LV     Attr       Layout     Role
  -lvol1 ----h----- none       public,history
2016-03-03 13:49:15 +01:00
0339a5f447 report: add full_descendants field to display descendants with history
Same as lv_full_ancestors, but the other way round in the ancestry chain.
2016-03-03 13:49:15 +01:00
715f1fb4c4 report: add full_ancestors field to display ancestors with history
The lv_full_ancestors reporting field is just like the existing
lv_ancestors field but it also takes into account any history and
indirect relations recorded.
2016-03-03 13:49:15 +01:00
f228750386 report: report historical LV names with '-' prefix
All names for historical LVs are prefixed with '-' character to make clear
difference between live and historical LVs. The '-' can't be set by users
for live LV names during lvcreate hence we never get into a conflict with
the names that user defines for live LVs.
2016-03-03 13:49:15 +01:00
8b9953e8c5 report: display (h)istorical state in lv_attr field
The 'historical' state is displayed as 5th bit ("state") in the lv_attr
field and denoted by new 'h' character.
2016-03-03 13:49:15 +01:00
2af5971523 report: add lv_historical field to identify historical LVs
The lv_historical reporting field is a simple binary field that reports
whether an LV is historical one ("historical" value or value of "1" displayed)
or not (blank string "" or value of "0" displayed).
2016-03-03 13:49:15 +01:00
e112f5ce05 commands: lvs: recognize -H|--history switch
When lvs command is used together with the -H|--history switch,
all historical LVs are reported as well.
2016-03-03 13:49:14 +01:00
28f96d5ab6 report: display lv_name,lv_uuid,vg_name,lv_time and new lv_time_removed for historical LVs 2016-03-03 13:49:14 +01:00
2e7a121062 toollib: honour '-H|--history' switch while executing process_each_lv_in_vg
When processing LVs in a VG and when the -H|--history switch is used,
make process_each_lv_in_vg to iterate over historical volumes too.

For each historical LV, we use dummy struct logical_volume instance with
the "this_glv" reference set to a wrapper over proper struct
historical_logical_volume representation. This makes it possible to process
historical LVs just like normal live LVs (though a dummy one without any
segments and all the other fields zeroed and blank) and it also allows
for using all historical LV related information via lv->this_glv->historical
reference.

One can use a simple call to lv_is_historical to make a difference between
live and historical LV in all the code that is called by process_each_* fns.
2016-03-03 13:49:14 +01:00
f7e0a4cc18 cmd: add '-H|--history' switch and wire it up in cmd_context and processing_handle
This patch adds "include_historical_lvs" field to struct cmd_context to
make it possible for the command to switch between original funcionality
where no historical LVs are processed and functionality where historical
LVs are taken into account (and reported or processed further). The switch
between these modes is done using the '-H|--history' switch on command
line.

The include_historical_lvs state is then passed to process_each_* fns
using the "include_historical_lvs" field within struct processing_handle.
2016-03-03 13:49:14 +01:00
baee45a103 metadata: add lv_is_historical fn to test if the LV is historical one 2016-03-03 13:49:14 +01:00
673bc0636c metadata: format_text: interconnect historical LVs among each other and also with live LVs
Interconnect historical LVs in an ancestry chain and also connect the first/last
one with its live ancestor/descendant if it exists.
2016-03-03 13:49:13 +01:00
a61bc70f62 metadata: add support for interconnection of thin pool LV segment with indirect origin
Add support for making an interconnection between thin LV segment and
its indirect origin (which may be historical or live LV) - add a new
"indirect_origin" argument to attach_pool_lv function.
2016-03-03 13:46:40 +01:00
c45af2df4e metadata: add find_historical_glv fn
The find_historical_glv is helper function that looks up historical
LV in struct volume_group's historical_lvs list and returns it if
found.
2016-03-03 13:46:39 +01:00
a0842d1f25 metadata: format_text: import historical LVs
Import historical LV list from metadata and add it to struct
volume_group's historical_lvs list.
2016-03-03 13:46:39 +01:00
54d3d976c7 metadata: format_text: reuse _print_timestamp fn 2016-03-03 13:46:39 +01:00
3a0ef77305 metadata: format_text: also export historical LVs
Also export historical LVs when exporting LVM2 metadata.
This is list of all historical LVs listed in
"historical_logical_volumes" metadata section with all
the properties exported for each historical LV.

For example, we have this thin snapshot sequence:

  lvol1 --> lvol2 --> lvol3
                 \
                  --> lvol4

We end up with these metadata:

logical_volume {
  ...
  (lvol1, lvol3 and lvol4 listed here as usual - no change here)
  ...
}

historical_logical_volumes {
  lvol2 {
    id = "S0Dw1U-v5sF-LwAb-W9SI-pNOF-Madd-5dxSv5"
    creation_time = 1456919613      # 2016-03-02 12:53:33 +0100
    removal_time = 1456919620       # 2016-03-02 12:53:40 +0100
    origin = "lvol1"
    descendants = ["lvol3", "lvol4"]
  }
}

By removing lvol1 further, we end up with:

historical_logical_volumes {
  lvol2 {
    id = "S0Dw1U-v5sF-LwAb-W9SI-pNOF-Madd-5dxSv5"
    creation_time = 1456919613      # 2016-03-02 12:53:33 +0100
    removal_time = 1456919620       # 2016-03-02 12:53:40 +0100
    origin = "-lvol1"
    descendants = ["lvol3", "lvol4"]
  }

  lvol1 {
    id = "me0mes-aYnK-nRfT-vNlV-UiR1-GP7r-ojbROr"
    creation_time = 1456919608      # 2016-03-02 12:53:28 +0100
    removal_time = 1456919767       # 2016-03-02 12:56:07 +0100
  }
}
2016-03-03 13:46:18 +01:00
790b2e8748 metadata: create historical LVs when LVs are removed and interconnect with live LVs
When an LV is being removed, we create an instance of
"struct historical_logical_volume" wrapped up in
"struct generic_logical_volume".

All instances of "struct historical_logical_volume" are then recorded in
"historical_lvs" list which is part of "struct volume_group".

The "historical LV" is then interconnected with "live LVs" to
connect a history chain for the live LV.
2016-03-03 11:26:51 +01:00
eeaa5a4481 metadata: add add_glv_to_indirect_glvs and remove_glv_from_indirect_glvs
The add_glv_to_indirect_glvs is a helper function that registers a
volume represented by struct generic_logical_volume instance ("glv")
as an indirect user of another volume ("origin_glv") and vice versa -
it also registers the other volume ("origin_glv") as indirect_origin
of user volume ("glv").

The remove_glv_from_indirect_glvs does the opposite.
2016-03-03 11:26:51 +01:00
937f72b168 metadata: add get_or_create_glv and get_or_create_glvl
The get_or_create_glv is helper function that retrieves any existing
generic_logical_volume wrapper for the LV. If the wrapper does not exist
yet, it's created.

The get_org_create_glvl is the same as get_or_create_glv but it creates
the glv_list wrapper in addition so it can be added to a list.
2016-03-03 11:26:51 +01:00
e573eca554 metadata: add infrastructure to track LV history
Add new structures and new fields in existing structures to support
tracking history of LVs (the LVs which don't exist - the have been
removed already):

  - new "struct historical_logical_volume"
    This structure keeps information specific to historical LVs
    (historical LV is very reduced form of struct logical_volume +
     it contains a few specific fields to track historical LV
     properties like removal time and connections among other LVs).

  - new "struct generic_logical_volume"
    Wrapper for "struct historical_logical_volume" and
    "struct logical_volume" to make it possible to handle volumes
    in uniform way, no matter if it's live or historical one.

  - new "struct glv_list"
    Wrapper for "struct generic_logical_volume" so it can be
    added to a list.

  - new "indirect_glvs" field in "struct logical_volume"
    List that stores references to all indirect users of this LV - this
    interconnects live LV with historical descendant LVs or even live
    descendant LVs.

  - new "indirect_origin" field in "struct lv_segment"
    Reference to indirect origin of this segment - this interconnects
    live LV (segment) with historical ancestor.

  - new "this_glv" field in "struct logical_volume"
    This references an existing generic_logical_volume wrapper for this
    LV, if used. It can be NULL if not needed - which means we're not
    handling historical LVs at all.

  - new "historical_lvs" field in "struct volume group
    List of all historical LVs read from VG metadata.
2016-03-03 11:26:51 +01:00
5e718ec666 tests: drop check for md5sum 2016-03-03 10:17:03 +01:00
49839b6d96 tests: check kernel_cache_ funcs 2016-03-03 10:17:03 +01:00
e04a0184cb cleanup: use lv_is_partial
Check for PARTIAL_LV flag in standard way.
2016-03-03 10:17:03 +01:00
a975dc530e cleanup: use _field_string
Make at least some 'advantage' in use local func and do dereference
internally from char pointer and use short list of params.
2016-03-03 10:17:03 +01:00
25bf0beedb man: minor updates
Minor fixes in few pages.
2016-03-03 10:17:03 +01:00
fd349cb2e5 man: lvconvert updates
Improving style (following lvcreate way).
Sorting options alphabetically.
2016-03-03 10:17:03 +01:00
88ce15004e cache: add kernel_cache_policy option
Pair kernel_cache_settings with kernel_cache_policy.
There is very small chance in error case that the value in table
might be differnet from the value stored in metadata
so make it 'checkable'.
2016-03-03 10:14:23 +01:00
3d610fabbd WHATS_NEW: [unknown] replaces 'unknown device' 2016-03-01 11:16:35 -06:00
57cd94b9e3 pvs: replace 'unknown device' with [unknown]
A config setting can restore the old string.
2016-03-01 11:12:03 -06:00
afae3355f8 cleanup: missplaced .
Remove misplaced '.' after '?'
Drop extra   'stack;'  after log_debug().
2016-03-01 17:20:47 +01:00
058eb3739d makefile: handle dm-version-expected 2016-03-01 16:03:02 +01:00
3b93c11030 man: fix mising braces
Fixing some reported issued found by:
http://catb.org/~esr/doclifter/bugs.html

Reported-by: Eric S. Raymond <esr at thyrsus.com>
2016-03-01 14:02:43 +01:00
872d5922e1 cleanup: indent and dots 2016-03-01 14:02:43 +01:00
36d0dcef38 coverity: eliminate DEADCODE
Coverity notice this cannot be NULL: cur = &dms->regions[*cur_r]
so avoid NULL checking and simplify form.
2016-03-01 14:02:43 +01:00
8173c2ff9a coverity: missing error path 2016-03-01 14:02:43 +01:00
b2d819eafa update WHATS_NEW
including changes not recorded for the previous release.
2016-02-29 13:50:02 -06:00
e3b904fd08 tests: check [unknown] in lvmetad-pvscan-cache
Update test for new [unknown] VG name from
commit 250b9153.
2016-02-29 12:43:07 -06:00
250b915364 pvs: display VG name [unknown] for used PV without metadata
Rather than displaying a blank field for VG name.
2016-02-29 11:17:55 -06:00
4013e21ba8 post-release 2016-02-26 21:14:12 +00:00
731a9c1354 pre-release 2016-02-26 21:03:30 +00:00
9898126596 report: Shift (u)sed pv_attr under (a)llocatable.
Showing 'u' in the pv_attr reporting field is mostly unnecessary because
most PVs are allocatable, and being allocatable implies it is (u)sed,
and this is already obvious from other fields in the default 'pvs'
output like the VG name.

So move the new (u)sed pv_attr from character position 4 to 1, and only
show it in those rare cases when the PV is not (a)llocatable or the
relevant metadata is missing.

(Scripts should not be using pv_attr, but rather pv_allocatable,
pv_exported, pv_missing, pv_in_use etc.)
2016-02-26 15:46:37 +00:00
183bd8ca03 tests: skip on older version
Skip with older driver version.
Update address.
2016-02-26 10:21:36 +01:00
2988fa3c21 coverity: helping coverity with NULL pointer
Helping with understanding we will not try to deref NULL pointer,
as if the sizes are initialized to NULL it also means 'mem' would
be NULL, but thats too hard to model so make it obvious.
2016-02-26 10:21:36 +01:00
85a593c191 makefiles: add more dirs for lcov output
New daemons were missing in generated lcov output.
2016-02-26 10:21:34 +01:00
3e31f51869 dbus: fix the systemd service providing the DBus service
Correct name is lvm2-lvmdbusd.service not lvmdbusd.service.
This makes the bus-activation (auto-activation) work.

Signed-off-by: Vratislav Podzimek <vpodzime@redhat.com>
2016-02-26 10:20:08 +01:00
88530b2ef3 pvcreate: fix data alignment error check
Make the data_alignment variable 64 bits so it
can hold the invalid command line arg used in
pvreate-usage.sh pvcreate --dataalignment 1e.

On 32 bit arches, the smaller variable wouldn't
hold the invalid value so the error would not
trigger as expected by the test.
2016-02-25 17:02:18 -06:00
081359f6cd lvmdbusd: Do only 1 refresh for Vg.Change()
Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-25 16:43:56 -06:00
26b826ccf5 lvmdbusd testing: Add validatestate.py utility
This simple tool calls the Manager.Refresh method on the dbus service
to check and see if the dbus service has the most up to date state.
This is to be used for testing to ensure that event driven updates are
working as planned.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-25 16:43:55 -06:00
0d620e681f lvmdbustest.py: Move helper code to testlib.py
This will allow us to re-use in other client programs for testing.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-25 16:43:55 -06:00
f1bc68beb4 lvmdbusd: Reduce unnecessary state refreshes
When we use udev or have lvm call back into the dbus service when a
change occurs, even if that change originated from the dbus service
we end up refreshing the state of the system twice which is not
needed or wanted.  This change handles this case by removing any
pending refreshes in the worker queue if the state of the system
was just updated.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-25 16:43:55 -06:00
045d086a57 pvcreate: fix error from pv_write
After a pv_write() failure, the PV wasn't being skipped.
2016-02-25 16:40:24 -06:00
23a4801dbc tests: lvresize with zero arg 2016-02-25 23:30:26 +01:00
1a9f743eef cleanup: drop unneeded test
dmfree tests for NULL
2016-02-25 23:30:25 +01:00
e9b523e304 cleanup: indent
Last update missed to indent params.
2016-02-25 23:30:25 +01:00
5c29b54d4d cleanup: poll better check for internal errors 2016-02-25 23:30:25 +01:00
cdcf4cc794 lvconvert: use lp->repair
Set variable for repair testing.
2016-02-25 23:30:25 +01:00
ec8a75a321 lvconvert: use more display_lvname 2016-02-25 23:30:25 +01:00
86a651854f lvconvert: simplify handler processing
Easier code for handler init.
Drop release of pool mem - not needed, as command pool get dropped just
later.
2016-02-25 23:30:25 +01:00
abd9618dd8 lvconvert: fix vg parameter
Since we want to read env LVM_VG_NAME vg names,
we cannot just check LV names which do contain '/'.

So before the patch commands like:

> lvconvert --repair vg

Before:

Please provide a valid volume group name

After:
Path required for Logical Volume "vg".
Please provide a valid volume group name

> LVM_VG_NAME=vg lvconvert --repair vg

Before:
Please provide a valid volume group name

After:
Can't find LV vg in VG vg
2016-02-25 23:30:24 +01:00
a68e601886 lvresize: fix regression with zero size arg
Commit ca878a3426 introduced an issue
that zero sized extesion suddenly started to be accepted and
missed to return error.

Properly check invalid input values for sizes.
2016-02-25 23:29:57 +01:00
172bad0d56 Use a common message for a used PV
Change some inconsistent messages and adopt
the new wording "PV %s is used by" in place
of "PV %s is marked as belonging to"
or "PV %s belongs to".
2016-02-25 14:23:41 -06:00
66e175702a pvcreate: fix setting uuid arg
Commit 4de6caf5 ("redefine pvcreate structs") left
out setting the "idp" pointer to the "id" arg.
2016-02-25 12:00:53 -06:00
79f2596215 tests: add simple dmstats report tests
Add tests for the "dmstats report" command:

  * report
  * report --count
  * report --histogram

So far the tests just check the command runs as expected when a
correctly configured stats region exists: validation of output
can be added later.
2016-02-25 16:40:59 +00:00
3d3b132d9a tests: add dmstats create tests
Add tests for the "dmstats create" command:

  * simple whole-device region
  * region using --start/--len options
  * region using --segments option
  * region with precise timestamps (--precise)
  * region with histogram bounds (--bounds)
2016-02-25 16:40:59 +00:00
11fd7b7c64 tests: make lib/expected-version-dm a dependency of .tests-stamp 2016-02-25 16:40:59 +00:00
d4a5c252c5 tests: install does not depend on lib/version-expected
The install target already depends on .tests-stamp - since this
in turn depends on lib/version-expected there is no need to have
this as a dependency of install.
2016-02-25 16:40:59 +00:00
2d630ea78a tests: add template tests/shell/dmstats-create.sh
Add a template for testing 'dmstats create' operations.
2016-02-25 16:40:58 +00:00
3dae416229 tests: add driver_at_least() to aux.sh
Add a function to test whether the running device-mapper driver
version is at least equal to some given version.
2016-02-25 16:40:58 +00:00
1f8fd5a152 tests: add basic dmstats tests
Add initial dmstats tests to 000-basic.sh. These tests ensure that
the dmsetup binary is built and linked correctly when called as
'dmstats' and that the version of the binary matches the expected
library version used for the build.
2016-02-25 16:40:58 +00:00
985ed7822f dmstats: create dmstats symlink in test/lib
Create a symbolic link in test/lib for 'dmstats', pointing to the
dmsetup binary in the tools/ build directory.
2016-02-25 16:40:58 +00:00
42ae586fa7 lvmcache: fix missing free of vginfo->system_id causing mem leak 2016-02-25 16:25:27 +01:00
a77ded3001 replace pvcreate_params with pvcreate_each_params
"pvcreate_each_params" was a temporary name used
to transition from the old "pvcreate_params".

Remove the old pvcreate_params struct and rename the
new pvcreate_each_params struct to pvcreate_params.
Rename various pvcreate_each_params terms to simply
pvcreate_params.
2016-02-25 09:14:10 -06:00
4de6caf5b5 redefine pvcreate structs
New pv_create_args struct contains all the specific
parameters for creating a PV, independent of the
command.
2016-02-25 09:14:10 -06:00
c201ee09bd metadata: add fixme about code used only by liblvm 2016-02-25 09:14:10 -06:00
04d34da706 pvremove: use common toollib processing code
Use the new pvcreate_each_device() function from
toollib.
2016-02-25 09:14:09 -06:00
30c69b3f8a toollib: remove unsed pvcreate params function
which has been replaced by an equivalent pvcreate_each params
function.
2016-02-25 09:14:09 -06:00
0cd7d2332c liblvm: replace pvcreate_single with pvcreate_vol
And remove the pvcreate_single wrapper.
2016-02-25 09:14:09 -06:00
a9940bd3c9 vgcreate: use the common toollib pv create
Use the new pvcreate_each_device() function from
toollib, previously added for pvcreate, in place
of the old pvcreate_vol().

This also requires shifting the location where the
lock is acquired for the new VG name.  The lock for
the new VG is supposed to be acquired before pvcreate.
This means splitting the vg_lock_newname() out of
vg_create(), and calling vg_lock_newname() directly
before pvcreate, and then calling the remainder of
vg_create() after pvcreate.

The new function vg_lock_and_create() now does
vg_lock_newname() + vg_create(), like the previous
version of vg_create().

The lock on the new VG name is released before the
pvcreate and reacquired after the pvcreate because
pvcreate needs to reset lvmcache, which doesn't work
when locks are held.  An exception could likely be
made for the new VG name lock, which would allow
vgcreate to hold the new VG name lock across the
pvcreate step.
2016-02-25 09:14:09 -06:00
749a7cecf8 vgextend: use the common toollib pv create 2016-02-25 09:14:09 -06:00
6a1c22aadf pvcreate: use the common toollib pv create 2016-02-25 09:14:09 -06:00
71671778ab toollib: add two phase pv processing code
This is common code for handling PV create/remove
that can be shared by pvcreate/vgcreate/vgextend/pvremove.
This does not change any commands to use the new code.

- Pull out the hidden equivalent of process_each_pv
  into an actual top level process_each_pv.

- Pull the prompts to the top level, and do not
  run any prompts while locks are held.
  The orphan lock is reacquired after any prompts are
  done, and the devices being created are checked for
  any change made while the lock was not held.

Previously, pvcreate_vol() was the shared function for
creating a PV for pvcreate, vgcreate, vgextend.
Now, it will be toollib function pvcreate_each_device().

pvcreate_vol() was called effectively as a helper, from
within vgcreate and vgextend code paths.
pvcreate_each_device() will be called at the same level
as other process_each functions.

One of the main problems with pvcreate_vol() is that
it included a hidden equivalent of process_each_pv for
each device being created:

  pvcreate_vol() -> _pvcreate_check() ->

   find_pv_by_name() -> get_pvs() ->

     get_pvs_internal() -> _get_pvs() -> get_vgids() ->

       /* equivalent to process_each_pv */
       dm_list_iterate_items(vgids)
         vg = vg_read_internal()
         dm_list_iterate_items(&vg->pvs)

pvcreate_each_device() reorganizes the code so that
each-VG-each-PV loop is done once, and uses the standard
process_each_pv function at the top level of the function.
2016-02-25 09:14:09 -06:00
ff2267012a vgconvert: refactor to avoid pvcreate code
This uses the vg->pv_write_list in place of the
vg->pvs_to_write list, and eliminates the use of
pvcreate_params.  The label remove and zeroing
steps are shifted out of vg_write() to the higher
level like pvcreate will do.
2016-02-25 09:14:09 -06:00
5dd615c41e metadata: use pv_write_list for _check_old_pv_ext_for_vg
The _check_old_pv_ext_for_vg() function only needs to
do pv_write(), so it can use the simpler pv_list structs
on the pv_write_list.
2016-02-25 09:14:09 -06:00
bafbc72c8c metadata: refactor part of add_pv_to_vg
This shifts the use of the 'pv_to_write' struct
and the 'pvcreate_params' struct to the one
caller of add_pv_to_vg, which is made static.
2016-02-25 09:14:09 -06:00
5e5ad77f5f vg_write: add list of pvs to write
The vg->pv_write_list contains pv_list structs for which
vg_write() should call pv_write().

The new list will replace vg->pvs_to_write that contains
vg_to_create structs which are used to perform higher-level
pvcreate-related operations. The higher level pvcreate
operations will be moved out of vg_write() to higher levels.
2016-02-25 09:14:09 -06:00
3ac860334b configure 2016-02-25 13:58:48 +00:00
718a695b0c configure: require sanlock 3.3.0
For a sanlock flag added in that version.
2016-02-24 13:22:23 -06:00
664fa6d1be lvmlockd: use new sanlock flag to avoid blocking
This flag allows sanlock requests to avoid all blocking.
2016-02-24 10:10:59 -06:00
77f034bfa3 tests: include lvmlockd in default make check 2016-02-23 16:34:46 -06:00
e793253084 lvmlockd: fix sparse snapshot case
A snapshot can be created without a real origin LV
in this case, so there's no lock to use.
2016-02-23 15:45:25 -06:00
79809d6cdc cleanup: use sizeof instead of macro.
Keep the buffer size defined at a single place and then use
its sizeof.
2016-02-23 21:40:17 +01:00
9267e0c5e7 cleanup: use braces around macro params 2016-02-23 21:40:17 +01:00
63c052b9e2 coverity: ensure thin_pool_seg is not NULL
thin_pool_seg being NULL would be an internal error.
2016-02-23 21:40:17 +01:00
ddfec5b51a coverity: use same arithmetic for both major and minor
Run all arithmetic in the same 'dev_t' type.
2016-02-23 21:40:17 +01:00
9e3a9eab0e coverity: check for dm_snprintf
Check return state like everywhere else.
2016-02-23 21:40:17 +01:00
a9634e993a coverity: check cmd pointer exists
Since in _report_init() we check few times for cmd != NULL
keep it consistent and Coverity happier.
2016-02-23 21:40:16 +01:00
68955a8102 coverity: ensure non-null pointers are used
Here is too complex for Coverity to guess
those pointers cannot be NULL, but it's
very easy to add little checks here.
2016-02-23 21:40:16 +01:00
9b92cb2760 coverity: drop unused assignments 2016-02-23 21:40:16 +01:00
eaaae185b7 coverity: check for zero length buffer
When get_shared_library_path() would got zero length buffer,
it could have underflow in size calc later.
So just put extra small check for this case.
2016-02-23 21:40:16 +01:00
b08eb91df1 coverity: check for info pointer existance
Since we already check in few other places  'info' is not NULL,
do the same for others - however when info would be NULL
it more or less looks like internal error.
2016-02-23 21:40:16 +01:00
2e168a52b0 coverity: drop unneeded header 2016-02-23 21:40:12 +01:00
6d6e063a0f libdm: fix string boundary
The test for string 'end' needs to account for ending \0,
which also needs to fit <SIZE.
2016-02-23 21:38:52 +01:00
eccc91f9b0 lvmlockd: set default result value
The default error value should be set indicating
an error.
2016-02-23 14:35:40 -06:00
0236a34224 tests: updates for check_lvmlockd
Move the lvmlockd-related setup functions into aux.

For check_lvmlockd_test, start a new instance of
lvmlockd --test for each shell test.
2016-02-23 14:00:28 -06:00
42da7a6c38 make: Add check_lvmlockd_* targets to top-level 2016-02-23 18:34:46 +01:00
f54253d396 tests: add SKIP_WITH_LVMLOCKD
to all tests that don't already used vgcreate $SHARED
2016-02-23 09:28:48 -06:00
5d7e83c73c tests: check warn about belong is printed 2016-02-23 14:41:24 +01:00
c0b836e316 gcc: logical-op warning go away
Don't be too much inventive and shutdown gcc6 warning:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69602
2016-02-23 14:41:24 +01:00
05cc1b87a9 gcc: cleanup Wunused-const-variable
Use #define instead, since we do not require actually buffer needs
to exists to eliminated new gcc6 warning:

clvm.h:53:19: warning: ‘CLVMD_SOCKNAME’ defined but not used
[-Wunused-const-variable]
2016-02-23 14:41:24 +01:00
e717ce555b pvremove: add warn when removing PV in use
Reshuffle messages during pvremove.

Always print WARNING: when PV is in use so using options
--force --force doesn't make this important user
notification go away.

Simplify variable 'used' usage (so older gcc doesn't warn
about the use of unitilizied variable).

Add some '.' into messages.
2016-02-23 14:40:30 +01:00
7d8a67714f cleanup: drop double ; 2016-02-23 12:25:25 +01:00
dbc71dc05e gcc: cleanup some sign warnings
When comparing unsigned with int, the comparision is made
as 'unsigned' type, so make it rather explicit which type
is being compared.
2016-02-23 12:25:25 +01:00
293aabe4cd cache: enforce header check
Currently it's been checked for 'zero' header for thin-pool,
but lets use it always for cache as well - since it's relatively 'cheap'
detection of read 'error' problems as thin/cache tools
currently do not work fast enough in this case.
2016-02-23 12:25:25 +01:00
f501f083bf thin: fix read size compare
Fix the compare with 'unsigned' sizeof() and error read -1 result.
So the read error is correctly recognized.
2016-02-23 12:22:18 +01:00
05eb87ca2d lvmdbusd: Initial unit test driver script
It's disabled until we can fix it up.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-22 16:07:54 -06:00
ecc0406886 lvmdbusd: Remove unlimited retries
Change while to for loop to prevent the daemon from getting stuck
when lvm is messed up.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-22 16:07:54 -06:00
21034644b6 lvmdbusd: Add env variable to use session bus
export LVMDBUSD_SESSION=True to run on the session bus instead
of the system bus so that we can run the unit test without
installing the dbus conf file.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-22 16:07:54 -06:00
64aab5885d lvmdbus: Make unit tests work in test env
Reduced the size of LVs created and use actual PE numbers instead of hard
coding them to allow us to work with the loop back devices.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-22 16:07:54 -06:00
70d0b210e1 lvmdbusd: background.py, fix stdout parse error
It appears that the output of lvconvert --merge can vary some.  The code
was blowing up as it was trying to parse a line of stdout to retrieve the
% complete, but the line did not have the needed format and an execption
was thrown.  The uncaught exception caused the background thread to exit
without updating the job object, which caused the client to hang forever
waiting.  Added a default exception handler to prevent unhandled execptions
causing hangs and removed the parameter skip_first_line as it's no longer
needed.  The code checks to see if the line can be parsed before doing so.

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-22 16:07:54 -06:00
d7dd8bf9d6 lvmdbustest.py: Make executable
Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-22 16:07:54 -06:00
f4efc2435c tests: fix clean up after lvmlockd tests 2016-02-22 14:15:17 -06:00
ec81c42179 lvmdbusd: Fix make install for python >= 3.5
python 3.5 renamed .pyo files to .opt-1.pyc.
2016-02-22 18:16:41 +01:00
367fb85e44 spec: Fix 04ab1fa572: Remove left-overs 2016-02-22 17:50:35 +01:00
c716813651 lvmlockd: invalidate name in lockspace struct after remove
After the lockspace has been successfully removed,
invalidate the name field in the lockspace struct.
The struct remains on the list of lockspaces until
the struct can be freed later.  Until the struct is
freed, its name will prevent another new lockspace
from being created with the same name.
2016-02-22 09:36:35 -06:00
161ae36363 test: add make check_lvmlockd_test
Which runs lvmlockd in --test mode, without
any lock manager.

Also make some adjustments to the check_lvmlockd
variations using the lock managds.
2016-02-22 09:36:35 -06:00
ed5e5c38b5 tests: skip thin-flags test on 32bit el6 kernel
Until kernel is fixed, stop running test always hitting OOPS there.
2016-02-22 14:59:28 +01:00
3178cfc818 cleanup: use char arrays. 2016-02-22 14:27:44 +01:00
2d6ef123a6 cleanup: indent changes
Some code indention.
Use dm_strncpy() for simplier code.

TODO: we could possibly use   %32s  for printing pvid...
so maybe adding extra  FMT_PVID....
2016-02-22 14:26:15 +01:00
fba54ae55e cleanup: libdm clang warnings
Add some extra clang pointer validation so we do not try deref NULL.
2016-02-22 14:18:28 +01:00
275c9f7e77 libdm: grow with initialized struct content
Coverity noticed struct hist has been copied uninitalized into mempool.
2016-02-22 14:17:32 +01:00
30a73d1604 lvmetad: fix error path
Coverity noticed the internal error path would  be using uninit struct.
So always make sure reply is initilized.
2016-02-22 14:15:53 +01:00
44b3909e58 post-release 2016-02-21 23:37:48 +00:00
3ef36f05b6 pre-release 2016-02-21 23:17:24 +00:00
8b6cad3219 lvmdbustest.py: resync latest changes
This file update was missed, copied latest file from:
https://github.com/tasleson/lvm-dubstep/blob/master/test/lvmdbustest.py

Signed-off-by: Tony Asleson <tasleson@redhat.com>
2016-02-19 15:16:05 -06:00
eefcbd5b28 thin: fix update_pool_lv error path
When update fails in suspend() (sending of messages
fails because metadata space is full) call resume(),
so the locking sequence works properly for clustering.

Also failing deactivation should unlock memory.
2016-02-19 11:25:56 +01:00
04ab1fa572 spec: Update python bindings and dbus-service
The workaround for python3 is no longer needed.
2016-02-18 20:46:03 +01:00
a89ddda1a2 tests: needs_check needs version 16
Skip part of test when driver is too old.
2016-02-18 18:11:29 +01:00
42b394c142 thin: fix test for nonexisting status
Check status has right type.
2016-02-18 18:11:29 +01:00
bcf7f80791 tests: checking thin flags
Test various  (D/M/F) attrs for thin-pool/thin
2016-02-18 16:49:38 +01:00
485bce1ae3 man: lvs updates 2016-02-18 16:49:38 +01:00
f31d596c0d thin: report needs_check and fail state
Fix reporting of Fail thin-pool target status
as attr[8] letter 'F'.

Report  'needs_check' status from thin-pool target via
attr field [4] (letter 'c'/'C'), and also via CheckNeeded field.

TODO: think about better name here?
TODO: lots of prop_not_implemented_set
2016-02-18 16:49:34 +01:00
0358ca3aad thin: report PERCENT_INVALID for failed pool
When thin-pool is in failed/error state, we can't
read percentage so report invalid value.
2016-02-18 16:45:42 +01:00
0fb3669d49 libdm: thin status update
Fix parsing of 'Fail' status (using capital letter) for thin-pool.
Add also parsing of 'Error' state for thin-pool.
Add needs_check test for thin-pool.

Detect Fail state for thin.
2016-02-18 16:45:42 +01:00
ecfa465366 metadata: ask for confirmation before really initializing/removing PV that is marked as belonging to a VG
Ask for confirmation when using pvcreate/pvremove on a PV which is
marked as belonging to a VG, just like we do in case of a PV which
belongs to known VG:

$ pvcreate -ff /dev/sda
Really INITIALIZE physical volume "/dev/sda" that is marked as belonging to a VG [y/n]? n
  /dev/sda: physical volume not initialized

$ pvremove -ff /dev/sda
Really WIPE LABELS from physical volume "/dev/sda" that is marked as belonging to a VG [y/n]? n
  /dev/sda: physical volume label not removed
2016-02-18 14:33:54 +01:00
1a141e8623 lbmdbusd: Support in-tree testing. 2016-02-18 13:26:08 +00:00
ef5583a209 Fix rpm builds 2016-02-18 12:37:44 +01:00
bc19a16fc7 report: report -1, not 'unkown' for lv_{snapshot_invalid,merge_failed} with --binary
State:
$ lvs -o lv_name,lv_active_locally,lv_snapshot_invalid,lv_merge_failed vg/lvol0
  LV    ActLocal       SnapInvalid     MergeFailed
  lvol0 active locally         unknown         unknown

Now with using --binary switch.

Before this patch (lv_snapshot_invalid and lv_merge_failed not switched into numeric value
where -1 represents 'unknown' value)
$ lvs -o lv_name,lv_active_locally,lv_snapshot_invalid,lv_merge_failed vg/lvol0 --binary
  LV    ActLocal   SnapInvalid     MergeFailed
  lvol0          1         unknown         unknown

With this patch applied:
$ lvs -o lv_name,lv_active_locally,lv_snapshot_invalid,lv_merge_failed vg/lvol0 --binary
  LV    ActLocal   SnapInvalid     MergeFailed
  lvol0          1              -1              -1
2016-02-18 12:10:00 +01:00
e5fc48411a configure: Use python-config if python2-config not found.
Assume that's good enough for older systems.
2016-02-18 02:10:35 +00:00
7dce72ee18 . 2016-02-18 01:50:36 +00:00
6af2ce6244 lvmdbusd: Rename module to lvmdbusd 2016-02-18 01:14:56 +00:00
887e96ded7 autoconf: Fix py-compile permissions 2016-02-18 01:05:05 +00:00
0f353e2053 lvmdbus: resync latest changes with original repo 2016-02-18 00:27:57 +00:00
545e58fd18 WHATS_NEW 2016-02-18 00:01:02 +00:00
5987562cf9 lvmdbus: Add new daemon. 2016-02-17 23:53:35 +00:00
055c628e38 man: fix list of restricted LV name suffixes 2016-02-17 15:38:27 +01:00
065526c590 metadata: add missing _repair_inconsinstent_vg call during PV ext repair 2016-02-17 10:19:55 +01:00
b077e7374f metadata: do not repair missing PV_EXT_USED flag for PVs belonging to foreign VG
The host that owns foreign VGs is responsible for fixing up PV_EXT_USED
flag - the same already applies to repairing any inconsistent VG.

This patch also moves the iteration over vg->pvs inside
_check_or_repair_pv_ext fn - it's cleaner this way.
2016-02-17 10:19:24 +01:00
13f3e92632 refactor: add common _is_foreign_vg fn 2016-02-16 13:44:48 +01:00
45be3c875f pv: use pv->fmt to check for fake PVs, not pv->vg
pv->vg is not set yet during pvcreate processing. Use pv->fmt instead to
check for these fake PVs (all normal PVs have format defined, devices
which are not PVs don't have this set).

This fixes commit 0000db7f98.
2016-02-15 15:52:13 +01:00
099d99975c cleanup: make the message about marked PVs consistent with the others 2016-02-15 15:20:23 +01:00
cc9e683adc toollib: skip PV if system ID is used and PV marked as used but metadata missing
If we know that a PV belongs to some VG and we're missing metadata
(because we have only those PV(s) from VG present in the system that
don't have metadata areas), we should skip such PV when processing
under system ID.

This is because we know that the PV belongs to some VG, but we
really can't decide whether it matches system ID unless the VG
metadata is present again.
2016-02-15 15:17:36 +01:00
0000db7f98 pv: mark fake PVs as not used
Some of the PVs are not even orphan PVs - they're fake PVs - this can
happen if we're listing all devices with "pvs -a". Such PV must not
be marked as used.
2016-02-15 14:46:31 +01:00
abbaeef096 cleanup: use is_used_pv fn to detect whether PV is in use while reporting pv_free field 2016-02-15 13:30:37 +01:00
698e0eb851 WHATS_NEW: PV_EXT_USED flag and related 2016-02-15 13:07:35 +01:00
8ad93874d6 tests: fix tests checking pv_attr - there's a new bit now 2016-02-15 12:44:46 +01:00
a4e25f4381 tests: add pv-ext-flags.sh test
Testing PV extension flags. Currently, there's only one PV extension
flag present - the PV_EXT_USED flag (marking PV as used in a VG).
2016-02-15 12:44:46 +01:00
2f00d57e6f vg: automatically update to newest PV ext version during vg_write 2016-02-15 12:44:46 +01:00
9b9f1ae772 format: format_text: add pv_needs_rewrite to format_handler and implemention for format_text 2016-02-15 12:44:46 +01:00
08de88535e report: identify used PVs in pv_attr field with 'u' char 2016-02-15 12:44:46 +01:00
db494d7d34 report: always display 0 for pv_free field if we don't have any mda and PV is marked as used at the same time 2016-02-15 12:44:46 +01:00
d84a80afb5 backup: backup_restore_vg: register PVs that need writing via vg->pvs_to_write list
The backup_restore_vg is used directly for restoring the VG from backup.
It's also used to do the VG conversions from one metadata format to
another which means vgconvert calls backup_restore_vg too.

When restoring VG from backup, we need to rewrite/write PV headers as
PVs may have been orphans before and now they're becoming part of some
VG - we need to write the PV_EXT_USED flag at least.

When using the backup_restore_vg for vgconvert, we need to write
completely new PV header in different format.

Avoid the special "pv_write" call and handling that was used before
this patch in vgconvert (vgconvert_single function to be more precise)
and reuse existing internal interface to register PV header for writing
(or rewriting) via vg->pvs_to_write list instead like we do it elsewhere
in the code.

This patch also resolves a problem in which PV headers with target
format were written in the vgconvert_single fn as orphans and VG
metadata were added later on - this was a tiny hack actually.
We can't do this now - we need to write the PV as belonging
to a VG because otherwise the PV_EXT_USED flag won't be written
properly (if the PV header is written as orphan, the PV_EXT_USED
is set to 0, of course, even though metadata are attached later).
So this patch removes this tiny inconsistency which was passing
just fine before because we didn't have any relation to the VG
in PV header before. Now we have the PV_EXT_USED flag which says
the "PV is used in some VG".
2016-02-15 12:44:46 +01:00
531ced90dc metadata: _vg_read: check if PV_EXT_USED flag is set correctly for non-orphan PVs and do a repair if needed
The same check as we already do for orphan PVs, just the other way
round now: if the PV is surely part of some VG and any PV the VG
contains does not have the PV_EXT_USED flag set, repair it.

For example - /dev/sda here is in VG vg and it's incorrectly not
marked as used by PV_EXT_USED flag:

pvs --binary -o pv_ext_vsn,pv_in_use
  WARNING: Volume Group vg is not consistent.
  WARNING: Repairing Physical Volume /dev/sda that is in Volume Group vg but not marked as used.
  PV         VG     Fmt  Attr PSize   PFree   ExtVsn PInUse
  /dev/sda   vg     lvm2 a--  124.00m 124.00m      2      1
2016-02-15 12:44:46 +01:00
f75e42c06c report: add pv_ext_vsn field to display PV header extension version used
For example:

$ pvs -o pv_name,vg_name,pv_ext_vsn,pv_in_use
  PV         VG     ExtVsn InUse
  /dev/sda               2
  /dev/sdb   vg          2    used
  /dev/vda2  fedora      1    used
2016-02-15 12:44:46 +01:00
e0b1415105 metadata: check for PV extension version before doing any checks on PV extension flags
PV header extension versions:
  0 - the original PV without any extensions
  1 - bootloader area support added
  2 - PV_EXT_USED flag support added

So do the associated checks related to PV_EXT_USED flag only if
PV header extension found is of version 2 and higher.
2016-02-15 12:44:46 +01:00
d97f1c89de metadata: _vg_read: check if PV_EXT_USED flag is set correctly for orphan PVs and do a repair if needed
If we know that the PV is orphan, meaning there's at least one MDA on
that PV which does not reference any VG and at the same time there's
PV_EXT_USED flag set, we're certainly in an inconsistent state and we
need to fix this.

For example, such situation can happen during vgremove/vgreduce if we
removed/reduced the VG, but we haven't written PV headers yet because
vgremove stopped abruptly for whatever reason just before writing new
PV headers with updated state, including PV extension flags (and so the
PV_EXT_USED flag).

However, in case the PV has no MDAs at all, we can't double-check
whether the PV_EXT_USED is correct or not - if that PV is marked
as used, it's either:
  - really used (but other disks with MDAs are missing)
  - or the error state as described above is hit

User needs to overwrite the PV header directly if it's really clear
the PV having no MDAs does not belong to any VG and at the same time
it's still marked as being in use (pvcreate -ff <dev_name> will fix this).

For example - /dev/sda here has 1 MDA, orphan and is incorrectly marked
with PV_EXT_USED flag:

$ pvs --binary -o+pv_in_use
  WARNING: Found inconsistent standalone Physical Volumes.
  WARNING: Repairing flag incorrectly marking Physical Volume /dev/sda as used.
  PV         VG     Fmt  Attr PSize   PFree   InUse
  /dev/sda          lvm2 ---  128.00m 128.00m     0
2016-02-15 12:44:46 +01:00
3436d5b791 report: add pv_in_use field to display whether PV is in use or not
For example:

$ pvs -o pv_name,vg_name,pv_in_use
  PV         VG     InUse
  /dev/sda   vg      used
  /dev/sdb
  /dev/sdc           used

(sda is part of vg - it's used
 sdb is not part of vg - it's not used
 sdc is part of vg, but MDAs missing - it's used)
2016-02-15 12:44:46 +01:00
b6e3080fff pv: _pvcreate_write: do label removal and zeroing only if creating a new PV 2016-02-15 12:44:46 +01:00
73f1d444c8 pv: issue different message of different type when we're overwriting existing PV header instead of creating a new one
Scenario:

$ pvcreate /dev/sda
  Physical volume "/dev/sda" successfully created

We're adding the PV to a VG.

Before this patch:
$ vgcreate vg /dev/sda
  Physical volume "/dev/sda" successfully created
  Volume group "vg" successfully created

With this path applied:
$ vgcreate vg /dev/sda
  Volume group "vg" successfully created

...and verbose log containing: "Physical volume "/dev/sda" successfully written"
2016-02-15 12:44:46 +01:00
52999133a3 pv: check for the PV_EXT_USED flag and deny pvcreate/pvchange/pvremove/vgcreate on such PV (unless forced)
Make sure we won't use a PV that is already marked as used. Normally,
VG metadata would stop us from doing that, but we can run into a
situation where such metadata is missing because PVs with MDAs
are missing and the PVs left are the ones with 0 MDAs.

(/dev/sda in this example has 0 MDAs and it belongs to a VG,
but other PVs with MDA are missing)

$ pvs -o pv_name,pv_mda_count /dev/sda
  PV         #PMda
  /dev/sda       0

$ pvcreate /dev/sda
  PV '/dev/sda' is marked as belonging to a VG but its metadata is missing.
  Can't initialize PV '/dev/sda' without -ff.

$ pvchange -u /dev/sda
  PV '/dev/sda' is marked as belonging to a VG but its metadata is missing.
  Can't change PV '/dev/sda' without -ff.
  Physical volume /dev/sda not changed
  0 physical volumes changed / 1 physical volume not changed

$ pvremove /dev/sda
  PV '/dev/sda' is marked as belonging to a VG but its metadata is missing.
  (If you are certain you need pvremove, then confirm by using --force twice.)

$ vgcreate vg /dev/sda
  Physical volume '/dev/sda' is marked as belonging to a VG but its metadata is missing.
  Unable to add physical volume '/dev/sda' to volume group 'vg'.
2016-02-15 12:44:46 +01:00
d320d9c52b pv: format-text: store PV_EXT_USED flag if PV is used and unset it otherwise
When adding a PV to VG, set the PV_EXT_USED flag in PV header and
vice versa - if the PV is no longer in a VG, unset the flag.
2016-02-15 12:44:46 +01:00
10128c9bd6 metadata: schedule PV for header rewrite if adding a PV to VG or restoring VG
When adding PV to VG, we need to rewrite PV header as there's a flip
in PV_EXT_USED flag. The same applies if we're restoring VG from backup.
2016-02-15 12:44:46 +01:00
2950adc2ab metadata: add_pv_to_vg: add 'new_pv' arg to state if the PV is about to be created 2016-02-15 12:44:46 +01:00
4cbaaa5c98 pv: add is_used_pv fn 2016-02-15 12:44:46 +01:00
71ea2e1602 lvmcache/lvmetad: cache PV extension version
Store PV extension version in lvmcache/lvmetad for use throughout the code.
2016-02-15 12:44:46 +01:00
7593221f94 lvmcache/lvmetad: cache PV extension flags
Store PV extension flags in lvmcache/lvmetad for use throughout the code.
2016-02-15 12:44:46 +01:00
54b41db9a6 metadata: introduce PV_EXT_USED flag and bump PV_HEADER_EXTENSION_VSN 2016-02-15 12:44:46 +01:00
a522af93b7 format: add FMT_PV_FLAGS to indicate format supports PV flags 2016-02-15 12:44:46 +01:00
4361543f3e refactor: rename struct pv_to_create --> struct pv_to_write
We'll use this struct in subsequent patches for PVs which should
be rewritten, not just created. So rename struct pv_to_create to
struct pv_to_write for clarity.
2016-02-15 12:44:45 +01:00
952498ef4d post-release 2016-02-15 10:48:55 +00:00
228b8245e4 pre-release 2016-02-15 10:35:16 +00:00
672deaebc5 man: pvresize: remove old comment about inability to resize PV with more mdas 2016-02-12 16:29:47 +01:00
337aa4ca8e tests: indent
Better bash indention
2016-02-12 11:59:42 +01:00
0daf9d7ac5 pvmove: fix possible memory pool corruption
This is a hotfix for a bug introduced in
6d7dc87cb3.

The bug description: First we allocate memory for
processing handle (at an address 1) then we
allocate some memory on the same pool for later use
in pvmove_poll function inside the process_each_pv
function (at an address 2). After we jump out of
process_each_pv we called destroy_processing_handle.
As a result of destroying the handle memory pool could
deallocate all memory at address 1 or higher. The
pvmove_poll function tried to copy a memory allocated
at address 2 that could be returned to the system.
If it was so it led to segfault.

We need to rethink proper fix but in the same time
cmd->mem pool is recreated per each lvm command so
this should not cause problems even when we run
multiple commands in lvm shell.

A valgrind snapshot of the corruption:

Invalid read of size 1
    at 0x4C29F92: strlen (mc_replace_strmem.c:403)
    by 0x5495F2E: dm_pool_strdup (pool.c:51)
    by 0x1592A7: _create_id (pvmove.c:774)
    by 0x159409: pvmove_poll (pvmove.c:796)
    by 0x1599E3: pvmove (pvmove.c:931)
    by 0x15105B: lvm_run_command (lvmcmdline.c:1655)
    by 0x1523C3: lvm2_main (lvmcmdline.c:2121)
    by 0x1754F3: main (lvm.c:22)
Address 0xf15df8a is 138 bytes inside a block of size 8,192 free'd
    at 0x4C28430: free (vg_replace_malloc.c:446)
    by 0x5494E73: dm_free_wrapper (dbg_malloc.c:357)
    by 0x5495DE2: _free_chunk (pool-fast.c:318)
    by 0x549561C: dm_pool_free (pool-fast.c:151)
    by 0x164451: destroy_processing_handle (toollib.c:1837)
    by 0x1598C1: pvmove (pvmove.c:903)
    by 0x15105B: lvm_run_command (lvmcmdline.c:1655)
    by 0x1523C3: lvm2_main (lvmcmdline.c:2121)
    by 0x1754F3: main (lvm.c:22)
2016-02-12 11:40:33 +01:00
a077a64983 tests: update test
Upgrade test to count with much faster dmeventd work thanks
to low_watter_mark support.

Fix some wrong tests.
2016-02-12 10:21:07 +01:00
befe0078ad gcc: better code for older compiler
Address this gcc warning:

metadata/lv.c:243: warning: initialized field overwritten
metadata/lv.c:243: warning: (near initialization for 'status.seg_status')

Present with e.g.: gcc version 4.3.2 (Debian 4.3.2-1.1)
2016-02-12 10:17:39 +01:00
ba111e7f4a tests: check for automated dmeventd resize
Watermark support should handle relatively quickly data LV resizes.
So check if it does what is expected.
2016-02-11 18:38:40 +01:00
53058e5234 debug: cut_and_paste type in message
Typo in debug message.
2016-02-11 18:38:40 +01:00
cc23fdbd13 cleanup: update messages 2016-02-11 18:38:40 +01:00
5a32d2c1d9 cleanup: drop unneeded assigns 2016-02-11 18:35:07 +01:00
032cf8ade6 cleanup: relocate function to vg.c 2016-02-11 18:35:06 +01:00
acf7815aca cleanup: stripes_extents
Simplify calculation of extents rounding needed for
segment size.

Segment size has to divisible by 'extent count' needed to contain
whole stripe. LVM currently does not support stripes across segment.

In case the stripe size is bigger then extent size,
require bigger rounding.
2016-02-11 18:35:06 +01:00
740d27f9fe cleanup: rename usepolicies
Switch to ARG name without '_' in the middle (like all others args).
2016-02-11 18:35:06 +01:00
3f916e8285 lvresize: check for given parameters
Check ac_ value as passed args.
Also drop reseting 'computed' values - since they get
assigned values later.
2016-02-11 18:35:06 +01:00
0baf66a992 dm: alloc always 8byte aligned
Fixing regression caused by 197b5e6dc7.
So the 'TODO' part now finally know the answer - there is 'sparc64'
architecture which imposes limitation to read 64b words only through
64b aligned address.

Since we never could know how is the user going to use the returned
pointer and the userusually expects it's aligned on the highest CPU
required alignement, preserve it also for char*.

Fixes: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=809685
Reported-by: Anatoly Pugachev <matorola@gmail.com>
2016-02-11 18:35:05 +01:00
f91622741f dm: fix thin-pool targer params order
Wrong thin-pool feature flag ordering in dm table: It will lead to
unnecessary table reload.

Fix it by placeing feature flags in order they are returned from the
kernel so current 'table line diff' code will not see a difference.
2016-02-11 18:32:24 +01:00
e32e793c43 lvconvert: enable spare creation during conversion
Let user control pool metadata spare creation after repair as
the VG might not have enough free space.
2016-02-11 18:30:40 +01:00
3b76e9fd98 config: fix verbose type to int
'verbose' was marked as a boolean option while it
takes integer args - so it has limited usage to 0 or 1,
but we supported 0-4 at least.

Fix it by switching to corrent int type.
(Hopefully noone was trying to use this variable as true/yes/false/no
way - as the would be unsupported/undocumented).
2016-02-11 18:30:39 +01:00
02f2916b5b thin: fix low_water_mark threshold calc
Reporter noticed lvm2 incorrectly translated
lvm2 threshold value to  water mark in commit:
99237f0908

Fix it by properly translating size to number of
blocks in thin-pool and then calc for free blocks
matching configured lvm2 threshold value.

Reported-by: Ming-Hung Tsai <mingnus@gmail.com>
2016-02-11 18:30:24 +01:00
8423be80ee conf: use use_blkid_wiping=0 if not defined in lvm.conf and support not compiled in
Normally, we generate and provide lvm.conf file where use_blkid_wiping
is set based on whether support for this is compiled in or not. This was
generated properly based on configure.

However, if lvm.conf is not used at all (someone deletes it) or the value
in lvm.conf is commented out (user edited it), we still need to use
proper default value that is based on DEFAULT_USE_BLKID_WIPING taken
from configure script - we used hardcoded value of "1" in this case
by mistake.
2016-02-10 14:53:10 +01:00
c0e0f5a923 filter: do not check for suspended devs in filter-usable in lvmetad mode
We already do check for suspended devs within udev rules where
the pvscan is to update lvmetad. So the check for suspended devs
in "pre-lvmetad" chain is not useful here - remove it - it may
be a source of hardly to detect races anyway (if udev rule detects
the device is not suspended and then the pvscan instance sees the
dev as suspended, we may end up not reacting to the event properly).
2016-02-03 14:57:36 +01:00
1498bc8cc4 metadata: format: also delete bootloader areas from lvmcache when reading lvm1 and pool label
lvm1 and pool format do not support bootloader areas and we need to
remove any existing associated bootloader areas when we read lvm1 and
pool labels.

This has its importance if we're converting from one format to another
and we're reusing lvmcache in long-running commands (e.g. clvmd or lvm
shell) and we need to make lvmcache consistent and valid for current format.
2016-02-02 13:57:19 +01:00
ec43f55445 filters: partitioned: fix partition table filter with external_device_info_source="udev" and blkid<2.20
Non-dm devices have ID_PART_TABLE_TYPE variable exported in
udev db from blkid scan for *both* whole devices and partitions.
We used ID_PART_ENTRY_DISK in addition to decide whether this
is the whole device or partition and then we filtered out only
whole devices where the partition table really is.

However, ID_PART_ENTRY_DISK was added in blkid 2.20 so we need
to use a different set of variables to decide on whole devices
and partitions on systems where older blkid is still used.

Now, we use ID_PART_TABLE_TYPE to detect that there's something
related to partitioning with this device and we use DEVTYPE variable
instead to decide between whole device (DEVTYPE="disk") and partition
(DEVTYPE="partition").

For dm devices it's simpler, we have ID_PART_TABLE_TYPE variable\
set in udev db for whole devices. It's not set for partitions,
hence we don't need more variable in addition to make the decision
on whole device vs. partition (dm devices do not have regular
partitions, hence DEVTYPE can't be used anyway, it's always set
to "disk" for whole disks and partitions).
2016-02-02 13:28:11 +01:00
762b0d697f lvmlockd: don't adopt locks from unused lm
When built without dlm or sanlock support, don't
attempt to adopt locks from that lm.
2016-01-28 09:42:45 -06:00
0ad40a76c0 post-release 2016-01-25 01:12:27 +00:00
d05d7d974c pre-release 2016-01-25 01:08:16 +00:00
bc8f8ac0fa tests: add pv-check-dev-size.sh 2016-01-22 14:16:00 +01:00
136fd8f2f6 conf: add metadata/check_pv_device_sizes 2016-01-22 14:16:00 +01:00
c0912af310 metadata: check PV dev size is not less than PV size 2016-01-22 14:16:00 +01:00
1f5dfb7369 lvmcache: invalidate all cached dev sizes if all VGs got unlocked 2016-01-22 14:16:00 +01:00
d090d6574e device: also cache device size
Add "size" and "size_seqno" to struct device to cache device's size
and also to control its lifetime - the cached value is valid as long
as the global _dev_size_seqno is equal to the device's size_seqno,
otherwise we need to get the size again and cache the new value.

This patch also adds new dev_size_seqno_inc() fn for the appropriate
parts of the code to increment current global value of _dev_size_seqno
and hence to cause all currently cached values for device sizes to
be invalidated.

The device size is now cached because we're planning to reuse this
information for further checks and we want to avoid checking it more
than necessary to save resources.
2016-01-22 14:13:34 +01:00
dc388e0c7a lvmlockd: remove noisy log_debug
The debug message appeared even when lvmlockd was not used,
and the lockd operation was simply being skipped.
2016-01-21 14:37:15 -06:00
55056c2d16 vgimportclone: fix VG name variable reference in error message after failed PV uuid change 2016-01-21 14:47:48 +01:00
22810155a6 cleanup: add missing prototype
Commit 2304286f68
missed to add function prototype.
2016-01-21 13:29:08 +01:00
347575df1d toollib: restore command break support
Fix regression caused by c9f021de0b.
This commit actually transfered real-action (e.g. device removal)
into the next loop which has however missed to check for break.
So add check for break also there.
2016-01-21 13:29:07 +01:00
c701d9cc8c toollib: use cmd mempool for list
When creating a list in 'context of command' - use proper mempool.

vg->vgmem is mempool related to VG metadata - and can be eventually
locked read-only when VG struct is shared.
2016-01-21 13:28:28 +01:00
fcbef05aae doc: change fsf address
Hmm rpmlint suggest fsf is using a different address these days,
so lets keep it up-to-date
2016-01-21 12:11:37 +01:00
cc53a23d82 cleanup: join if/else 2016-01-21 12:11:37 +01:00
3e09f916b4 man: show hidden pieces
W: manual-page-warning /usr/share/man/man8/lvm.8.gz 491: warning: macro `_cdata',' not defined

rpmlint actually notices we had few hidden word in man page.
the line cannot start with apostrophe as it has then a different
meaning.
2016-01-21 12:11:35 +01:00
640c45d5a4 man: dmsetup
Typo in CMD_UDEVCREATECOOKIE macro name noticed by rpmlint.
2016-01-21 12:10:26 +01:00
43b436398e configure: fix configure to set proper use_blkid_wiping if autodetected as disabled
If not using explicit --enable-blkid-wiping/--disable-blkid-wiping
configure option, the configure script tries to enable/disable blkid
wiping feature automatically based on blkid library version found.

The script incorrectly set default value for lvm.conf's
allocation/use_blkid_wiping" setting to "1" (enabled) if proper
blkid library version was not found or the version found was less
than the minimum required. It should be set to "0" in this case.
2016-01-21 10:01:34 +01:00
21028a7903 cleanup: reformat sentence about max sizes
The extent size must fits all blocks in 4294967295 sectors
(in 512b units) this is 1/2 KiB less then 2TiB.

So while previous statement 'suggested' 2TiB is still acceptable value,
make it clear it's not.

As now we support any multiples of 128KB as extent size -
values like 2047G will still 'flow-in' otherwise the largest power-of-2
supported value is 1TiB.

With 1TiB user needs 8388608 extents for 8EiB device.
(FYI such device is already unusable with todays glibc-2.22.90-27)

4GiB extent size is currently the smallest extent size which allows
a user to create 8EiB devices (with 2GiB  it's less then 8EiB).

TODO: lvm2 may possibly print amount of 'lost/unused space' on a PV,
since using such ridiculously sized extent size may result in huge
space being left unaccessible.
2016-01-20 13:44:47 +01:00
7b5a8f61a7 cleanup: drop extra cmd passed arg
Use vg->cmd when needed cmd struct.
2016-01-20 13:44:47 +01:00
b64703401d cleanup: relocate size assign
Directly set thin-pool size when thin data LV size changes.
2016-01-20 13:44:47 +01:00
ca878a3426 cleanup: adjust once 2016-01-20 13:44:47 +01:00
178cbb580a cleanup: update check function
Use display_lvname().
Use lv_is_lockd_sanlock_lv().
Order  'error' checks ahead of 'ignore' ones.
2016-01-20 13:44:47 +01:00
4b9ae55a8d cleanup: shuffle check of threshold
Check first threshold and then policy_amount.
2016-01-20 13:44:47 +01:00
c99ca6f430 cleanup: use log_print
Using log_print for ignoring message instead of log_warn.
Add some missing '.'.
2016-01-20 13:44:47 +01:00
2da7525c83 activation: remote node check doesn't work yet 2016-01-20 02:54:11 +00:00
509410bbbc clvmd: Initialise udev.
Since commit 2fc126b00d, the library
code requires udev to be initialised for device scanning and
clvmd can fail to find VGs if devices/external_device_info_source
is set to "udev".
2016-01-20 00:58:09 +00:00
2304286f68 activation: Add lv_is_active_remotely. 2016-01-19 22:01:59 +00:00
c812c2dbc7 locking: Add node parameter to query_resource. 2016-01-19 21:42:22 +00:00
7f6a1e6bba man: mention GPT id for LVM in pvcreate man page 2016-01-19 15:28:44 +01:00
2a4ef78c4a report: fix off-by-one error when reporting LV segment's metadata device extent count
Commit a3f484f812 used "-1" two times by
mistake for the extent count when reporting seg_metadata_le_ranges.
2016-01-19 14:44:06 +01:00
acf1e84e8c report: add note about seg_pe_ranges and seg_le_ranges in -o help 2016-01-19 14:30:21 +01:00
1341f83554 report: add seg_le_ranges report field 2016-01-19 14:30:21 +01:00
fccb1bb276 report: make devices, metadata_devices, seg_pe_ranges and seg_metadata_le_ranges fields consistent
There are two basic groups of fields for LV segment device reporting:
  - related to LV segment's devices: devices and seg_pe_ranges
  - related to LV segment's metadata devices: metadata_devices and seg_metadata_le_ranges

The devices and metadata_devices report devices in this format:
    "device_name(extent_start)"

The seg_pe_ranges and seg_metadata_le_ranges report devices in
this format:
    "device_name:extent_start-extent_end"

This patch reverts partly what commit 7f74a99502
(v 2.02.140) introduced in this area - it added [] for
hidden devices to mark them for all four fields mentioned above.

We won't be marking hidden devices in devices and metadata_devices
fields.

The seg_metadata_le_ranges field will have hidden devices marked -
it's new enough that we don't need to care about compatibility much
yet.

The seg_pe_ranges is old enough that we shouldn't be changing this
one - so we're reverting to not marking hidden devices here.
Instead, there's going to be a new field "seg_le_ranges" which
is going to replace the seg_pe_ranges and it will mark hidden devices -
this is going to be introduced in a patch later.

So in the end we'll end up with:

   (LV segment's devices)
   devices field with "device_name(extent_start)" format, not marking hidden devices
   seg_pe_ranges field with "device_name:extent_start-extent_end" format, not marking hidden devices (deprecated, new seg_le_ranges should be used instead for standardized format)
   seg_le_ranges field with "device_name:extent_start-extent_end" format, marking hidden devices

   (LV segment's metadata devices)
   metadata_devices field with "device_name:extent_start-extent_end" format, not marking hidden devices
   seg_metadata_le_ranges field with "device_name:extent_start-extent_end" format, marking hidden devices

Also, both seg_le_ranges and seg_metadata_le_ranges will honour the
report/list_item_separator setting which can be used to configure
the delimiter used for list items.

So, to sum it up, we will recommend using the new seg_le_ranges and
seg_metadata_le_ranges fields because they display devices with
standard extent range format, they can mark hidden devices and they
honour the report/list_item_separator setting.

We'll be keeping devices,seg_pe_ranges and metadata_devices fields
for compatibility.
2016-01-19 14:30:20 +01:00
b160b73800 report: change _format_pvsegs to return list instead of plain string, change associated report fields from STR to STR_LIST
The associated devices,metadata_devices,seg_pe_ranges and
seg_metadata_le_ranges are reported as genuine string lists now.
This allows for using the items separately in -S|--select
(so searching for subsets etc.) and also it allows for
configuring the separator using report/list_item_separator
which may be useful in scripts (however, we'll enable this
only for seg_le_metadata_ranges and not for devices,seg_pe_ranges
and seg_metadata_devices for compatibility reasons - see following
patch).
2016-01-19 14:17:41 +01:00
2ed324648e refactor: add 'delimiter' variable for non-default delimiter when reporting string list 2016-01-19 11:50:52 +01:00
48f270970f lvconvert: disallow test mode in shared VG
until test mode can be checked in all the necessary
locations related to lvmlockd to prevent making
actual changes.
2016-01-18 16:53:14 -06:00
6b3e402298 toollib: add comment about missing device
Add a comment in _process_pvs_in_vg() to document the
place where there have been problems with processing
PVs twice.

For a while we had a hacky workaround here where we'd
skip processing a PV if its device wasn't found in
all_devices (and !is_missing_pv since we want to
process PVs with missing devices.).  That workaround
was removed in commit 5cd4d46f because it was no
longer needed.

The workaround had originally been needed to prevent
a device from being processed twice when the PV had
no MDAs -- it would be processed once in its real VG
and then the workaround would prevent it from being
processed a second time in the orphan VG.

Wrongly appearing as an orphan likely happened because
lvmcache would consider the no-MDA PV an orphan unless
the real VG holding that PV was also in lvmcache.
This issue is also mentioned in pvchange where holding
the global lock allows VGs to remain in lvmcache so
PVs with 0 mdas are not considered orphans.

The workaround in _process_pvs_in_vg() was originally
intended for reporting commands, not for pvchange.
But, it was accidentally helping pvchange also because
the method described by the pvchange global lock
comment had been subverted by commit 80f4b4b8.
Commit 80f4b4b8 was found to be unnecessary, and was
reverted in commit e710bac0.  This restored the
intended global lock lvmcache effect to pvchange, and
it no longer relied on the workaround in toollib.
2016-01-18 16:09:22 -06:00
a3f484f812 report: Fix seg_pe_ranges LV sizes.
When reporting on LVs, take the end of the range from the size of the
underlying (hidden) LV rather than the logical size of the current
segment (that PVs use).
2016-01-18 22:04:43 +00:00
6d7dc87cb3 pvmove: use toollib
Previously, pvmove used the function find_pv_in_vg() which did the
equivalent of process_each_pv() by doing:

  find_pv_by_name() -> get_pvs() ->

  get_pvs_internal() -> _get_pvs() -> get_vgids() ->

  /* equivalent to process_each_pv */
  dm_list_iterate_items(vgids)
    vg = vg_read_internal()
    dm_list_iterate_items(&vg->pvs)

With the found 'pv', it would do vg_read() on pv_vg_name(pv),
and then do the actual pvmove processing.

This commit simplifies by using process_each_pv() and putting
the actual pvmove processing into the "single" function.
This eliminates both find_pv_by_name() and the vg_read().
The processing code that followed vg_read remains the same.

The return code for the pvmove command is not based on the
process_each_pv return code, but is based on the success/fail
conditions in the existing code.
2016-01-18 14:48:30 -06:00
5cd4d46f30 Revert "Revert "process_each_pv: remove unnecessary workaround""
This reverts commit 6d09c8c2c4.

Try again to remove the workaround.
2016-01-18 09:36:55 -06:00
06346eab84 lvmlockd: cosemtic improvements to logging
Also pass our name to sanlock so it appears in
the sanlock status output.
2016-01-18 09:35:21 -06:00
95ead96004 lvmlockd: fix lvb validation for conversion
Make the lvb validation rules for convert match
those for unlock (even though it would be very
unlikely or impossible for convert to deal with
zero lvb.)
2016-01-18 09:35:20 -06:00
54b41dcd53 pvchange, pvresize: fix lockd_gl() usage
When an orphan PV is changed/resized, the
lvmlockd global lock is converted from sh
to ex. If the command is changing two
orphan PVs, the conversion to ex should
be done only once.
2016-01-18 09:35:06 -06:00
1ee6af344b report: add kernel_cache_settings field
Existing cache_settings field displays the settings which are
saved in metadata. Add new kernel_cache_settings fields to display
the settings which are currently used by kernel, including fields
for which default values are used.

This way users have complete view of the set of cache settings
supported (and which they can set) and their values which are used
at the moment by kernel.

For example:

$  lvs -o name,cache_policy,cache_settings,kernel_cache_settings vg
  LV      Cache Policy Cache Settings                               KCache Settings
  cached1 mq    migration_threshold=1024,write_promote_adjustment=2 migration_threshold=1024,random_threshold=4,sequential_threshold=512,discard_promote_adjustment=1,read_promote_adjustment=4,write_promote_adjustment=2
  cached2 smq   migration_threshold=1024                            migration_threshold=1024
  cached3 smq   migration_threshold=2048
2016-01-18 14:42:29 +01:00
7f62777041 post-release 2016-01-16 02:12:10 +00:00
0faa27d4f5 pre-release 2016-01-16 02:11:21 +00:00
7559af2334 lvm2app: fix lvm2app to return either 0 or 1 for lvm_vg_is_{clustered,exported}
Fix lvm2app to return either 0 or 1 for lvm_vg_is_{clustered,exported},
including internal functions pvseg_is_allocated and vg_is_resizeable
which are not yet exposed in lvm2app but make them consistent with the
rest.
2016-01-15 14:42:18 +01:00
1752f5c31e lvmlockd: fixes for test mode
Get the test mode working (lvmlockd running with no
lock manager).
2016-01-14 16:01:29 -06:00
e710bac03d Revert "lvmcache: skip drop when vg_write lock is not held"
This reverts e28e22b9e1
The problem that that commit was fixing (pytest failure)
no longer appears with the current code, so the commit is
not needed.

That commit is a problem for pvchange, because it prevents
lvmcache from retaining VG metadata even while the global
lock is held.  pvchange holds the global lock to ensure
that VG metadata is kept in lvmcache throughout processing.
If the cache is not kept, a PV with zero MDAs will appear
first in its actual VG and then appear again in the orphan VG.
It wrongly appears a second time in the orphan VG only if
the actual VG is dropped from lvmcache.
2016-01-14 13:34:36 -06:00
b82d5ee092 report: add kernel_discards report field to display thin pool discard used in kernel
Thin pool discard mode set in metadata can be different from the one
actually used if any device underneath does not support that mode. Add
kernel_discard report field to make it possible to see this difference.
2016-01-14 16:54:12 +01:00
6d09c8c2c4 Revert "process_each_pv: remove unnecessary workaround"
This reverts commit be1b1f3d89.
2016-01-14 09:12:57 -06:00
88400b599e lvmanip: fix last commit and drop else
In last commit when removing if() branch
this 'else' now has to be dropped.
2016-01-14 11:55:47 +01:00
278c5509ee cleanup: order ac members 2016-01-14 11:34:05 +01:00
c9a813bff8 cleanup: spaces 2016-01-14 11:34:05 +01:00
7d2b7f2bd8 cleanup: replace log_warn 2016-01-14 11:34:05 +01:00
2567d03e95 cleanup: explicit prohibition for virtual segs
Internal _alloc_init() is only called from allocate_extents(),
which already does prevent usage of virtual segments.

So mark as internal error early and do not process it any further.
2016-01-14 11:34:05 +01:00
4310dfd4e1 cleanup: simplier formula 2016-01-14 11:34:05 +01:00
ebcfd09ba9 cleanup: more readable check 2016-01-14 11:34:05 +01:00
753a496348 snapshot: relocate alloc_snapshot_seg
Move alloc_snapshot_seg to snapshot_manip and make it local static.
2016-01-14 11:34:05 +01:00
8857b22764 segtype: check for activation
Before setting static variable with check passed state,
detect if we are allowed to talk to driver.
2016-01-14 11:34:05 +01:00
43897239b3 lvresize: check for poolmetadatasize arg earlier
Since we check for poolmetadatasize, we need to detect it before
actual test.
2016-01-14 11:34:04 +01:00
526297296f lvmanip: add lv_is_snapshot
Add new test for  lv_is_snapshot().
Also move few other bitchecks into same place as remaining bit tests.

TODO: drop lv_is_merging_origin() and keep using lv_is_merging().
2016-01-14 11:34:04 +01:00
01228b692b vgcfgrestore: Retain allocatable PV attribute.
pvchange -xn was getting lost.
All PVs were set to allocatable again after restore.

Moved setting ALLOCATABLE_PV outside pv_setup().
2016-01-14 00:46:45 +00:00
9e9c757541 vgchange: fix lockd_gl results
The wrong error value was being checked from lockd_gl()
in two cases.

Clarify the use of lockd_gl() in the lock-start case.
2016-01-13 16:40:02 -06:00
1b1f42b490 lvmlockd: fix exit code
libdaemon uses 1 for success
2016-01-13 16:40:02 -06:00
be1b1f3d89 process_each_pv: remove unnecessary workaround
The problem addressed by this workaround no longer
seems to exist, so remove it.  PVs with no mdas
no longer appear in both their actual VG and in
the orphan VG.
2016-01-13 10:46:04 -06:00
63d59254d9 lv: fix check for NULL origin_lv in _do_lv_origin_dup, cleanup _do_lvconvert_lv_dup 2016-01-13 17:11:05 +01:00
04d1a8a5e4 cleanup: rename 'invisible devices' to 'hidden devices' 2016-01-13 16:43:25 +01:00
939d296525 conf: fix 'the volume list' vs 'volume list' and '@*' 2016-01-13 15:47:26 +01:00
9a81881965 cleanup: rename 'invisible devices' to 'hidden devices' 2016-01-13 15:37:15 +01:00
1417ed304b cleanup: rename 'invisible devices' to 'hidden devices' 2016-01-13 15:22:46 +01:00
d2d5c5e6c9 WHATS_NEW: reports and invisible devices 2016-01-13 14:45:49 +01:00
efab21b411 test: add report-invisible.sh test 2016-01-13 14:37:09 +01:00
c66a83fdc3 tests: update tests to deal with invisible devices consistently 2016-01-13 13:55:24 +01:00
84a9f750fe cleanup: cleanup lv.h and put fns into categories for better readability 2016-01-13 12:17:00 +01:00
293abbb8d2 conf: update command_profile_template.profile.in 2016-01-13 12:16:58 +01:00
53b355a24b conf: regenerate 2016-01-13 12:01:55 +01:00
e168b5de75 conf: add report/mark_invisible_devices 2016-01-13 12:01:10 +01:00
7f74a99502 lv: use brackets for invisible devices when formatting device segments
Include brackets for the name if the dev is invisible.
This change applies to all callers of _format_pvsegs fn:
  - lvseg_devices (the "lvs -o devices")
  - lvseg_metadata_devices (the "lvs -o metadata_devices)
  - lvseg_seg_pe_ranges (the "lvs -o seg_pe_ranges")
  - lvseg_seg_metadata_le_ranges (the "lvs -o seg_metadata_le_ranges")
2016-01-13 11:20:04 +01:00
f1fe7af014 lv: add common lv_pool_lv fn for use in report and dup, use brackets for invisible devices
The common lv_pool_lv fn avoids code duplication and also
the reporting part now uses _lvname_disp and _uuid_disp to display
name and uuid respectively, including brackets for the name if the
dev is invisible.
2016-01-13 11:20:01 +01:00
42fcbc1fd4 lv: add common lv_metadata_lv fn for use in report and dup, use brackets for invisible devices
The common lv_metadata_lv fn avoids code duplication and also
the reporting part now uses _lvname_disp and _uuid_disp to display
name and uuid respectively, including brackets for the name if the
dev is invisible.
2016-01-13 11:19:58 +01:00
cdbf76b2f0 lv: add common lv_data_lv fn for use in report and dup, use brackets for invisible devices
The common lv_data_lv fn avoids code duplication and also
the reporting part now uses _lvname_disp and _uuid_disp to display
name and uuid respectively, including brackets for the name if the
dev is invisible.
2016-01-13 11:19:55 +01:00
d50cd9d8d7 lv: add common lv_mirror_log_lv for use in report and dup, use brackets for invisible devices
The common lv_mirror_log_lv fn avoids code duplication and also
the reporting part now uses _lvname_disp and _uuid_disp to display
name and uuid respectively, including brackets for the name if the
dev is invisible.
2016-01-13 11:19:51 +01:00
aae45a1f21 lv: add common lv_origin_lv fn for use in report and dup, use brackets for invisible devices
The common lv_origin_lv fn avoids code duplication and also
the reporting part now uses _lvname_disp and _uuid_disp to display
name and uuid respectively, including brackets for the name if the
dev is invisible.
2016-01-13 11:19:45 +01:00
1bd83814ce lv: add common lv_convert_lv fn for use in report and dup, use brackets for invisible devices
The common lv_convert_lv fn avoids code duplication and also
the reporting part now uses _lvname_disp and _uuid_disp to display
name and uuid respectively, including brackets for the name if the
dev is invisible.
2016-01-13 11:16:37 +01:00
9e336582f4 man lvmlockd: mention pvmove restriction 2016-01-12 12:01:53 -06:00
0c6946b4ce pvmove: disallow moving PVs under sanlock leases
Fail with an error message if pvmove tries to move PVs
under the lvmlock LV.
2016-01-12 11:53:33 -06:00
176b4aaebe report: use proper string reference in _string_disp call for _cache_policy_disp fn 2016-01-12 16:14:23 +01:00
1a3ee6402e test: conditional skip of auto-activation bg polling test
if dm-snapshot-merge target not present skip whole test
2016-01-12 13:32:23 +01:00
d1e30ff0ba vgchange: drop redundant check
check for background polling option is performed from
within vgchange_background_polling routine as well.
2016-01-12 11:41:41 +01:00
d09246a07d test: add test for autoactivation regression
add test for a regression fixed in
40701af969
2016-01-12 11:40:43 +01:00
40701af969 pvscan: restore polling in autoactivation handler
This commit fixes regression in auto-activation code introduced
in commit: c26d81d6e6.

- resolves rhbz1295562
2016-01-12 11:40:43 +01:00
d6cf83968c report: use brackets to signify LVs which are not visible when reporting lv_parent
Use common _lvname_disp to report lv_parent. The _lvname_disp
takes care of properly marking LVs which are not visible - such
LVs are always enclosed in brackets when reported within any
other field.

For example, thin pool over RAID.

Before:

$ lvs -a -o name,lv_parent,data_lv,metadata_lv vg
  LV                          Parent           Data               Meta
  cache_pool                                   [cache_pool_tdata] [cache_pool_tmeta]
  [cache_pool_tdata]          cache_pool
  [cache_pool_tdata_rimage_0] cache_pool_tdata
  [cache_pool_tdata_rimage_1] cache_pool_tdata
  [cache_pool_tdata_rmeta_0]  cache_pool_tdata
  [cache_pool_tdata_rmeta_1]  cache_pool_tdata
  [cache_pool_tmeta]          cache_pool
  [cache_pool_tmeta_rimage_0] cache_pool_tmeta
  [cache_pool_tmeta_rimage_1] cache_pool_tmeta
  [cache_pool_tmeta_rmeta_0]  cache_pool_tmeta
  [cache_pool_tmeta_rmeta_1]  cache_pool_tmeta
  [lvol0_pmspare]

With this patch applied:

$ lvs -a -o name,lv_parent,data_lv,metadata_lv vg
  LV                          Parent             Data               Meta
  cache_pool                                     [cache_pool_tdata] [cache_pool_tmeta]
  [cache_pool_tdata]          cache_pool
  [cache_pool_tdata_rimage_0] [cache_pool_tdata]
  [cache_pool_tdata_rimage_1] [cache_pool_tdata]
  [cache_pool_tdata_rmeta_0]  [cache_pool_tdata]
  [cache_pool_tdata_rmeta_1]  [cache_pool_tdata]
  [cache_pool_tmeta]          cache_pool
  [cache_pool_tmeta_rimage_0] [cache_pool_tmeta]
  [cache_pool_tmeta_rimage_1] [cache_pool_tmeta]
  [cache_pool_tmeta_rmeta_0]  [cache_pool_tmeta]
  [cache_pool_tmeta_rmeta_1]  [cache_pool_tmeta]
  [lvol0_pmspare]
2016-01-11 15:34:35 +01:00
f03a21f5b8 cleanup: use _field_set_value and _string_disp consistently in report.c
Do not mix dm_report_field_set_value and _field_set_value and
use single function call throughout for clarity. The same applies
for dm_report_field_string and _string_disp.
2016-01-11 15:01:42 +01:00
a83d611a86 report: fix invalid memory read when reporting cache LV policy name
Fix regression caused by commit c2d4330f27
which removed the dm_pool_strdup for the cache policy name in
_cache_policy_disp report function.

This regression was hit with buffered reporting only (which is
used by default). The reason is that for buffered reporting, we're
iterating over LVs in VG (process_each_lv) while gathering
all the information that is needed for the report. In this case,
the LV's cache policy name has not been duped, but only the pointer
to the original VG buffer was stored. When the LV iteration finished,
the VG buffer was freed and any report to output called later
(dm_report_output call) accessed already freed VG data.

This didn't appear if unbuffered reporting was used (--unbuffered)
because in this case, the data were reported to output as
soon as they were processed, hence it was reported to output
before the VG data was freed.
2016-01-11 12:51:08 +01:00
0dac4f09b4 post-release 2016-01-08 18:51:08 +00:00
04b82a8126 pre-release 2016-01-08 18:46:41 +00:00
580c67486f document commits since last release 2016-01-08 09:53:58 -06:00
8d11468ab2 man: lvs: document F,D and M thin pool health status chars for lv_attr in lvs man page 2016-01-08 15:47:01 +01:00
4304a95dfd lvmdump: also add lvm2-activation{-early,-net}.service systemd status for lvmdump -s
The lvm2-activation{-early,-net}.service systemd unit statuses were missing
in dump gathered by lvmdump -s. These are quite important when debugging
scenarios with systemd environment and where lvmetad is not used.
2016-01-04 15:12:25 +01:00
124b490fe6 lvmlockd: update VG lock version earlier
Have commands send lvmlockd the update message
in vg_write instead of vg_commit, so that it's
not done while LVs are suspended.  If the vg_write
is not committed, and the seqno sent to lvmlockd
is not used, then lvmlockd can detect this when
the next update uses the same seqno.
2015-12-15 16:14:49 -06:00
796461a912 vgrename: use process_each_vg
Use process_each_vg() to lock and read the old VG,
and then call the main vgrename code.

When real VG names are used (not a UUID in place of the
old name), the command still pre-locks the new name
(when strcmp wants it locked first), before calling
process_each_vg on the old name.

In the case where the old name is replaced with a UUID,
process_each_vg now translates that UUID into the real
VG name, which it locks and reads.  In this case, we
cannot do pre-locking to maintain lock ordering because
the old name is unknown.  So, in this case the strcmp
based lock ordering is suppressed and the old name is
always locked first.  This opens a remote chance for
lock ordering conflict between racing vgrenames between
two names where one or both commands use the UUID.
2015-12-14 14:26:47 -06:00
37bd35bc3d pvscan: Remove duplicate filter wipe.
Also always clear the internal lvmcache after rescanning, and
reinstate a test for --trustcache so that 'pvs --trustcache'
(for example) avoids rescanning.
2015-12-14 20:14:59 +00:00
92e1422707 process_each_pv: do full scan earlier to find new devices
Before commit c1f246fedf,
_get_all_devices() did a full device scan before
get_vgnameids() was called.  The full scan in
_get_all_devices() is from calling dev_iter_create(f, 1).
The '1' arg forces a full scan.

By doing a full scan in _get_all_devices(), new devices
were added to dev-cache before get_vgnameids() began
scanning labels.  So, labels would be read from new devices.
(e.g. by the first 'pvs' command after the new device appeared.)

After that commit, _get_all_devices() was called
after get_vgnameids() was finished scanning labels.
So, new devices would be missed while scanning labels.
When _get_all_devices() saw the new devices (after
labels were scanned), those devices were added to
the .cache file.  This meant that the second 'pvs'
command would see the devices because they would be
in .cache.

Now, the full device scan is factored out of
_get_all_devices() and called by itself at the
start of the command so that new devices will
be known before get_vgnameids() scans labels.
2015-12-14 10:02:29 -06:00
1be56e46c4 post-release 2015-12-14 12:25:48 +00:00
3e8126a66a pre-release 2015-12-14 12:24:21 +00:00
4aa9e99a10 Change messages from verbose to debug
These messages about outdated PVs should not
be verbose because they always appear, even
when there are no outdated PVs.
2015-12-11 15:28:46 -06:00
3e48354f2d cleanup: add missing WHATS_NEW 2015-12-11 20:15:57 +01:00
07b9147ced tests: check lvrename of stacked cache pool 2015-12-11 20:15:57 +01:00
7a4badc07f fix static linking
Static linking fails currently, as -lm and -lpthread are missing:

gcc -O2  -fPIC -O2  -L../libdm -L../lib -L../libdaemon/client -static
-L../libdm/ioctl \
      -o dmsetup.static dmsetup.o -ldevmapper    -lrt
../libdm/ioctl/libdevmapper.a(libdm-stats.o): In function
`dm_stats_create_region':
libdm-stats.c:(.text+0x2d69): undefined reference to `log10'
libdm-stats.c:(.text+0x2d6e): undefined reference to `lround'
../libdm/ioctl/libdevmapper.a(pool.o): In function `dm_pool_create':
pool.c:(.text+0x134): undefined reference to `pthread_mutex_lock'
pool.c:(.text+0x14f): undefined reference to `pthread_mutex_unlock'

Signed-off-by: Riku Voipio <riku.voipio@linaro.org>
2015-12-11 20:15:51 +01:00
0688dbbc53 tests: fix logging
Actually  file redirection must be before stderr redir.
2015-12-10 21:01:24 +01:00
cd8e95d933 lvrename: always allow to rename pools
Since we mark cache-pool as 'hidden/private' while it is in-use,
we may still allow user to change it's name.

It should not cause any harm and user may prefer better naming
for a cache-pool in use.
2015-12-10 21:01:24 +01:00
bf4b74c5eb cache: support stacked rename
Preserve skip_pool flag when running for_each_sub_lv() so
lvrename continues to work when thin-pool is using cached
data LV.
2015-12-10 21:01:24 +01:00
dcb26b5f13 lvmlockd: reconnect to lvmetad if it's restarted
If lvmetad is restarted after lvmlockd has connected
to it, then lvmlockd should reconnect.
2015-12-10 10:50:19 -06:00
bdba4e7a93 lvrename: move the lvmlockd LV lock
The function it was in is used for various
internal renaming of hidden LVs where a lock
from lvmlockd does not apply.
2015-12-09 11:59:49 -06:00
dcd946e95a dmeventd: Don't trust fifo with wrong attrs.
If an existing fifo has the wrong attributes it cannot be trusted
so we must unlink it and recreate it correctly.
(Replaces 2c8d6f5c90: if the other end of
the fifo already got opened while its mode was insecure, delaying the
chmod isn't going to make any difference!)
2015-12-08 01:48:17 +00:00
94dab390ef dmeventd: Extend checks on client socket.
Reinstate and extend checks removed by e1b111b02a.

The code has always assumed that only root has access to the directory
containing the fifos and that they are under the complete control of
dmeventd code.  If anything is found not to be as expected, then open()
should certainly not be attempted!
2015-12-08 00:59:39 +00:00
00bab9d9cd post-release 2015-12-05 15:36:22 +00:00
063b353b28 pre-release 2015-12-05 15:33:19 +00:00
fedf15ffb0 tests: extend test 2015-12-04 22:10:30 +01:00
748b8158b5 archiver: fix reporting for check_current_backup
It's getting a bit more complex here.

Basic idea behind is - check_current_backup() should not
log error when a user is using a read-only filesystem,
so e.g.  vgscan  will not report any error when it tries
to take missing backup.

We still have cases when error could be reported though,
e.g. the backup this would be a symbolic link, but these
are rather misconfiguration and unexpected case.
2015-12-04 22:10:30 +01:00
8b16efd17c debug: correct stack tracing
Here the 'goto' is correct path, as  !device_is_usable
is traceable with <backtrace>.

Keep the 'stack' for unusable device.
2015-12-04 22:10:30 +01:00
45781161f4 libdm: add some doc for mirror status
Comment content of struct for mirror status.
2015-12-04 22:10:30 +01:00
c24d913c47 lvconvert: Reinstate raid merge after splitmirror.
After commit 46c8d6bb8a
(lvconvert: Improve message for raid without -m)
2015-12-03 17:40:10 +00:00
89418c1253 tests: check read-only backup archive 2015-12-03 18:17:45 +01:00
d2524315e6 vgextend: reinstantiate archiving
Since commit f5d06efbab we lost archiving.
Restore it now with process_each_vg.
2015-12-03 18:17:45 +01:00
e7978c5ab6 cleanup: drop log_suppress(2) usage
No longer need to use  log_suppress(2) instance so dropped.
2015-12-03 18:02:34 +01:00
f40b3ba1e9 archiver: inital change toward proper logging
We have to modes of  'archive()' usage -
1. compulsory - fail stops command and user may try '-An' option
to do a command.

2. non-compulsory - some fails in archiving are ignorable (i.e.
read-only filesystem where archive dir is located).

Those 2 cases needs to be properly handle - i.e. the non-compulsory
logging should not be tampering  error logging message production.

So more work here is needed
2015-12-03 18:01:45 +01:00
20acc66a23 log: use full buffer size for printf
Pass full buffer size to printf() function - no reason to make
buffer 1 char smaller.

Also rename locn buffer to message buffer directly since it's
not used for anything else.

TODO: we may use same buffer also for 'buf[]' since there is
no collision - so may safe 1K on stack usage.
2015-12-03 18:01:42 +01:00
20483ead5b cleanup: use try_id_read_format
Better then using log_suppress in this case.
2015-12-03 18:00:54 +01:00
c15c44a492 uuid: add id_read_format_try
Provide id_read_format() functionality without log_error
when ID is not valid one - it will just return 0.

Does not need to use log_suppress() then.
2015-12-03 18:00:38 +01:00
aec58c8620 lvconvert: Reinstate mirror to raid conversions.
Reinstate conversions from mirror to raid stopped
by commit 46c8d6bb8a
(lvconvert: Improve message for raid without -m).
2015-12-03 14:40:14 +00:00
3bbf89e9ec man lvm: add section about unique VG names 2015-12-02 10:37:25 -06:00
61573bd197 toollib: only interpret vgname arg as uuid for vgrename
In general, --select should be used to specify a VG by UUID,
but vgrename already allows a uuid to be substituted for
the name, so continue to allow it in that case.
2015-12-01 15:50:14 -06:00
166adf0e1f toollib: allow VG UUID to be used in place of VG name
If the VG arg from the command line does not match the
name of any known VGs, then check if the arg looks like
a UUID.  If it's a valid UUID, then compare it to the
UUID of known VGs.  If it matches the UUID of a known VG,
then process that VG.
2015-12-01 12:08:24 -06:00
67763a9bec lvresize: use process_each_vg
No functional change.
2015-12-01 11:01:26 -06:00
5bbbd37f41 lvrename: use process_each_vg
No functional change.
2015-12-01 09:54:33 -06:00
f7571eb287 lvcreate: use process_each_vg
No functional change.
2015-12-01 09:36:52 -06:00
ea74215fa1 vgextend: pass single vgname as process_each_vg arg
Pass the single vgname as a new process_each_vg arg
instead of setting a cmd flag to tell process_each_vg
to take only the first vgname arg from argv.

Other commands with different argv formats will be
able to use it this way.
2015-12-01 09:36:45 -06:00
3bcdf5d14b lvmcache: change duplicate VG name warnings to verbose
When two different VGs with the same name exist,
they are both stored in lvmcache using the vginfo->next
list.  Previously, the code would print warnings (sometimes)
when adding VGs to this list.  Now the duplicate VG names
are handled by higher level code, so this list no longer
needs to print warnings about duplicate VG names being found.
2015-12-01 09:30:23 -06:00
88cef47b18 vg_read: look up vgid from name
After recent changes to process_each, vg_read() is usually
given both the vgname and vgid for the intended VG.

However, in some cases vg_read() is given a vgid with
no vgname, or is given a vgname with no vgid.

When given a vgid with no vgname, vg_read() uses lvmcache
to look up the vgname using the vgid.  If the vgname is
not found, vg_read() fails.

When given a vgname with no vgid, vg_read() should also
use lvmcache to look up the vgid using the vgname.
If the vgid is not found, vg_read() fails.

If the lvmcache lookup finds multiple vgids for the
vgname, then the lookup fails, causing vg_read() to fail
because the intended VG is uncertain.

Usually, both vgname and vgid for the intended VG are passed
to vg_read(), which means the lvmcache translations
between vgname and vgid are not done.
2015-12-01 09:18:48 -06:00
1e43ec15ce toollib: remove unused function 2015-12-01 09:10:01 -06:00
aa4932674a process_each: resolve duplicate VG names
If two different VGs with the same name exist on the system,
a command that just specifies that ambiguous name will fail
with a new error:

$ vgs -o name,uuid
  ...
  foo qyUS65-vn32-TuKs-a8yF-wfeQ-7DkF-Fds0uf
  foo vfhKCP-mpc7-KLLL-Uh08-4xPG-zLNR-4cnxJX

$ lvs foo
  Multiple VGs found with the same name: foo
  Use the --select option with VG UUID (vg_uuid).

$ vgremove foo
  Multiple VGs found with the same name: foo
  Use the --select option with VG UUID (vg_uuid).

$ lvs -S vg_uuid=qyUS65-vn32-TuKs-a8yF-wfeQ-7DkF-Fds0uf
  lv1 foo ...

This is implemented for process_each_vg/lv, and works
with or without lvmetad.  It does not work for commands
that do not use process_each.

This change includes one exception to the behavior shown
above.  If one of the VGs is foreign, and the other is not,
then the command assumes that the intended VG is the local
one and uses it.
2015-12-01 09:09:55 -06:00
4ff2583dc5 process_each: always use list of vgnames on system
This makes process_each_vg/lv always use the list of
vgnames on the system.  When specific VGs are named on
the command line, the corresponding entries from
vgnameids_on_system are moved to vgnameids_to_process.

Previously, when specific VGs were named on the command
line, the vgnameids_on_system list was not created, and
vgnameids_to_process was created from the arg_vgnames
list (which is only names, without vgids).

Now, vgnameids_on_system is always created, and entries
are moved from that list to vgnameids_to_process -- either
some (when arg_vgnames specifies only some), or all (when
the command is processing all VGs, or needs to look at
all VGs for checking tags/selection).

This change adds one new lvmetad lookup (vg_list) to a
command that specifies VG names.  It adds no new work
for other commands, e.g. non-lvmetad commands, or
commands that look at all VGs.

When using lvmetad, 'lvs foo' previously sent one
request to lvmetad: 'vg_lookup foo'.
Now, 'lvs foo' sends two requests to lvmetad:
'vg_list' and 'vg_lookup foo <uuid>'.

(The lookup can now always include the uuid in the request
because the initial vg_list contains name/vgid pairs.)
2015-12-01 09:09:49 -06:00
68e2ea11a3 mirror: fix condition
Recent patch tested wrong condition for error
2015-12-01 13:59:20 +01:00
86e7894ecc cleanup: use dm_get_status_mirror
Use libdm function to parse mirror status report.
2015-12-01 13:03:16 +01:00
6336ef98d4 lib: pass mem pool to check_transient_status
check_transient_status() may need to allocate some memory,
so pass in already existing mem pool.
2015-12-01 13:01:28 +01:00
c717ea5fc0 tests: unit test for mirror status 2015-12-01 13:00:52 +01:00
fa87979004 libdm: introduce dm_get_status_mirror
Add missing function to parse mirror status.
2015-12-01 13:00:43 +01:00
46c8d6bb8a lvconvert: Improve message for raid without -m. 2015-11-30 22:36:05 +00:00
eb22f7c8f7 lvmcache: new function to check if VG is foreign
When not using lvmetad, this uses the system_id field in
the cached vginfo structs that are populated during a scan.

When using lvmetad, this requests the VG from lvmetad, and
checks the system_id field in the returned metadata.
2015-11-30 11:54:56 -06:00
05ac836798 system_id: refactor check for allowed system_id
Refactor the code that checks for an allowable system_id
so that it can be used from other places.
2015-11-30 11:46:55 -06:00
d3ca18e489 lvmcache: include system_id in vginfo cache
Save system_id just like creation_host and lock_type
strings in vginfo cache.
2015-11-30 11:32:17 -06:00
1f357532bb lvmetad: include both vgid and vgname in lookup request
When the command already knows both the vgid and vgname,
it should send both to lvmetad for a more exact request,
and it can save lvmetad the work of a name lookup.
2015-11-30 10:57:30 -06:00
cd4d2cff97 post-release 2015-11-28 01:29:00 +00:00
b4a3aaf910 pre-release 2015-11-28 01:25:53 +00:00
1fb8d746d6 tests: make unit testing usable again
Make unit tests usable/compilable with newer header files.
Add 'initial' dmlist_t  for list tests.
More will come...
2015-11-27 11:22:21 +01:00
ec647f1d43 cleanup: clean gcc shadow declaration of version warning 2015-11-26 21:52:22 +01:00
4afe43e1a3 debug: show LV name where dlid creation failed 2015-11-26 21:52:05 +01:00
922fccc656 cleanup: using display_lvname
Use for showing vgname/lvname in messages.
No functional change.
2015-11-26 09:27:37 +01:00
b7b59ad932 cleanup: remove unused code
Remove long outstand unused code lines, which were already
been obsoleted by other code.

Statuses and snapshot tree creation is already handled differently.

Also drop some 'extra' log_error() and use only stack;
since error has already been reported.
2015-11-26 09:27:37 +01:00
528695ec20 cleanup: avoid allocation for vg_name
Since we do not use dev_manager in a way we would have destroyed VG
content while  in-use - we could safely keep just pointer.
So dropping strdup.

Also it seems we actually no longer use vg_name for anything
so it may possibly go away completely unless it would be useful
for debugging...
2015-11-26 09:27:37 +01:00
d582be43d4 libdm: const raid params and error for unsupported type
Accept const struct with raid params (No API change).
Also add extra error message when raid type is unsupported.
2015-11-26 09:27:04 +01:00
1ea8afd3ca lvmconfig: add --sinceversion for --type new
Just for convenience to display all new configuration settings
introduced since given version (before, there was only --atversion
to display settings introduced in concrete version).

For example:
	$ lvmconfig --type new --sinceversion 2.2.120
	allocation {
		# cache_mode="writethrough"
		# cache_settings {
		# }
	}
	global {
		use_lvmlockd=0
		# lvmlockd_lock_retries=3
		# sanlock_lv_extend=256
		use_lvmpolld=1
	}
	activation {
	}
	# report {
		# compact_output_cols=""
		# time_format="%Y-%m-%d %T %z"
	# }
	local {
		# host_id=0
	}
2015-11-25 14:12:12 +01:00
66c7fa4a44 cleanup: rename lv_ondisk to lv_committed
Patch has no functional change.
2015-11-25 11:39:26 +01:00
4312b09635 cleanup: change ondisk committed
Patch has no functional change.
2015-11-25 11:39:26 +01:00
d9faf85987 cleanup: rename vg_ondisk to vg_committed
Unifying terminology.

Since all the metadata in-use are ALWAYS on disk - switch
to terminology  committed and precommitted.

Patch has no functional change inside.
2015-11-25 11:11:21 +01:00
0285066e10 thin: fix previous update of partial tree building
We do want to preserve 'active' thin-pool,
so add this 'fake' layer only when activating.

TODO:  think how to use thin-pool without fake LV layer.
2015-11-24 23:24:11 +01:00
8d86c5db03 tests: improve teardown
Do not try to execute vgremove, when test has left suspended devices.
2015-11-24 11:29:28 +01:00
a220939d9e tests: data correctness after thin-pool resize 2015-11-24 11:29:27 +01:00
9243877ea1 cleanup: use display_lvname
Switch debug msg to use display_lvname.
Link to VG early, so we have access to VG from LV.
2015-11-23 23:42:59 +01:00
5e50e5f0b4 thin: skip detach preload from pools
lv preload for detached LVs started to be used also
for various other types which just happens to pass through
weak if() condition.

TODO: find here better solution to rather explicitly check
for types we really need to preload.
2015-11-23 23:42:59 +01:00
6d6c233768 cleanup: move towards using direct LV pointers
We do not won't to 'expose'  internals of VG struct.
ATM we use lists to keep all LVs - we may want to switch
to better struct for quicker 'search'.

Since we do not need 'lists' but always actual LV,
switch find_lv_in_vg_by_lvid() to return LV,
and replaces some use case of  find_lv_in_vg()
with 'better' working find_lv() which already
returns LV.
2015-11-23 23:42:59 +01:00
94c9453659 thin: work with active thin-pool
When 'lvextend -L+XX vg/thinpool'  do not leave inactive table
loaded for 'wrapping' LV on top of resized thin-pool
(ATM we use linear  LV for this with same size as thin-pool).
2015-11-23 23:41:36 +01:00
15be97d76b memlock: add more libs on ignore list
Udev recently start to 'link-in' major amount of useless libs.
(Seem to be faulty 'systemd' link-in all issue)
Anyway - avoid locking those libs in RAM.
2015-11-23 23:39:01 +01:00
6ca5447e0c libdm: enhance thin-pool preload
When preloading thin-pool device node for already
existing/running thin-pool do not resume such thin-pool.

This allows to properly schedule commit point for metadata,
when thin-pool data or metadata volume is resized.
2015-11-23 23:34:46 +01:00
ddbf0075b1 libdm: drop extra space from cache target line
Extra space between 'cache' target and metadata device caused
string comparation being not equal and thus always causing
table reload even when uneeded.
2015-11-23 23:33:37 +01:00
fe64d3a2e2 man lvmcache: include chunk size 2015-11-23 11:57:41 -06:00
c026846739 post-release 2015-11-23 03:40:34 +00:00
369bc264b0 pre-release 2015-11-23 03:37:54 +00:00
da50f8bee6 tests: more cache conversion checks 2015-11-19 14:40:49 +01:00
795616a87b cache: lvconvert repairs only thin pools
Avoid internal error message where thin pool repair code tries to
fix cache pool - was catched later in code stack, so rather
catch this early and make the repair function exlusive
to thin pools.

So far we have no code for repairing cache pools
(other then the automatic during activation/deactivation).
2015-11-19 14:40:24 +01:00
d1608345df cache: enable raid conversion for _cdata and _cmeta
Since thin-pool supports convertion of data and metadata LV,
enable the same for cache data and metadata LV.
2015-11-19 14:38:36 +01:00
6f002c29a5 tests: stacktrace on skip if message is empty 2015-11-19 12:18:33 +01:00
2a23550cf3 tests: add missing --skip option and S env.variable 2015-11-19 12:00:59 +01:00
0614c63579 cleanup: cast resulting value explicitely 2015-11-19 11:59:19 +01:00
0b2be60497 cleanup: add stack traces 2015-11-18 22:17:26 +01:00
e2b00b0a89 cleanup: use display_lvname in pmspare
Just switch to use display_lvname().
Also squeeze possibly failing strncpy into INTERNAL_ERROR
as lvname always should fit.
2015-11-18 22:17:26 +01:00
0a2cadf6b8 libdm: report: consolidate use of string list selection structures 2015-11-18 10:54:09 +01:00
7b11ef6de0 tests: update lvmcache-exercise
To handle multiple VGs with the same name.
Simply using the VG name is ambiguous, and
lvmetad requires the VG uuid be used to
specify which one is meant.
2015-11-17 12:12:17 -06:00
6167f5da10 coverity: trying different model
Model reseting of given set, but it still makes
FD_SET to think it's accessing uninitialized value.

Maybe model also FD_SET.
2015-11-17 19:01:25 +01:00
83661c8f7f cleanup: use embeded list
Skip pointer and put list into selection_str_list.
2015-11-17 19:01:25 +01:00
6e71d3fbde cleanup: more readable code
Simplify if() expression.
Rename 'this' to 'vg'..
2015-11-17 19:01:25 +01:00
d8049dd17a cleanup: add some test for NULL
Coverity here is a bit 'blind' here and cannot resolve which
code paths are actually able to hit this code path.
(It's using 'statistic' to resolve all possible paths,
and it's not scanning 'individual' code paths.)

This just cleans warns and add 'cheap' tests.
2015-11-17 19:01:25 +01:00
011dd82050 cleanup: do not call vg_read with NULL mda
Use 'mda' instead of NULL to quite Coverity warn.
However this code seems to be actually not even possible to hit.
With proper analysis it may possibly be dropped from code to
simplify logic.
2015-11-17 19:01:25 +01:00
121341e52c cleanup: unify NULL custom check
Unify testing of NULL custom pointer.
Resolve 'factor' only in required if() branch.
2015-11-17 19:01:25 +01:00
cad3568def raid: drop unneeded NULL test
Skip testing target_pvs for NULL, we already
dereference it in many other places.
If check would ever be needed - it needs to be
in front of _raid_extract_images().
2015-11-17 19:01:25 +01:00
51dfba002b libdm: update error message
Correcting error message.
2015-11-17 19:01:25 +01:00
931fede81b hash: change name of new lookup function 2015-11-17 11:59:44 -06:00
4d37db123d lvmetad: improve error message for VGs with same name 2015-11-17 10:35:42 -06:00
485d2ca945 lvmetad: different style for hash functions
In lookup, return a count of entries with the
same key rather than the value from a second
entry with the same key.

Using some slightly different names.
2015-11-17 10:27:16 -06:00
d42cedae58 lvmetad: add error explaining duplicate VG names
When a VG name lookup fails because the name matches
multiple VGs, return an explanatory error.
2015-11-16 16:25:49 -06:00
7d1c9e1d5a lvmetad: fix some error logging
For some errors old_meta may not be set, so
check before logging it.
2015-11-16 15:13:26 -06:00
68c386cce7 lvmetad: use lookup_withval in another location
Simply use lookup_withval right away rather than doing a
standard lookup, checking for the wrong mapping, then
repeating with lookup_withval to get the right mapping.
2015-11-16 15:13:22 -06:00
4a984cabc4 lvmetad: remove unneeded FIXME
This case is now handled correctly.
2015-11-16 13:44:57 -06:00
920a281994 hash: add comment about multiple values 2015-11-16 11:02:25 -06:00
b6a45963e3 libdm: fix check of pointer
Ahhh being blind here - wanted to check the pointer before dereference
not a dereferenced one.
2015-11-16 13:10:24 +01:00
2a2487f02f libdm: better error reporting from dm_split_lvm_name
Report errors from all error paths correctly.
Validate passed args before dereferencing them.
2015-11-16 13:09:53 +01:00
5d4f5873a9 coverity: model FD_ZERO
Coverity is not able to understand assembly language in
system's header file, so provide model for such macro.

Note: to really see model in-use: #nodef FD_ZERO model_FD_ZERO
need to go to coverity/config/user_nodefs.h
2015-11-16 01:16:11 +01:00
8ebf2b0611 debug: lvconvert add missing display_lvname
Add missing display_lvname in _lvconvert_merge_thin_snapshot().

Also when we detect missing origin, report Internal error,
which would likely be the primary fault here
(and avoid dereft of NULL origin as noticed by Coverity).
2015-11-16 01:16:11 +01:00
0f4d96f1bd cleanup: just alphabetically sort links 2015-11-16 01:16:11 +01:00
dccbc3b621 cleanup: simplify dev_cache_exit
Just set whole _cache struct into unitialized state just
like with lib init start usage.
Lists are initialized with dev_cache_init().
2015-11-16 01:16:11 +01:00
5a4676fea9 cleanup: add _free on error path
Just like with failing allocation above also _free(dev).

TODO: rework this to always use mempool and drop unneeded
comlexity we have in this function.
2015-11-16 01:16:11 +01:00
c3b292a4a9 format-text: ensure no division by zero
Coverity likes here to be 100% sure no division by zero is possible.
Add check for alignment !=0 which is made on other code paths here.
2015-11-16 01:16:11 +01:00
193e7f5973 config: check vdef pointer before dereference
Coverity notices we check for v_def != NULL elsewhere, so it thinks
it may be possibly NULL also here.
2015-11-16 01:16:11 +01:00
96d73dc6ea libdm: check for passed custom time value
Coverity reports custom should be checked before derefernce.
2015-11-16 01:16:11 +01:00
d4288c9bdf libdm: check for null from pool strdup
Unlikely to happen, but Coverity shown we may have possible
derefer NULL pointer.
2015-11-16 01:16:09 +01:00
422c7474ca libdm: check if passed return pointer is not NULL
Coverity: before storing return value, check passed space will
not dereference NULL pointer.
2015-11-16 01:15:04 +01:00
dd9a05b5ae man: improve cmirrord.8 manpage
- Keywords in bold
- Add syslog and signal ref.
- Sort see also sections

Signed-off-by: Stéphane Aulery <saulery@free.fr>
2015-11-16 01:15:03 +01:00
376892ddf8 clvmd: remove -v option from getopt
-V is documented, not -v.

Signed-off-by: Stéphane Aulery <saulery@free.fr>
2015-11-16 01:15:03 +01:00
e31f4b76f4 cache: handle older metadata format
When reading older lvm2 metadata for cache-pool - we now handle more
extended syntax - basically we want to enter most setting when
actually creating cached LV.

For this new validation code has been added. However older metadata
without new settings set is now found as invalid.

Fix it by adding default settings for  cache policy  mq
and cache mode  writethrough.
2015-11-16 01:12:57 +01:00
d9295410e9 lvmetad: change the new hash to take data len
If the data len is passed into the hash table
and saved there, then the hash table internals
do not need to assume that the data value is
a string at any point.
2015-11-13 16:54:22 -06:00
e425bce281 tests: allow lvmetad tests with duplicate VG names 2015-11-13 15:09:26 -06:00
46193f4a59 lvmetad: handle duplicate VG names
New hash table functions are added that allow for
multiple entries with the same key.  Use of the
vgname_to_vgid hash table is converted to these
new functions since there are multiple entries
in vgname_to_vgid that have the same key (vgname).

When multiple VGs with the same name exist, commands
that reference only a VG name will fail saying the
VG could not be found (that error message could be
improved.)  Any command that works with the select
option can access one of the VGs with -S vg_uuid=X.
vgrename is a special case that allows the first VG
name arg to be replaced by a uuid, which also works.

(The existing hash table implementation is not well
suited for handling this case, but it works ok with
the new extensions.  Changing lvmetad to use its own
custom hash tables may be preferable at some point.)
2015-11-13 14:56:35 -06:00
970a428909 pvmove: Remove unused find_pvmove_lv_from_pvname. 2015-11-13 18:06:08 +00:00
b2e13ac552 coverity: add few internal errors
Mark impossible paths with internal errors.
Also replace 'strcmp() with more readable seg_is...()
2015-11-13 11:18:27 +01:00
3089f5ab15 coverity: model some function
Reduce number of false-positives and model functions in a way
Coverity is able to understand it.
2015-11-13 11:18:27 +01:00
8d258c7df4 coverity: hint
Here Coverity cannot see the pointer cannot be NULL in this
code path - opened coverity case #00531860.

We could make a model to avoid seeing related reports,
but then we loose coverage for modeled function.

So decided to add minor hint for this case.
2015-11-13 11:18:27 +01:00
ea1814cea8 tests: without delay_dev skip some checks
When delay_dev is missing these tests are just racy.
2015-11-13 11:17:07 +01:00
6dadebb1e4 cleanup: better error message
Use display_lvname.
2015-11-13 11:17:06 +01:00
1f2a42c7b7 cleanup: check LVs in one statement
Use a single statement to check all LVs we want to
deref via  get_only_segment_using_this_lv().
2015-11-13 11:17:06 +01:00
70af08122e cleanup: missing check for PV2
Patch missed also check this pointer dereference.
2015-11-13 11:17:06 +01:00
e0828e885b cleanup: drop unneded check for mem
Revert missed to drop this extra check.
2015-11-13 11:17:06 +01:00
112c0592ad debug: put stack on error path
At least check result and trace it.
However we may need better error reaction in this case.
2015-11-13 11:17:06 +01:00
007be91e3d raid: ensure area_count is at least 2
Enusure we will not divide by 0.
2015-11-13 11:17:06 +01:00
d74e1291cd libdm: put in secure check
Coverity complains about NULL deref - while this cannot currently
happen, put in secure INTERNAL_ERROR.
2015-11-13 11:17:05 +01:00
0128770d6d reporter: add missing stack trace
Use goto_out on error paths.
2015-11-13 11:17:05 +01:00
43777b551d lvmetad: tail chasing to shut up coverity 2015-11-12 09:35:41 -06:00
058725c721 dmeventd: fix check for failing open.
Recent change 2c8d6f5c90
actually droped restart when the reason of failing open is missing
device completely - check for ENOENT now as another reason
to start new dmeventd server  (when there is no systemd to maintain it).
2015-11-11 19:54:55 +01:00
1e729c47d2 str_list: do not support str lists without mempools
Do not support str lists without mempools. Instead, create temporary
mempool where necessary (currently only _get_report_options fn).
2015-11-11 16:09:52 +01:00
b8779e706e configure: check for udev_device_get_is_initialized is available
The udev_device_get_is_initialized is available since libudev version
165. Older versions are still used somewhere (e.g. RHEL6). So better
check for this fn and use it only if it's available.
2015-11-11 15:15:50 +01:00
f82e0210b7 dev-ext: issue error if external_device_info_source=udev and udev db record incomplete
Udev db records are marked as not initialized (incomplete) on timeout.
Issue an error message whenever LVM finds such records so users are
aware that something's going wrong with udev db.

This is important in case we use devices/external_device_info_source="udev"
where udev database records are used to do various filtering decisions.

For example:

udev log of timed out worker:

Nov 11 13:02:25 raw.virt systemd-udevd[607]: seq 1997 '/devices/virtual/block/dm-2' is taking a long time
Nov 11 13:04:25 raw.virt systemd-udevd[607]: seq 1997 '/devices/virtual/block/dm-2' killed
Nov 11 13:04:25 raw.virt systemd-udevd[607]: worker [11221] terminated by signal 9 (Killed)
Nov 11 13:04:25 raw.virt systemd-udevd[607]: worker [11221] failed while handling '/devices/virtual/block/dm-2'
...

LVM also issues error message visibly if incomplete udev db record is found,
devices/external_device_info_source="udev" is set:

$ pvs
  Udev database has incomplete information about device /dev/dm-2.
  Failed to get external handle for device /dev/dm-2 [udev].
  ...
2015-11-11 13:14:07 +01:00
6d0db97163 libdm: reorder error path
Coverity noticed recent fix of an error path missed to
release 'dmt' - reoder code to ensure 'dmt' is released.
2015-11-10 21:41:47 +01:00
a45cc0fe14 raid: fix the string compare
Coverity noticed this condition is always false and the error
path could never be visited.

So check for all mismatches of supported messages
and actually mark log_error as internal error.
2015-11-10 21:40:28 +01:00
59905100d1 coverity: Add placeholder modelling file. 2015-11-10 01:37:11 +00:00
fb59847a0f libdm: replace assign with increment
Coverity didn't liked assign with && expression, so use trick.
It does not complain against this prefix incremenent operation.
2015-11-09 22:51:48 +01:00
7ec61cd5b9 vgrename: check if new and old names match
When the first arg is a UUID and vgrename translates
that UUID to a current VG name, the old and new VG
names are not being checked for equality.  If they
are equal, it produces an internal error rather than
a proper error.
2015-11-09 13:23:59 -06:00
cd937efa77 lvmetad: change recent cleanups
with better alternatives.
2015-11-09 12:18:43 -06:00
d2d5191b78 lvmlockd: reverse some unnecessary checking
These are unnecessary or not useful.
2015-11-09 12:18:43 -06:00
a0cb92cbb1 tests: handle missing delay_dev
Try to run as much of test which could run without delay_dev.
2015-11-09 19:07:53 +01:00
6762eec88c lvmlockd: fix the NO_GL_LS condition
indicating when no global lockspace exists.
2015-11-09 11:33:16 -06:00
45e749493c cleanup: ensuring string is not NULL
Coverity cannot see the string cannot be NULL so make it explicit.
2015-11-09 17:04:10 +01:00
76b42901c0 cache: ensure there is no NULL str
Coverity is not smart enough to detect this case could never happen.
2015-11-09 17:04:10 +01:00
b1215b7f8c lvmlockd: enforce 64bit arithmetic
Coverity suggest to stay on the 'safe' side and widen operators early
so 64bit offset is made from 64bit arithmentic.
2015-11-09 17:04:10 +01:00
d6767d753f lvmlockd: add missing error checks
Detect error from function and report them.
2015-11-09 17:04:10 +01:00
c2d5cfbdb8 cleanup: use _ for local function 2015-11-09 17:04:10 +01:00
3db5ba08b1 cleanup: drop unneded headers
Coverity notices they are not really needed.
2015-11-09 17:04:10 +01:00
6c331f3061 dmsetup: one missed dms 2015-11-09 17:04:10 +01:00
32762e2a9c libdaemon: fix passing 32bit values for %d
Since %d is now prohibited for its great confusion,
replace it with  FMTd64 and correctly converted int64_t
parameter.
2015-11-09 17:04:10 +01:00
e207ededd6 lvmlockd: shut up warnings 2015-11-09 10:00:04 -06:00
36ee367343 libdaemon: prohibit use of %d for 64bit numbres
Do not let pass %d and print internal error when found one.
Require all users to use  FMTd64 - it's seriously confusing.
2015-11-09 14:03:25 +01:00
0b5a75c9af lvmetad: restore use of FMTd64
daemon_reply_simple() eats just 64bit numbers - so make it explicit.
2015-11-09 14:02:27 +01:00
7103012754 tests: update test to check for race better
Use  delay_dev to slow down mirror sync so we could more
easily check for race and proper reject of parallel mirror
leg addition/reduction.

Also expose fail in mirror allocation of parallel leg.
2015-11-09 12:21:17 +01:00
ab4773671b tests: do not skip test when delay is missing
Rather then skipping whole test - just do not use it.

Failing tests that have required delay need to deal with reality
and shell either check for HAVE_DM_DELAY and skip portion
of test or using should when needed.
2015-11-09 12:21:17 +01:00
e4c9b390ca cleanup: update comment 2015-11-09 12:21:17 +01:00
84a9546869 dmsetup: cleanup warn for older compilers
Older gcc somehow thinks there is a path of using
subcommand uninitilized.

So make it more obvious there is no such one.
2015-11-09 12:21:17 +01:00
5aae8de776 lvmetad: maintain seqno as int
Keep seqno as 32bit value.
Also use '_' prefix for local _update_metadata.
2015-11-09 12:21:17 +01:00
57c2a1ae8c raid: mark intententional copy and paste
Coverity: add this extra comment, to let Coverity know this
slightly changed copy&paste code is intentional.
2015-11-09 10:22:52 +01:00
846adadbcc cleanup: use code in place
Pass const strings to printf(),
and use  struct names directly instead of creating unused vars on stack.
2015-11-09 10:22:52 +01:00
22e19cb354 cleanup: reoder rstatus init
In all error paths always initialize *rstatus.
2015-11-09 10:22:52 +01:00
b1dab26be0 cleanup: coverity quiet
While through all codepaths we never 'read' lock_id unless LCKF_CONVERT,
coverity cannot decrypt this.

As since it's usually better to pass in 'well-defined' data structures
preset lock_id to 0.
2015-11-09 10:22:52 +01:00
11151121aa cleanup: use fputs for plain strings
Use fputs() when printing plain string,
easier then fprintf which needs to parse it.

Also check fd before close is >= 0 -
it is - but coverity fail to see it, so eliminate
this false-positive warning.
2015-11-09 10:22:52 +01:00
c4c5635870 cleanup: drop unneeded assign
prio is always assigned later.
2015-11-09 10:22:52 +01:00
e262d5e596 cleanup: keep using enum typedef
Using enum instead of unsigned.
2015-11-09 10:22:52 +01:00
9b9b5d0ea2 cleanup: use 64bit multiply for print 2015-11-09 10:22:52 +01:00
f6d2528f64 cleanup: drop unneeded header file 2015-11-09 10:22:51 +01:00
5ba219e87a cleanup: use display_lvname 2015-11-09 10:22:51 +01:00
04f76d9020 cleanup: use NAME_LEN
Let's have instant check for max name len when creating
subLV name.
2015-11-09 10:22:51 +01:00
5c48ef993b cleanup: use NAME_LEN buffer instead of alloca
Drop alloca and use NAME_LEN size to get implicit check
for max len of LV name.
2015-11-09 10:22:51 +01:00
2e04eee192 cleanup: do not test alloca for NULL
alloca() never returns NULL.
In case stack is out-of-range the behaviour is undefined.
2015-11-09 10:22:51 +01:00
c542c18d2a cleanup: drop unneded assign
Coverity doesn't really like to see subcommand being assigned NULL,
so drop it.
2015-11-09 10:22:51 +01:00
07046e994f alloc: use own mem pool for alloc_handle
Keep alloc_handle's data in a single mempool and do not
spread them into vgmem pool.
2015-11-09 10:22:49 +01:00
0c380c316c cleanup: relocate error capture
Capture internal error before allocation anything.
2015-11-09 10:21:09 +01:00
67b4761bc3 toollib: add missing check for lvmcache_init()
Coverity notices lvmcache_init() may fail so check and
error out in case of failure.
2015-11-09 10:19:20 +01:00
164d7e72bf devmanager: validate target params
Coverity: ensure we do not read through NULL pointers for
target_type and params.
2015-11-09 10:19:20 +01:00
4f8f8fcb52 report: add extra pointer check
Coverity was seeing possible trouble with NULL pointer dereference.
So ensure it may never happen.
2015-11-09 10:19:20 +01:00
856e11e11c lv_manip: do not deref NULL for debug message
Coverity: when 'pv2' would be passed as NULL, do not try to
deref it in debug message.
2015-11-09 10:19:20 +01:00
fa1d730847 dev-type: fix TOCTOU order
Doing 'stat' checking first and later opening is racy.
And since we do not really care about any 'status' info
here and we read 'sysfs' here - just drop whole 'stat()'
call and directly handle error from failing 'fopen()'.
2015-11-09 10:19:20 +01:00
80c3fb786c thin: fix error path mem leak
Coverity: when parsing of thin-pool status would have failed,
it could have leaked memory pool and dmt struct.
2015-11-09 10:19:19 +01:00
3cadc1c87e libdm: add test for dm_task_get_message_response()
Coverity notices dm_task_get_message_response() result should be
checked for NULL which should not be passed to dm_pool_strdup().
2015-11-09 10:19:19 +01:00
84303dc17a libdm: exlicitly check for NULL
Coverity: another explict check for NULL, where coverity fails to
see it.
2015-11-09 10:19:19 +01:00
f6c140e200 libdm: ensure vars are initialized
Coverity found potential error path, where code could
have used some unset variables.
2015-11-09 10:19:19 +01:00
b1c4017743 libdm: add missing error path check
Coverity: do not continue with section cloning when root node
would a NULL.
2015-11-09 10:19:19 +01:00
18fd0bd20c lvconvert: add extra check for existance of pointer
Coverity here is not fully-in-picture - but please it
with validation of pointer which currently cannot be null,
since we always return at least empty string.
2015-11-09 10:19:19 +01:00
b83a20b80a lvmetad: validate mda is not NULL
Coverity: make it explicitely obvious metadata area is not NULL.
2015-11-09 10:19:19 +01:00
99def8f439 lvmetad: check for pointers not NULL
Check for  arg_vgid_lookup and arg_name_lookup not being NULL.
Drop checking arg_vgid and arg_name for NULL since they
are already dereference earlier - thus mostly must be NOT NULL.

(If that would be possible larger rework of this function would be
required).
2015-11-09 10:19:19 +01:00
f66fe2c444 lvmetad: require meta_lookup
Coverity: do not call update_pvid_to_vgid() with
meta_lookup == NULL since it is dereferencing it.
2015-11-09 10:19:19 +01:00
91bde0f4a1 lvmetad: check for allocation fail
Coverity: missing check for root != NULL as this pointer is
later dereferenced in add_last_node().
2015-11-09 10:19:19 +01:00
297d6773af dmsetup: add missing checks for dm_stats_create() ret value
Coverity likes to see a check for dms not being NULL, so
add those missing ones...
2015-11-09 10:19:19 +01:00
e90c5d2060 dmsetup: check for NULL from dm_task_get_ioctl_timestamp
Coverity: ensure NULL is not passed to dm_timestamp_delta().
2015-11-09 10:19:19 +01:00
9df3069083 clvmd: check for pthread_create status
Coverity: likes to see checked function result.
2015-11-09 10:19:18 +01:00
2c8d6f5c90 dmeventd: open fifo in one function
Put calls related to fifo opening into a single function.

Fix  Time-Of-Check-Time-Of-Use and use fstat()
and fchmod() on already opened fd instead of
checking first path and then risking to open something
different.
2015-11-09 10:18:53 +01:00
e1b111b02a dmeventd: reorder tou 2015-11-09 10:00:33 +01:00
8b857bfdc6 libdevmapper-event: fix fifo leak on error path
Coverity: when _init_client() fails, client fifo could have
been already openned and needs to be closed on error path.
2015-11-09 10:00:13 +01:00
459b3db61e configure: report whether to build lvmlockd
Report configured status for build with lvmlockd.
2015-11-09 09:58:27 +01:00
af6adec7cc post-release 2015-11-09 01:48:57 +00:00
a3f77ed4ba pre-release 2015-11-09 01:45:22 +00:00
b9341e36f1 test: disable duplicate VG name test for lvmetad
Until we decide how duplicate VG names should be
handled by lvmetad, and implement that.
2015-11-06 15:58:22 -06:00
8096f2224c mirror: Fix log size calc when more than 1 extent.
Currently the code creates the log separately after allocating space for
the data and as no data allocation is needed this second time,
total_extents ends up holding zero so use new_extents directly instead.
2015-11-05 23:40:47 +00:00
16780f6faa vg_read: skip repair and wipe for foreign and shared VGs
When reading a foreign VG we cannot write it, since
it belongs to another host.  When reading a shared VG
we cannot write it because we may not have an ex lock.
(Or we may be reading the shared VG while not using
lvmlockd in which case it's like reading a foreign VG.)

Add the same checks for wiping outdated PVs.  We may
read a foreign or shared VG, or see the PVs, while
another host is part way through writing a new version
of the VG to the PVs.  This might cause us to think
some of the PVs are outdated.  We do not want to
write another host's PVs, especially when we may
wrongly conclude they are outdated.
2015-11-03 13:42:21 -06:00
4103896ca0 lvmcache: change log_verbose to log_warn
Without this, some cases miss printing a
warning for duplicate PVs.
2015-11-03 13:37:31 -06:00
d30105f471 lvmetad: log duplicate PVs returned from lvmetad
When the command gets a list of alternate devices
from lvmetad, log each one directly.  This is not
the same as the warnings when adding lvmcache,
which are related to which duplicate is preferred.
2015-11-03 13:35:51 -06:00
19feda2c95 tests: skip duplicate vg names test with lvmetad
If two PVs have different VGs with the same name
(different uuids), one of the VGs is ignored by
lvmetad.  A FIXME exists in lvmetad to find a
better response.
2015-11-03 13:25:35 -06:00
4e6377f5ba lvmetad: refactor and document
update_metadata and pv_found update the cached metadata;
these are both reworked to improve the code, organize it
by each possible state and transition, make it much more
clear what's changing, add more error checking and
handling, and add comments.

The state and content of the cache (hash tables) does not
change (apart from some things that didn't work before),
and the communication to/from commands does not change.
The implementation and organization of the code making
the state changes does change significantly.

One detail related to the content of the cache does change:
different hash tables do not reference the same memory any more;
the target values in each hash table are allocated and freed
individually.
2015-11-03 13:18:27 -06:00
4b47ee5296 config: fix copy error in examples
The same example was copied without
changing the variable name.
2015-11-03 11:07:27 -06:00
1055 changed files with 103673 additions and 25132 deletions

2
.gitignore vendored
View File

@ -7,6 +7,8 @@
*.orig
*.pc
*.pot
*.pyc
*.pyo
*.rej
*.so
*.so.*

View File

@ -2,7 +2,7 @@
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
@ -305,7 +305,7 @@ the "copyright" line and a pointer to where the full notice is found.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.

View File

@ -10,7 +10,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@
@ -59,6 +59,8 @@ liblvm: lib
daemons: lib libdaemon tools
tools: lib libdaemon device-mapper
po: tools daemons
man: tools
all_man: tools
scripts: liblvm libdm
lib.device-mapper: include.device-mapper
@ -95,10 +97,10 @@ endif
DISTCLEAN_TARGETS += cscope.out
CLEAN_DIRS += autom4te.cache
check check_system check_cluster check_local check_lvmetad check_lvmpolld unit: all
check check_system check_cluster check_local check_lvmetad check_lvmpolld check_lvmlockd_test check_lvmlockd_dlm check_lvmlockd_sanlock unit: all
$(MAKE) -C test $(@)
conf.generate: tools
conf.generate man.generate: tools
# how to use parenthesis in makefiles
leftparen:=(
@ -128,8 +130,9 @@ rpm: dist
$(top_srcdir)/spec/source.inc >$(rpmbuilddir)/SOURCES/source.inc
rpmbuild -v --define "_topdir $(rpmbuilddir)" -ba $(top_srcdir)/spec/lvm2.spec
generate: conf.generate
generate: conf.generate man.generate
$(MAKE) -C conf generate
$(MAKE) -C man generate
all_man:
$(MAKE) -C man all_man
@ -166,8 +169,11 @@ install_tmpfiles_configuration:
LCOV_TRACES = libdm.info lib.info liblvm.info tools.info \
libdaemon/client.info libdaemon/server.info \
daemons/clvmd.info daemons/dmeventd.info \
daemons/lvmetad.info
daemons/clvmd.info \
daemons/dmeventd.info \
daemons/lvmetad.info \
daemons/lvmlockd.info \
daemons/lvmpolld.info
CLEAN_TARGETS += $(LCOV_TRACES)

5
README
View File

@ -6,11 +6,12 @@ Installation instructions are in INSTALL.
There is no warranty - see COPYING and COPYING.LIB.
Tarballs are available from:
ftp://sourceware.org/pub/lvm2/
ftp://sources.redhat.com/pub/lvm2/
The source code is stored in git:
http://git.fedorahosted.org/git/lvm2.git
git clone git://git.fedorahosted.org/git/lvm2.git
https://sourceware.org/git/?p=lvm2.git
git clone git://sourceware.org/git/lvm2.git
Mailing list for general discussion related to LVM2:
linux-lvm@redhat.com

View File

@ -1 +1 @@
2.02.134(2)-git (2015-10-30)
2.02.172(2)-git (2017-06-28)

View File

@ -1 +1 @@
1.02.111-git (2015-10-30)
1.02.141-git (2017-06-28)

595
WHATS_NEW
View File

@ -1,5 +1,598 @@
Version 2.02.134 -
Version 2.02.172 - 28th June 2017
=================================
Add missing NULL to argv array when spliting cmdline arguments.
Add display_percent helper function for printing percent values.
lvconvert --repair handles failing raid legs (present but marked 'D'ead).
Do not lvdisplay --maps unset settings of cache pool.
Fix lvdisplay --maps for cache pool without policy settings.
Support aborting of flushing cache LV.
Reenable conversion of data and metadata thin-pool volumes to raid.
Improve raid status reporting with lvs.
No longer necessary to '--force' a repair for RAID1.
Linear to RAID1 upconverts now use "recover" sync action, not "resync".
Improve lvcreate --cachepool arg validation.
Limit maximum size of thin-pool for specific chunk size.
Print a warning about in-use PVs with no VG using them.
Disable automatic clearing of PVs that look like in-use orphans.
Cache format2 flag is now using segment name type field.
Support storing status flags via segtype name field.
Stop using '--yes' mode when fsadm runs without terminal.
Extend validation of filesystems resized by fsadm.
Enhance lvconvert automatic settings of possible (raid) LV types.
Allow lvchange to change properties on a thin pool data sub LV.
Fix lvcreate extent percentage calculation for mirrors.
Don't reinstate still-missing devices when correcting inconsistent metadata.
Properly handle subshell return codes in fsadm.
Disallow cachepool creation with policy cleaner and mode writeback.
Version 2.02.171 - 3rd May 2017
===============================
Fix memory warnings by using mempools for command definition processing.
Fix running commands from a script file.
Add pvcreate prompt when device size doesn't match setphysicalvolumesize.
lvconvert - preserve region size on raid1 image count changes
Adjust pvresize/pvcreate messages and prompt if underlying dev size differs.
raid - sanely handle insufficient space on takeover.
Fix configure --enable-notify-dbus status message.
Change configure option name prefix from --enable-lockd to --enable-lvmlockd.
lvcreate - raise mirror/raid default regionsize to 2MiB
Add missing configurable prefix to configuration file installation directory.
Version 2.02.170 - 13th April 2017
==================================
Introduce global/fsadm_executable to make fsadm path configurable.
Look for limited thin pool metadata size when using 16G metadata.
Add lvconvert pool creation rule disallowing options with poolmetadata.
Fix lvconvert when the same LV is incorrectly reused in options.
Fix lvconvert VG name validation in option values.
Fix missing lvmlockd LV locks in lvchange and lvconvert.
Fix dmeventd setup for lvchange --poll.
Fix use of --poll and --monitor with lvchange and vgchange.
Disallow lvconvert of hidden LV to a pool.
Ignore --partial option when not used for activation.
Allow --activationmode option with lvchange --refresh.
Better message on lvconvert --regionsize
Allow valid lvconvert --regionsize change
Add raid10 alias raid10_near
Handle insufficient PVs on lvconvert takeover
Fix SIGINT blocking to prevent corrupted metadata
Fix systemd unit existence check for lvmconf --services --startstopservices.
Check and use PATH_MAX buffers when creating vgrename device paths.
Version 2.02.169 - 28th March 2017
==================================
Automatically decide whether '-' in a man page is a hyphen or a minus sign.
Add build-time configuration command line to 'lvm version' output.
Handle known table line parameter order change in specific raid target vsns.
Conditionally reject raid convert to striped/raid0* after reshape.
Ensure raid6 upconversion restrictions.
Adjust mirror & raid dmeventd plugins for new lvconvert --repair behaviour.
Disable lvmetad when lvconvert --repair is run.
Remove obsolete lvmchange binary - convert to built-in command.
Show more information for cached volumes in lvdisplay [-m].
Add option for lvcreate/lvconvert --cachemetadataformat auto|1|2.
Support cache segment with configurable metadata format.
Add allocation/cache_metadata_format profilable settings.
Use function cache_set_params() for both lvcreate and lvconvert.
Skip rounding on cache chunk size boudary when create cache LV.
Improve cache_set_params support for chunk_size selection.
Fix metadata profile allocation/cache_[mode|policy] setting.
Fix missing support for using allocation/cache_pool_chunk_size setting.
Upstream git moved to https://sourceware.org/git/?p=lvm2
Support conversion of raid type, stripesize and number of disks
Reject writemostly/writebehind in lvchange during resynchronization.
Deactivate active origin first before removal for improved workflow.
Fix regression of accepting both --type and -m with lvresize. (2.02.158)
Add lvconvert --swapmetadata, new specific way to swap pool metadata LVs.
Add lvconvert --startpoll, new specific way to start polling conversions.
Add lvconvert --mergethin, new specific way to merge thin snapshots.
Add lvconvert --mergemirrors, new specific way to merge split mirrors.
Add lvconvert --mergesnapshot, new specific way to combine cow LVs.
Split up lvconvert code based on command definitions.
Split up lvchange code based on command definitions.
Generate help output and man pages from command definitions.
Verify all command line items against command definition.
Match every command run to one command definition.
Specify every allowed command definition/syntax in command-lines.in.
Add extra memory page when limiting pthread stack size in clvmd.
Support striped/raid0* <-> raid10_near conversions.
Support shrinking of RaidLVs.
Support region size changes on existing RaidLVs.
Avoid parallel usage of cpg_mcast_joined() in clvmd with corosync.
Support raid6_{ls,rs,la,ra}_6 segment types and conversions from/to it.
Support raid6_n_6 segment type and conversions from/to it.
Support raid5_n segment type and conversions from/to it.
Support new internal command _dmeventd_thin_command.
Introduce new dmeventd/thin_command configurable setting.
Use new default units 'r' for displaying sizes.
Also unmount mount point on top of MD device if using blkdeactivate -u.
Restore check preventing resize of cache type volumes (2.02.158).
Add missing udev sync when flushing dirty cache content.
vgchange -p accepts only uint32 numbers.
Report thin LV date for merged LV when the merge is in progress.
Detect if snapshot merge really started before polling for progress.
Checking LV for merging origin requires also it has merged snapshot.
Extend validation of metadata processing.
Enable usage of cached volumes as snapshot origin LV.
Fix displayed lv name when splitting snapshot (2.02.146).
Warn about command not making metadata backup just once per command.
Enable usage of cached volume as thin volume's external origin.
Support cache volume activation with -real layer.
Improve search of lock-holder for external origin and thin-pool.
Support status checking of cache volume used in layer.
Avoid shifting by one number of blocks when clearing dirty cache volume.
Extend metadata validation of external origin LV use count.
Fix dm table when the last user of active external origin is removed.
Improve reported lvs status for active external origin volume.
Fix table load for splitted RAID LV and require explicit activation.
Always active splitted RAID LV exclusively locally.
Do not use LV RAID status bit for segment status.
Check segtype directly instead of checking RAID in segment status.
Reusing exiting code for raid image removal.
Fix pvmove leaving -pvmove0 error device in clustered VG.
Avoid adding extra '_' at end of raid extracted images or metadata.
Optimize another _rmeta clearing code.
Fix deactivation of raid orphan devices for clustered VG.
Fix lvconvert raid1 to mirror table reload order.
Add internal function for separate mirror log preparation.
Fix segfault in lvmetad from missing NULL in daemon_reply_simple.
Simplify internal _info_run() and use _setup_task_run() for mknod.
Better API for internal function _setup_task_run.
Avoid using lv_has_target_type() call within lv_info_with_seg_status.
Simplify internal lv_info_with_seg_status API.
Decide which status is needed in one place for lv_info_with_seg_status.
Fix matching of LV segment when checking for it info status.
Report log_warn when status cannot be parsed.
Test segment type before accessing segment members when checking status.
Implement compatible target function for stripe segment.
Use status info to report merge failed and snapshot invalid lvs fields.
Version 2.02.168 - 30th November 2016
=====================================
Display correct sync_percent on large RaidLVs
lvmdbusd --blackboxsize <n> added, used to override default size of 16
Allow a transiently failed RaidLV to be refreshed
Use lv_update_and_reload() inside mirror code where it applies.
Preserve mirrored status for temporary layered mirrors.
Use transient raid check before repairing raid volume.
Implement transient status check for raid volumes.
Only log msg as debug if lvm2-lvmdbusd unit missing for D-Bus notification.
Avoid duplicated underscore in name of extracted LV image.
Missing stripe filler now could be also 'zero'.
lvconvert --repair accepts --interval and --background option.
More efficiently prepare _rmeta devices when creating a new raid LV.
Version 2.02.167 - 5th November 2016
====================================
Use log_error in regex and sysfs filter to describe reason of failure.
Fix blkdeactivate to deactivate dev stack if dev on top already unmounted.
Prevent non-synced raid1 repair unless --force
Prevent raid4 creation/conversion on non-supporting kernels
Add direct striped -> raid4 conversion
Fix raid4 parity image pair position on conversions from striped/raid0*
Fix a few unconverted return code values for some lvconvert error path.
Disable lvconvert of thin pool to raid while active.
Disable systemd service start rate limiting for lvm2-pvscan@.service.
Version 2.02.166 - 26th September 2016
======================================
Fix lvm2-activation-generator to read all LVM2 config sources. (2.02.155)
Fix lvchange-rebuild-raid.sh to cope with older target versions.
Use dm_config_parse_without_dup_node_check() to speedup metadata reading.
Fix lvconvert --repair regression
Fix reported origin lv field for cache volumes. (2.02.133)
Always specify snapshot cow LV for monitoring not internal LV. (2.02.165)
Fix lvchange --discard|--zero for active thin-pool.
Enforce 4MiB or 25% metadata free space for thin pool operations.
Fix lock-holder device for thin pool with inactive thin volumes.
Use --alloc normal for mirror logs even if the mimages were stricter.
Use O_DIRECT to gather metadata in lvmdump.
Ignore creation_time when checking for matching metadata for lvmetad.
Fix possible NULL pointer derefence when checking for monitoring.
Add lvmreport(7) man page.
Don't install lvmraid(7) man page when raid excluded. (2.02.165)
Report 0% as dirty (copy%) for cache without any used block.
Fix lvm2api reporting of cache data and metadata percent.
Restore reporting of metadata usage for cache volumes (2.02.155).
Support raid scrubbing on cache origin LV.
Version 2.02.165 - 7th September 2016
=====================================
Add lvmraid(7) man page.
Use udev db to check for mpath components before running pvscan for lvmetad.
Use lsblk -s and lsblk -O in lvmdump only if these options are supported.
Fix number of stripes shown in lvcreate raid10 message when too many.
Change lvmdbusd to use new lvm shell facilities.
Do not monitor cache-pool metadata when LV is just being cleared.
Add allocation/cache_pool_max_chunks to prevent misuse of cache target.
Give error not segfault in lvconvert --splitmirrors when PV lies outside LV.
Fix typo in report/columns_as_rows config option name recognition (2.02.99).
Avoid PV tags when checking allocation against parallel PVs.
Disallow mirror conversions of raid10 volumes.
Fix dmeventd unmonitoring when segment type (and dso) changes.
Don't allow lvconvert --repair on raid0 devices or attempt to monitor them.
No longer adjust incorrect number of raid stripes supplied to lvcreate.
Move lcm and gcd to lib/misc.
Fix vgsplit of external origins. (2.02.162)
Prohibit creation of RAID LVs unless VG extent size is at least the page size.
Suppress some unnecessary --stripesize parameter warnings.
Fix 'pvmove -n name ...' to prohibit collocation of RAID SubLVs
Version 2.02.164 - 15th August 2016
===================================
Fix selection of PVs when allocating raid0_meta.
Fix sdbus socket leak leading to hang in lvmnotify.
Specify max stripes for raid LV types: raid0:64; 1:10; 4,5:63; 6:62; 10:32.
Avoid double suffix when naming _rmeta LV paired with _rimage LV.
Version 2.02.163 - 10th August 2016
===================================
Add profile for lvmdbusd which uses lvm shell json report output.
Restrict in-command modification of some parms in lvm shell.
Apply LVM_COMMAND_PROFILE early for lvm shell.
Refactor reporting so lvm shell log report collects whole of cmd execution.
Support LVM_*_FD envvars to redirect output to file descriptors.
Limit use of --corelog and --mirrorlog to mirrors in lvconvert.
Reject --nosync option for RAID6 LVs in lvcreate.
Do not refresh whole cmd context if profile dropped after processing LVM cmd.
Support straightforward lvconvert between striped and raid4 LVs.
Support straightforward lvconvert between raid1 and mirror LVs.
Report supported conversions when asked for unsupported raid lvconvert.
Add "--rebuild PV" option to lvchange to allow for PV selective rebuilds.
Preserve existing mirror region size when using --repair.
Forbid stripe parameters with lvconvert --repair.
Unify stripe size validation into get_stripe_params to catch missing cases.
Further lvconvert validation logic refactoring.
Version 2.02.162 - 28th July 2016
=================================
Extend vg_validate also to check raid configurations thoroughly.
Support lvconvert -Zn also when doing full cache pool conversion.
Suppress not zeroing warn when converting to thin LV for non-zeroing tpool.
Fix automatic updates of PV extension headers to newest version.
Improve lvconvert --trackchanges validation to require --splitmirrors 1.
Add note about lastlog built-in command to lvm man page.
Fix unrecognised segtype flag message.
lvconvert not clears cache pool metadata ONLY with -Zn.
Add allocation/raid_stripe_all_devices to reinstate previous behaviour.
Create raid stripes across fixed small numbers of PVs instead of all PVs.
Enabled lvconvert --uncache to work with partial VG.
Disallow lvconvert --replace with raid0* LVs.
Fix some lvmetad changed VG metadata notifications that sent uncommitted data.
Version 2.02.161 - 15th July 2016
=================================
Prohibit some lvchange/lvresize that were failing on raid0 volumes.
Fix segfaults in complex vgsplits. (2.02.159)
Reformat unwieldy lvconvert man page.
Allow --force to be passed through to pvcreate from vgcreate. (2.02.144)
Fix lvresize of filesystem when LV has already right size (2.02.141)
New LVM_LOG_FILE_MAX_LINES env var to limit max size of created logs.
Version 2.02.160 - 6th July 2016
================================
Minor fixes from coverity.
Version 2.02.159 - 6th July 2016
================================
Add raid0_meta segment type that provides metadata space for raid conversions.
Fix created link for a used pool for vgmknode.
Introduce and use is_power_of_2 macro.
Support conversions between striped and raid0 segment types.
Add infrastructure for raid takeover lvconvert options.
Version 2.02.158 - 25th June 2016
=================================
Add a more efficient native vgimportclone command to replace the script.
Make lvmlockd always attempt to connect to lvmetad if no connection exists.
Let lvmetad handle new connections after shutdown signal.
Disable lvmetad when vgcfgrestore begins and enable it again after.
Make pvscan do activation if lvmetad is configured but not running.
Fix rescanning the PVs for a single VG when using lvmetad.
Pool metadata lvresize uses now same code as resize of normal volume.
Preserve monitoring status when updating thin-pool metadata.
Return 0 (inactive) when status cannot be queried in _lv_active().
Switch to log_warn() for failing activation status query.
Replace vgimportclone script with binary.
While lvmetad is shutting down, continue handling all connections cleanly.
Refactor lvconvert argument handling code.
Notify lvmetad when vgcfgrestore changes VG metadata.
Add --logonly option to report only cmd log for a command, not other reports.
Add log/command_log_selection to configure default selection used on cmd log.
Use 'orphan' object type in cmd log for groups to collect PVs not yet in VGs.
Add lvm lastlog command for query and display of last cmd's log in lvm shell.
Report per-object return codes via cmd log while processing multiple objects.
Annotate processing code with log report hooks for per-object command log.
Also pass common printed messages (besides warnings and errors) to log report.
Log warnings and errors via report during cmd processing if this is enabled.
Make it possible to iterate over internal 'orphan' VGs in process_each_vg fn.
Make -S|--select option groupable that allows this option to be repeated.
Make -O|--sort option groupable that allows this option to be repeated.
Add --configreport option to select report for which next options are applied.
Add support for priorities on grouping command arguments.
Add report/{pvs,vgs,lvs,pvsegs,segs}_{cols,sort}_full to lvm.conf.
Add lvm fullreport command for joined PV, VG, LV and segment report per VG.
Integrate report group handling and cmd log report into cmd processing code.
Add log/report_command_log to lvm.conf to enable or disable cmd log report.
Add log/report_output_format to lvm.conf for default report output format.
Recognize --reportformat {basic|json} option to select report output format.
Add log/command_log_{sort,cols} to lvm.conf to configure command log report.
Add log_object_{type,name,id,group,group_id} fields to cmd log.
Add log_{seq_num,type,context,message,errno,ret_code} fields to cmd log.
Add CMDLOG report type - a separate report type for command logging.
Version 2.02.157 - 17th June 2016
=================================
Change pvscan --cache -aay to scan locally if lvmetad fails.
Version 2.02.156 - 11th June 2016
=================================
Don't allow duplicate orphan PVs to be used with vgcreate/vgextend/pvcreate.
Improve handling of lvmetad update failures.
Yes/No prompt accepts '^[ ^t]*([Yy]([Ee]([Ss]|)|)|[Nn]([Oo]|))[ ^t]*$'.
If available, also collect output from lsblk command when running lvmdump -s.
Version 2.02.155 - 3rd June 2016
================================
Reject PV tags on pvmove cmdline because only 1 PV is supported. (2.02.141)
Fix compilation error when building with configure --disable-devmapper.
Fix lvmconfig --type diff to display complete diff if config cascade used.
Automatically filter out partitioned loop devices with partscan (losetup -P).
Fix lvm devtypes internal error if -S used with field name from pvs/vgs/lvs.
When reporting Data%,Snap%,Meta%,Cpy%Sync use single ioctl per LV.
Add lvseg_percent_with_info_and_seg_status() for percent retrieval.
Enhance internal seg_status handling to understand snapshots better.
When refresh failed in suspend, call resume upon error path.
Support passthrough cache mode when waiting for clean cache.
Check cache status only for 'in-use' cache pools.
Extend setup_task() to preset flushing for dm_task object.
When checking LV is a merging COW, validate its a COW LV first.
Correcting value in copy_percent() for 100%.
Update vgreduce to use process_each_vg.
Update lvconvert to use process_each_lv.
Update pvscan to use process_each_vg for autoactivation.
Add basic support for --type raid0 using md.
Add support for lvchange --cachemode for cached LV.
Fix liblvm2app error handling when setting up context.
Delay liblvm2app init in python code until it is needed.
Simplify thread locking in lvmetad to fix locking problems.
Allow pvremove -ff to remove a duplicate PV.
Fix lvm2-activation-generator to read lvm.conf without full command setup.
Allow a minimal context to be used in lvm2app for reading lvm.conf.
Version 2.02.154 - 14th May 2016
================================
Fix liblvm segfault after failure initialising lvmetad connection.
Retry open without O_NOATIME if it fails (not file owner/CAP_FOWNER).
Split _report into one fn for options and arguments and one for processing.
Version 2.02.153 - 7th May 2016
===============================
Change warning messages related to duplicate PVs.
A named device is always processed itself, not switched for a duplicate.
Add PV attr "d" and report field "duplicate" for duplicate PVs.
Add config setting to disallow VG changes when duplicate PVs exist.
Use device size and active LVs to choose the preferred duplicate PV.
Disable lvmetad when duplicate PVs are seen.
Support --chunksize option also when caching LV when possible.
Add function to check for target presence and version via 1 ioctl.
Version 2.02.152 - 30th April 2016
==================================
Use any inherited tags when wiping metadata sub LVs to ensure activation.
Add str_list_wipe.
Improve support for interrupting procesing of volumes during lvchange.
Use failed command return code when lvchanging read-only volume.
Show creation transaction_id and zeroing state of pool with thin volume.
Stop checking for dm_cache_mq policy with cache target 1.9 (alias to smq).
Check first /sys/module/dm_* dir existance before using modprobe.
Remove mpath from 10-dm.rules, superseded by 11-dm-mpath.rules (mpath>=0.6.0).
Version 2.02.151 - 23rd April 2016
==================================
Fix error path after reusing of _setup_task (2.02.150).
Fix memory access for empty sysfs values (2.02.149).
Disable lvmetad when lvm1 metadata is seen, so commands revert to scanning.
Suppress errors when snapshot merge gets delayed because volume is in use.
Avoid internal snapshot LV names in messages.
Autodetect and use /run/lock dir when available instead of /var/lock.
lvchange --refresh for merging thin origin will retry to deactivate snapshot.
Recognize in-progress snapshot merge for thin volumes from dm table.
Avoid deciding to initiate a pending snapshot merge during resume.
Improve retrying lvmetad requests while lvmetad is being updated.
Read devices instead of using the lvmetad cache if rescan fails.
Move lvmetad token/filter check and device rescan to the start of commands.
Don't try deactivating fictional internal LV before snapshot merge. (2.02.105)
When not obtaining devs from udev, check they exist before caching them.
Detect device mismatch also when compiling without udev support.
Version 2.02.150 - 9th April 2016
=================================
Avoid using flushing dm status ioctl when checking for usable DM device.
Check for devices without LVM- uuid prefix only with kernels < 3.X.
Reuse %FREE size aproximation with lvcreate -l%PVS thin-pool.
Allow the lvmdump directory to exist already provided it is empty.
Show lvconverted percentage with 2 decimal digits.
Fix regression in suspend when repairing --type mirror (2.02.133).
Version 2.02.149 - 1st April 2016
=================================
Do not flush thin-pool when checking metadata fullness.
Remove spurious error about no value in /sys/dev/block/major:minor/dm/uuid.
Fix device mismatch detection for LV if persistent .cache file is used.
Fix holder device not being found in /dev while sysfs has it during dev scan.
Version 2.02.148 - 26th March 2016
==================================
Introduce TARGET_NAME and MODULE NAME macros.
Replace hard-coded module and target names with macros.
Add pv_major and pv_minor report fields.
Detect and warn about mismatch between devices used and assumed for an LV.
Version 2.02.147 - 19th March 2016
==================================
If available, use /proc/self/mountinfo to detect mounted volume in fsadm.
Fix resize of stacked raid thin data volume (2.02.141).
Fix test for lvremove failure in lvconvert --uncache (2.02.146).
Version 2.02.146 - 11th March 2016
==================================
More man page cleanups in lvconvert.
Fix makefile vpath in /udev when generating udev rules files.
Another attempt to improve VG name parsing for lvconvert (2.02.144).
Use new cache status info and skip flushing for failed cache.
Support --uncache with missing PVs.
Tidy report field names, headings and widths.
Add vgscan --notifydbus to send a dbus notification.
Add dbus notification from commands after a PV/VG/LV changes state.
Version 2.02.145 - 4th March 2016
=================================
Make it possible to use lvremove and lvrename on historical LVs.
For historical LVs, report 'none' for lv_layout and 'history' for lv_role.
Add full_{ancestors,descendants} fields to report LV ancestry with history.
Report (h)istorical state within 5th bit (State) of the lv_attr field.
Add lv_historical reporting field to report if LV is historical or not.
Add lv_time_removed reporting field to display removal time for hist. LVs.
Report lv_name, lv_uuid, vg_name, lv_time for historical LVs.
Add --nohistory switch to lvremove to disable history recording on demand.
Add -H|--history switch to lvs and lvdisplay to include historical LVs.
Create historical LVs out of removed thin snapshot LVs and record in history.
Add metadata/lvs_history_retention_time for automatic removal of hist. LVs.
Add metadata/record_lvs_history config for switching LV history recording.
Add support and infrastructure for tracking historical LVs.
Improve lvconvert man page.
Add kernel_cache_policy lvs field.
Display [unknown] instead of 'unknown device' in pvs output.
Fix error path when pvcreate allocation fails (2.02.144).
Display [unknown] instead of blank for unknown VG names in pvs output.
Version 2.02.144 - 26th February 2016
=====================================
Use new PV processing code in pvcreate/vgcreate/vgextend/pvremove.
Add new PV processing code that prompts user without locks held.
Prevent lvmlockd blocking with new flag requiring sanlock 3.3.0.
Only show (u)sed pv_attr char when PV is not (a)llocatable. (2.02.143)
Update makefile to generate lcov output also for lvmpolld and lvmlockd.
Fix SystemdService lvm2-lvmdbusd.service name.
Improve support for env LVM_VG_NAME for reference VG name in lvconvert.
Fix regression when lvresize accepted zero sizes. (2.02.141)
Always warn user about PV in use even when pvremove uses --force --force.
Use uninitialized pool header detection in all cases.
Fix read error detection when checking for uninitialized thin-pool header.
Fix error path for internal error in lvmetad VG lookup code.
Version 2.02.143 - 21st February 2016
=====================================
Fix error path when sending thin-pool message fails in update_pool_lv().
Support reporting CheckNeeded and Fail state for thin-pool and thin LV.
For failing thin-pool and thin volume correctly report percentage as INVALID.
Report -1, not 'unkown' for lv_{snapshot_invalid,merge_failed} with --binary.
Add configure --enable-dbus-service for an LVM D-Bus service.
Replace configure --enable-python_bindings with python2 and python3 versions.
If PV belongs to some VG and metadata missing, skip it if system ID is used.
Automatically change PV header extension to latest version if writing PV/VG.
Identify used PVs in pv_attr field by new 'u' character.
Add pv_in_use reporting field to report if PV is used or not.
Add pv_ext_vsn reporting field to report PV header extension version.
Add protective flag marking PVs as used even if no metadata available.
Version 2.02.142 - 15th February 2016
=====================================
Fix memory pool corruption in pvmove (2.02.141).
Support control of spare metadata creation when repairing thin-pool.
Fix config type of 'log/verbose' from bool to int (2.02.99).
Fix inverted data LV thinp watermark calc for dmeventd response (2.02.133).
Use use_blkid_wiping=0 if not defined in lvm.conf and support not compiled in.
Do not check for suspended devices if scanning for lvmetad update.
Clear cached bootloader areas when PV format changed.
Fix partn table filter with external_device_info_source="udev" and blkid<2.20.
Version 2.02.141 - 25th January 2016
====================================
Add metadata/check_pv_device_sizes switch to lvm.conf for device size checks.
Warn if device size is less than corresponding PV size in metadata.
Cache device sizes internally.
Restore support for command breaking in process_each_lv_in_vg() (2.02.118).
Use correct mempool when process_each_lv_in_vg() (2.02.118).
Fix lvm.8 man to show again prohibited suffixes.
Fix configure to set proper use_blkid_wiping if autodetected as disabled.
Initialise udev in clvmd for use in device scanning. (2.02.116)
Add seg_le_ranges report field for common format when displaying seg devices.
Honour report/list_item_separator for seg_metadata_le_ranges report field.
Don't mark hidden devs in -o devices,metadata_devices,seg_pe_ranges.(2.02.140)
Change LV sizes in seg_pe_ranges report field to match underlying devices.
Add kernel_cache_settings report field for cache LV settings used in kernel.
Version 2.02.140 - 16th January 2016
====================================
Fix lvm2app to return either 0 or 1 for lvm_vg_is_{clustered,exported}.
Add kernel_discards report field to display thin pool discard used in kernel.
Correct checking of target presence when driver access is disabled.
Eval poolmetadatasize arg earlier in lvresize.
Fix vgcfgrestore to respect allocatable attribute of PVs.
Add report/mark_hidden_devices to lvm.conf.
Use brackets consistently in report fields to mark hidden devices.
Restore background polling processing during auto-activation (2.02.119).
Fix invalid memory read when reporting cache LV policy_name (2.02.126).
Version 2.02.139 - 8th January 2016
===================================
Update lvmlockd with the new VG seqno before devices are suspended.
Rework vgrename to use the common processing code in toollib.
Make pvs show new devices on the system since the last .cache update.
Document F,D and M thin pool health status chars for lv_attr in lvs man page.
Also add lvm2-activation{-early,-net}.service systemd status for lvmdump -s.
Version 2.02.138 - 14th December 2015
=====================================
Support lvrename for hidden (used) cache pools.
Fix lvrename for stacked cache pools.
Version 2.02.137 - 5th December 2015
====================================
Restore archiving before changing metadata in vgextend (2.02.117).
Dropped internal usage of log_suppress(2).
Cleaned logging code for buffer size usage.
Added internal id_read_format_try() function to check and read valid UUID.
Change lvcreate, lvrename, lvresize to use process_each_vg.
Change process_each_vg to handle single VG as separate arg.
Issue error if ambiguous VG name is supplied in most commands.
Make process_each fns always work through full list of known VG names.
Use dm_get_status_mirror() instead of individual parsers.
Add mem pool arg for check_transient_status() target function.
Avoid misleading error with -m is omitted with lvconvert to raid types.
Add system_id to vginfo cache.
Version 2.02.136 - 28th November 2015
=====================================
Add new --sinceversion option for lvmconfig --type new.
Fix inactive table loaded for wrapping thin-pool when resizing it.
Extend the list of ignored libraries when locking memory.
Version 2.02.135 - 23rd November 2015
=====================================
Add a model file for Coverity.
Show correct error message for unsupported yet cache pool repair.
Allow lvconvert cache pools' data and metadata LV to raid.
Fix reading of old metadata with missing cache policy or mode settings.
Issue error if external_device_info_source=udev and udev db record incomplete.
Update lvmetad duplicate VG name handling to use hash function extensions.
Detect invalid vgrenames by vgid where the name is unchanged.
Fix passing of 32bit values through daemons (mostly lvmlockd).
Use local memory pool for whole alloc_handle manipulation.
Add missing pointer validation after dm_get_next_target().
Do not deref NULL pointer in debug message for _match_pv_tags().
Drop unneeded stat() call when checking for sysfs file.
Fix memory leak on error path of failing thin-pool percentage check.
Add missing test for failing node allocation in lvmetad.
Correct configure messages when enabling/disabling lvmlockd.
Version 2.02.134 - 9th November 2015
====================================
Refactor some lvmetad code and adjust some duplicate PV messages.
No longer repair/wipe VG/PVs if inaccessible because foreign or shared.
Pass correct data size to mirror log calc so log can be bigger than 1 extent.
Version 2.02.133 - 30th October 2015
====================================

View File

@ -1,5 +1,213 @@
Version 1.02.111 -
Version 1.02.141 - 28th June 2017
=================================
Fix reusing of dm_task structure for status reading (used by dmeventd).
Add dm_percent_to_round_float for adjusted percentage rounding.
Reset array with dead rimage devices once raid gets in sync.
Drop unneeded --config option from raid dmeventd plugin.
dm_get_status_raid() handle better some incosistent md statuses.
Accept truncated files in calls to dm_stats_update_regions_from_fd().
Restore Warning by 5% increment when thin-pool is over 80% (1.02.138).
Version 1.02.140 - 3rd May 2017
===============================
Add missing configure --enable-dmfilemapd status message and fix --disable.
Version 1.02.139 - 13th April 2017
==================================
Fix assignment in _target_version() when dm task can't run.
Flush stdout on each iteration when using --count or --interval.
Show detailed error message when execvp fails while starting dmfilemapd.
Fix segmentation fault when dmfilemapd is run with no arguments.
Numerous minor dmfilemapd fixes from coverity.
Version 1.02.138 - 28th March 2017
==================================
Support additional raid5/6 configurations.
Provide dm_tree_node_add_cache_target@base compatible symbol.
Support DM_CACHE_FEATURE_METADATA2, new cache metadata format 2.
Improve code to handle mode mask for cache nodes.
Cache status check for passthrough also require trailing space.
Add extra memory page when limiting pthread stack size in dmeventd.
Avoids immediate resume when preloaded device is smaller.
Do not suppress kernel key description in dmsetup table output for dm-crypt.
Support configurable command executed from dmeventd thin plugin.
Support new R|r human readable units output format.
Thin dmeventd plugin reacts faster on lvextend failure path with umount.
Add dm_stats_bind_from_fd() to bind a stats handle from a file descriptor.
Do not try call callback when reverting activation on error path.
Fix file mapping for extents with physically adjacent extents in dmstats.
Validation vsnprintf result in runtime translate of dm_log (1.02.136).
Separate filemap extent allocation from region table in dmstats.
Fix segmentation fault when filemap region creation fails in dmstats.
Fix performance of region cleanup for failed filemap creation in dmstats.
Fix very slow region deletion with many regions in dmstats.
Version 1.02.137 - 30th November 2016
=====================================
Document raid status values.
Always exit dmsetup with success when asked to display help/version.
Version 1.02.136 - 5th November 2016
====================================
Log failure of raid device with log_error level.
Use dm_log_with_errno and translate runtime to dm_log only when needed.
Make log messages from dm and lvm library different from dmeventd.
Notice and Info messages are again logged from dmeventd and its plugins.
Dmeventd now also respects DM_ABORT_ON_INTERNAL_ERRORS as libdm based tool.
Report as non default dm logging also when logging with errno was changed.
Use log_level() macro to consistently decode message log level in dmeventd.
Still produce output when dmsetup dependency tree building finds dev missing.
Check and report pthread_sigmask() failure in dmeventd.
Check mem alloc fail in _canonicalize_field_ids().
Use unsigned math when checking more then 31 legs of raid.
Fix 'dmstats delete' with dmsetup older than v1.02.129
Fix stats walk segfault with dmsetup older than v1.02.129
Version 1.02.135 - 26th September 2016
======================================
Fix man entry for dmsetup status.
Introduce new dm_config_parse_without_dup_node_check().
Don't omit last entry in dmstats list --group.
Version 1.02.134 - 7th September 2016
=====================================
Improve explanation of udev fallback in libdevmapper.h.
Version 1.02.133 - 10th August 2016
===================================
Add dm_report_destroy_rows/dm_report_group_output_and_pop_all for lvm shell.
Adjust group handling and json production for lvm shell.
Version 1.02.132 - 28th July 2016
=================================
Fix json reporting to escape '"' character that may appear in reported string.
Version 1.02.131 - 15th July 2016
=================================
Disable queueing on mpath devs in blk-availability systemd service/initscript.
Add new -m|--mpathoption disablequeueing to blkdeactivate.
Automatically group regions with 'create --segments' unless --nogroup.
Fix resource leak when deleting the first member of a group.
Allow --bounds with 'create --filemap' for dmstats.
Enable creation of filemap regions with histograms.
Enable histogram aggregation for regions with more than one area.
Enable histogram aggregation for groups of regions.
Add a --filemap option to 'dmstats create' to allow mapping of files.
Add dm_stats_create_regions_from_fd() to map file extents to regions.
Version 1.02.130 - 6th July 2016
================================
Minor fixes from coverity.
Version 1.02.129 - 6th July 2016
================================
Update default dmstats field selections for groups.
Add 'obj_type', 'group_id', and 'statsname' fields to dmstats reports.
Add --area, --region, and --group to dmstats to control object selection.
Add --alias, --groupid, --regions to dmstats for group creation and deletion.
Add 'group' and 'ungroup' commands to dmstats.
Allow dm_stats_delete_group() to optionally delete all group members.
Add dm_stats_get_object_type() to return the type of object present.
Add dm_stats_walk_init() allowing control of objects visited by walks.
Add dm_stats_get_group_descriptor() to return the member list as a string.
Introduce dm_stats_get_nr_groups() and dm_stats_group_present().
Add dm_stats_{get,set}_alias() to set and retrieve alias names for groups.
Add dm_stats_get_group_id() to return the group ID for a given region.
Add dm_stats_{create,delete}_group() to allow grouping of stats regions.
Add enum-driven dm_stats_get_{metric,counter}() interfaces.
Add dm_bitset_parse_list() to parse a string representation of a bitset.
Thin dmeventd plugin umounts lvm2 volume only when pool is 95% or more.
Version 1.02.128 - 25th June 2016
=================================
Recognize 'all' keyword used in selection as synonym for "" (no selection).
Add dm_report_set_selection to set selection for multiple output of report.
Add DM_REPORT_OUTPUT_MULTIPLE_TIMES flag for multiple output of same report.
Move field width handling/sort init from dm_report_object to dm_report_output.
Add _LOG_BYPASS_REPORT flag for bypassing any log report currently set.
Introduce DM_REPORT_GROUP_JSON for report group with JSON output format.
Introduce DM_REPORT_GROUP_BASIC for report group with basic report output.
Introduce DM_REPORT_GROUP_SINGLE for report group having single report only.
Add dm_report_group_{create,push,pop,destroy} to support report grouping.
Version 1.02.127 - 11th June 2016
=================================
Fix blkdeactivate regression causing skipping of dm + md devices. (1.02.126)
Version 1.02.126 - 3rd June 2016
================================
Report passthrough caching mode when parsing cache mode.
Version 1.02.125 - 14th May 2016
================================
Show library version in message even if dm driver version is unavailable.
Version 1.02.124 - 30th April 2016
==================================
Add dm_udev_wait_immediate to libdevmapper for waiting outside the library.
Version 1.02.123 - 23rd April 2016
==================================
Do not strip LVM- when debug reporting not found uuid.
Version 1.02.122 - 9th April 2016
=================================
Change log_debug ioctl flags from single characters into words.
Version 1.02.121 - 26th March 2016
==================================
Adjust raid status function.
Version 1.02.120 - 11th March 2016
==================================
Improve parsing of cache status and report Fail, Error, needs_check, ro.
Version 1.02.119 - 4th March 2016
=================================
Fix dm_config_write_node and variants to return error on subsection failures.
Remove 4096 char limit due to buffer size if writing dm_config_node.
Version 1.02.118 - 26th February 2016
=====================================
Fix string boundary check in _get_canonical_field_name().
Always initialized hist struct in _stats_parse_histogram().
Version 1.02.117 - 21st February 2016
=====================================
Improve status parsing for thin-pool and thin devices.
Version 1.02.116 - 15th February 2016
=====================================
Use fully aligned allocations for dm_pool_strdup/strndup() (1.02.64).
Fix thin-pool table parameter feature order to match kernel output.
Version 1.02.115 - 25th January 2016
====================================
Fix man page for dmsetup udevcreatecookie.
Version 1.02.114 - 14th December 2015
=====================================
Better support for dmsetup static linkage.
Extend validity checks on dmeventd client socket.
Version 1.02.113 - 5th December 2015
====================================
Mirror plugin in dmeventd uses dm_get_status_mirror().
Add dm_get_status_mirror() for parsing mirror status line.
Version 1.02.112 - 28th November 2015
=====================================
Show error message when trying to create unsupported raid type.
Improve preloading sequence of an active thin-pool target.
Drop extra space from cache target line to fix unneded table reloads.
Version 1.02.111 - 23rd November 2015
=====================================
Extend dm_hash to support multiple values with the same key.
Add missing check for allocation inside dm_split_lvm_name().
Test dm_task_get_message_response for !NULL in dm_stats_print_region().
Add checks for failing dm_stats_create() in dmsetup.
Add missing fifo close when failed to initialize client connection.
Version 1.02.110 - 30th October 2015
====================================
@ -29,7 +237,7 @@ Version 1.02.110 - 30th October 2015
Correct use of max_write_behind parameter when generating raid target line.
Fix dm-event systemd service to make sure it is executed before mounting.
Version 1.02.109 - 22nd September 2016
Version 1.02.109 - 22nd September 2015
======================================
Update man pages for dmsetup and dmstats.
Improve help text for dmsetup.

View File

@ -61,3 +61,174 @@ AC_DEFUN([AC_TRY_LDFLAGS],
ifelse([$4], [], [:], [$4])
fi
])
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_gcc_builtin.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_GCC_BUILTIN(BUILTIN)
#
# DESCRIPTION
#
# This macro checks if the compiler supports one of GCC's built-in
# functions; many other compilers also provide those same built-ins.
#
# The BUILTIN parameter is the name of the built-in function.
#
# If BUILTIN is supported define HAVE_<BUILTIN>. Keep in mind that since
# builtins usually start with two underscores they will be copied over
# into the HAVE_<BUILTIN> definition (e.g. HAVE___BUILTIN_EXPECT for
# __builtin_expect()).
#
# The macro caches its result in the ax_cv_have_<BUILTIN> variable (e.g.
# ax_cv_have___builtin_expect).
#
# The macro currently supports the following built-in functions:
#
# __builtin_assume_aligned
# __builtin_bswap16
# __builtin_bswap32
# __builtin_bswap64
# __builtin_choose_expr
# __builtin___clear_cache
# __builtin_clrsb
# __builtin_clrsbl
# __builtin_clrsbll
# __builtin_clz
# __builtin_clzl
# __builtin_clzll
# __builtin_complex
# __builtin_constant_p
# __builtin_ctz
# __builtin_ctzl
# __builtin_ctzll
# __builtin_expect
# __builtin_ffs
# __builtin_ffsl
# __builtin_ffsll
# __builtin_fpclassify
# __builtin_huge_val
# __builtin_huge_valf
# __builtin_huge_vall
# __builtin_inf
# __builtin_infd128
# __builtin_infd32
# __builtin_infd64
# __builtin_inff
# __builtin_infl
# __builtin_isinf_sign
# __builtin_nan
# __builtin_nand128
# __builtin_nand32
# __builtin_nand64
# __builtin_nanf
# __builtin_nanl
# __builtin_nans
# __builtin_nansf
# __builtin_nansl
# __builtin_object_size
# __builtin_parity
# __builtin_parityl
# __builtin_parityll
# __builtin_popcount
# __builtin_popcountl
# __builtin_popcountll
# __builtin_powi
# __builtin_powif
# __builtin_powil
# __builtin_prefetch
# __builtin_trap
# __builtin_types_compatible_p
# __builtin_unreachable
#
# Unsuppored built-ins will be tested with an empty parameter set and the
# result of the check might be wrong or meaningless so use with care.
#
# LICENSE
#
# Copyright (c) 2013 Gabriele Svelto <gabriele.svelto@gmail.com>
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 3
AC_DEFUN([AX_GCC_BUILTIN], [
AS_VAR_PUSHDEF([ac_var], [ax_cv_have_$1])
AC_CACHE_CHECK([for $1], [ac_var], [
AC_LINK_IFELSE([AC_LANG_PROGRAM([], [
m4_case([$1],
[__builtin_assume_aligned], [$1("", 0)],
[__builtin_bswap16], [$1(0)],
[__builtin_bswap32], [$1(0)],
[__builtin_bswap64], [$1(0)],
[__builtin_choose_expr], [$1(0, 0, 0)],
[__builtin___clear_cache], [$1("", "")],
[__builtin_clrsb], [$1(0)],
[__builtin_clrsbl], [$1(0)],
[__builtin_clrsbll], [$1(0)],
[__builtin_clz], [$1(0)],
[__builtin_clzl], [$1(0)],
[__builtin_clzll], [$1(0)],
[__builtin_complex], [$1(0.0, 0.0)],
[__builtin_constant_p], [$1(0)],
[__builtin_ctz], [$1(0)],
[__builtin_ctzl], [$1(0)],
[__builtin_ctzll], [$1(0)],
[__builtin_expect], [$1(0, 0)],
[__builtin_ffs], [$1(0)],
[__builtin_ffsl], [$1(0)],
[__builtin_ffsll], [$1(0)],
[__builtin_fpclassify], [$1(0, 1, 2, 3, 4, 0.0)],
[__builtin_huge_val], [$1()],
[__builtin_huge_valf], [$1()],
[__builtin_huge_vall], [$1()],
[__builtin_inf], [$1()],
[__builtin_infd128], [$1()],
[__builtin_infd32], [$1()],
[__builtin_infd64], [$1()],
[__builtin_inff], [$1()],
[__builtin_infl], [$1()],
[__builtin_isinf_sign], [$1(0.0)],
[__builtin_nan], [$1("")],
[__builtin_nand128], [$1("")],
[__builtin_nand32], [$1("")],
[__builtin_nand64], [$1("")],
[__builtin_nanf], [$1("")],
[__builtin_nanl], [$1("")],
[__builtin_nans], [$1("")],
[__builtin_nansf], [$1("")],
[__builtin_nansl], [$1("")],
[__builtin_object_size], [$1("", 0)],
[__builtin_parity], [$1(0)],
[__builtin_parityl], [$1(0)],
[__builtin_parityll], [$1(0)],
[__builtin_popcount], [$1(0)],
[__builtin_popcountl], [$1(0)],
[__builtin_popcountll], [$1(0)],
[__builtin_powi], [$1(0, 0)],
[__builtin_powif], [$1(0, 0)],
[__builtin_powil], [$1(0, 0)],
[__builtin_prefetch], [$1("")],
[__builtin_trap], [$1()],
[__builtin_types_compatible_p], [$1(int, int)],
[__builtin_unreachable], [$1()],
[m4_warn([syntax], [Unsupported built-in $1, the test may fail])
$1()]
)
])],
[AS_VAR_SET([ac_var], [yes])],
[AS_VAR_SET([ac_var], [no])])
])
AS_IF([test yes = AS_VAR_GET([ac_var])],
[AC_DEFINE_UNQUOTED(AS_TR_CPP(HAVE_$1), 1,
[Define to 1 if the system has the `$1' built-in function])], [])
AS_VAR_POPDEF([ac_var])
])

312
aclocal.m4 vendored
View File

@ -12,10 +12,67 @@
# PARTICULAR PURPOSE.
m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])])
# ===========================================================================
# http://www.gnu.org/software/autoconf-archive/ax_python_module.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PYTHON_MODULE(modname[, fatal, python])
#
# DESCRIPTION
#
# Checks for Python module.
#
# If fatal is non-empty then absence of a module will trigger an error.
# The third parameter can either be "python" for Python 2 or "python3" for
# Python 3; defaults to Python 3.
#
# LICENSE
#
# Copyright (c) 2008 Andrew Collier
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 8
AU_ALIAS([AC_PYTHON_MODULE], [AX_PYTHON_MODULE])
AC_DEFUN([AX_PYTHON_MODULE],[
if test -z $PYTHON;
then
if test -z "$3";
then
PYTHON="python3"
else
PYTHON="$3"
fi
fi
PYTHON_NAME=`basename $PYTHON`
AC_MSG_CHECKING($PYTHON_NAME module: $1)
$PYTHON -c "import $1" 2>/dev/null
if test $? -eq 0;
then
AC_MSG_RESULT(yes)
eval AS_TR_CPP(HAVE_PYMOD_$1)=yes
else
AC_MSG_RESULT(no)
eval AS_TR_CPP(HAVE_PYMOD_$1)=no
#
if test -n "$2"
then
AC_MSG_ERROR(failed to find required module $1)
exit 1
fi
fi
])
# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*-
# serial 1 (pkg-config-0.24)
#
# Copyright (c) 2004 Scott James Remnant <scott@netsplit.com>.
# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@ -227,4 +284,257 @@ AS_VAR_COPY([$1], [pkg_cv_][$1])
AS_VAR_IF([$1], [""], [$5], [$4])dnl
])# PKG_CHECK_VAR
# Copyright (C) 1999-2014 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_PATH_PYTHON([MINIMUM-VERSION], [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
# ---------------------------------------------------------------------------
# Adds support for distributing Python modules and packages. To
# install modules, copy them to $(pythondir), using the python_PYTHON
# automake variable. To install a package with the same name as the
# automake package, install to $(pkgpythondir), or use the
# pkgpython_PYTHON automake variable.
#
# The variables $(pyexecdir) and $(pkgpyexecdir) are provided as
# locations to install python extension modules (shared libraries).
# Another macro is required to find the appropriate flags to compile
# extension modules.
#
# If your package is configured with a different prefix to python,
# users will have to add the install directory to the PYTHONPATH
# environment variable, or create a .pth file (see the python
# documentation for details).
#
# If the MINIMUM-VERSION argument is passed, AM_PATH_PYTHON will
# cause an error if the version of python installed on the system
# doesn't meet the requirement. MINIMUM-VERSION should consist of
# numbers and dots only.
AC_DEFUN([AM_PATH_PYTHON],
[
dnl Find a Python interpreter. Python versions prior to 2.0 are not
dnl supported. (2.0 was released on October 16, 2000).
m4_define_default([_AM_PYTHON_INTERPRETER_LIST],
[python python2 python3 python3.3 python3.2 python3.1 python3.0 python2.7 dnl
python2.6 python2.5 python2.4 python2.3 python2.2 python2.1 python2.0])
AC_ARG_VAR([PYTHON], [the Python interpreter])
m4_if([$1],[],[
dnl No version check is needed.
# Find any Python interpreter.
if test -z "$PYTHON"; then
AC_PATH_PROGS([PYTHON], _AM_PYTHON_INTERPRETER_LIST, :)
fi
am_display_PYTHON=python
], [
dnl A version check is needed.
if test -n "$PYTHON"; then
# If the user set $PYTHON, use it and don't search something else.
AC_MSG_CHECKING([whether $PYTHON version is >= $1])
AM_PYTHON_CHECK_VERSION([$PYTHON], [$1],
[AC_MSG_RESULT([yes])],
[AC_MSG_RESULT([no])
AC_MSG_ERROR([Python interpreter is too old])])
am_display_PYTHON=$PYTHON
else
# Otherwise, try each interpreter until we find one that satisfies
# VERSION.
AC_CACHE_CHECK([for a Python interpreter with version >= $1],
[am_cv_pathless_PYTHON],[
for am_cv_pathless_PYTHON in _AM_PYTHON_INTERPRETER_LIST none; do
test "$am_cv_pathless_PYTHON" = none && break
AM_PYTHON_CHECK_VERSION([$am_cv_pathless_PYTHON], [$1], [break])
done])
# Set $PYTHON to the absolute path of $am_cv_pathless_PYTHON.
if test "$am_cv_pathless_PYTHON" = none; then
PYTHON=:
else
AC_PATH_PROG([PYTHON], [$am_cv_pathless_PYTHON])
fi
am_display_PYTHON=$am_cv_pathless_PYTHON
fi
])
if test "$PYTHON" = :; then
dnl Run any user-specified action, or abort.
m4_default([$3], [AC_MSG_ERROR([no suitable Python interpreter found])])
else
dnl Query Python for its version number. Getting [:3] seems to be
dnl the best way to do this; it's what "site.py" does in the standard
dnl library.
AC_CACHE_CHECK([for $am_display_PYTHON version], [am_cv_python_version],
[am_cv_python_version=`$PYTHON -c "import sys; sys.stdout.write(sys.version[[:3]])"`])
AC_SUBST([PYTHON_VERSION], [$am_cv_python_version])
dnl Use the values of $prefix and $exec_prefix for the corresponding
dnl values of PYTHON_PREFIX and PYTHON_EXEC_PREFIX. These are made
dnl distinct variables so they can be overridden if need be. However,
dnl general consensus is that you shouldn't need this ability.
AC_SUBST([PYTHON_PREFIX], ['${prefix}'])
AC_SUBST([PYTHON_EXEC_PREFIX], ['${exec_prefix}'])
dnl At times (like when building shared libraries) you may want
dnl to know which OS platform Python thinks this is.
AC_CACHE_CHECK([for $am_display_PYTHON platform], [am_cv_python_platform],
[am_cv_python_platform=`$PYTHON -c "import sys; sys.stdout.write(sys.platform)"`])
AC_SUBST([PYTHON_PLATFORM], [$am_cv_python_platform])
# Just factor out some code duplication.
am_python_setup_sysconfig="\
import sys
# Prefer sysconfig over distutils.sysconfig, for better compatibility
# with python 3.x. See automake bug#10227.
try:
import sysconfig
except ImportError:
can_use_sysconfig = 0
else:
can_use_sysconfig = 1
# Can't use sysconfig in CPython 2.7, since it's broken in virtualenvs:
# <https://github.com/pypa/virtualenv/issues/118>
try:
from platform import python_implementation
if python_implementation() == 'CPython' and sys.version[[:3]] == '2.7':
can_use_sysconfig = 0
except ImportError:
pass"
dnl Set up 4 directories:
dnl pythondir -- where to install python scripts. This is the
dnl site-packages directory, not the python standard library
dnl directory like in previous automake betas. This behavior
dnl is more consistent with lispdir.m4 for example.
dnl Query distutils for this directory.
AC_CACHE_CHECK([for $am_display_PYTHON script directory],
[am_cv_python_pythondir],
[if test "x$prefix" = xNONE
then
am_py_prefix=$ac_default_prefix
else
am_py_prefix=$prefix
fi
am_cv_python_pythondir=`$PYTHON -c "
$am_python_setup_sysconfig
if can_use_sysconfig:
sitedir = sysconfig.get_path('purelib', vars={'base':'$am_py_prefix'})
else:
from distutils import sysconfig
sitedir = sysconfig.get_python_lib(0, 0, prefix='$am_py_prefix')
sys.stdout.write(sitedir)"`
case $am_cv_python_pythondir in
$am_py_prefix*)
am__strip_prefix=`echo "$am_py_prefix" | sed 's|.|.|g'`
am_cv_python_pythondir=`echo "$am_cv_python_pythondir" | sed "s,^$am__strip_prefix,$PYTHON_PREFIX,"`
;;
*)
case $am_py_prefix in
/usr|/System*) ;;
*)
am_cv_python_pythondir=$PYTHON_PREFIX/lib/python$PYTHON_VERSION/site-packages
;;
esac
;;
esac
])
AC_SUBST([pythondir], [$am_cv_python_pythondir])
dnl pkgpythondir -- $PACKAGE directory under pythondir. Was
dnl PYTHON_SITE_PACKAGE in previous betas, but this naming is
dnl more consistent with the rest of automake.
AC_SUBST([pkgpythondir], [\${pythondir}/$PACKAGE])
dnl pyexecdir -- directory for installing python extension modules
dnl (shared libraries)
dnl Query distutils for this directory.
AC_CACHE_CHECK([for $am_display_PYTHON extension module directory],
[am_cv_python_pyexecdir],
[if test "x$exec_prefix" = xNONE
then
am_py_exec_prefix=$am_py_prefix
else
am_py_exec_prefix=$exec_prefix
fi
am_cv_python_pyexecdir=`$PYTHON -c "
$am_python_setup_sysconfig
if can_use_sysconfig:
sitedir = sysconfig.get_path('platlib', vars={'platbase':'$am_py_prefix'})
else:
from distutils import sysconfig
sitedir = sysconfig.get_python_lib(1, 0, prefix='$am_py_prefix')
sys.stdout.write(sitedir)"`
case $am_cv_python_pyexecdir in
$am_py_exec_prefix*)
am__strip_prefix=`echo "$am_py_exec_prefix" | sed 's|.|.|g'`
am_cv_python_pyexecdir=`echo "$am_cv_python_pyexecdir" | sed "s,^$am__strip_prefix,$PYTHON_EXEC_PREFIX,"`
;;
*)
case $am_py_exec_prefix in
/usr|/System*) ;;
*)
am_cv_python_pyexecdir=$PYTHON_EXEC_PREFIX/lib/python$PYTHON_VERSION/site-packages
;;
esac
;;
esac
])
AC_SUBST([pyexecdir], [$am_cv_python_pyexecdir])
dnl pkgpyexecdir -- $(pyexecdir)/$(PACKAGE)
AC_SUBST([pkgpyexecdir], [\${pyexecdir}/$PACKAGE])
dnl Run any user-specified action.
$2
fi
])
# AM_PYTHON_CHECK_VERSION(PROG, VERSION, [ACTION-IF-TRUE], [ACTION-IF-FALSE])
# ---------------------------------------------------------------------------
# Run ACTION-IF-TRUE if the Python interpreter PROG has version >= VERSION.
# Run ACTION-IF-FALSE otherwise.
# This test uses sys.hexversion instead of the string equivalent (first
# word of sys.version), in order to cope with versions such as 2.2c1.
# This supports Python 2.0 or higher. (2.0 was released on October 16, 2000).
AC_DEFUN([AM_PYTHON_CHECK_VERSION],
[prog="import sys
# split strings by '.' and convert to numeric. Append some zeros
# because we need at least 4 digits for the hex conversion.
# map returns an iterator in Python 3.0 and a list in 2.x
minver = list(map(int, '$2'.split('.'))) + [[0, 0, 0]]
minverhex = 0
# xrange is not present in Python 3.0 and range returns an iterator
for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[[i]]
sys.exit(sys.hexversion < minverhex)"
AS_IF([AM_RUN_LOG([$1 -c "$prog"])], [$3], [$4])])
# Copyright (C) 2001-2014 Free Software Foundation, Inc.
#
# This file is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# AM_RUN_LOG(COMMAND)
# -------------------
# Run COMMAND, save the exit status in ac_status, and log it.
# (This has been adapted from Autoconf's _AC_RUN_LOG macro.)
AC_DEFUN([AM_RUN_LOG],
[{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD
($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD
ac_status=$?
echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD
(exit $ac_status); }])
m4_include([acinclude.m4])

170
autoconf/py-compile Executable file
View File

@ -0,0 +1,170 @@
#!/bin/sh
# py-compile - Compile a Python program
scriptversion=2011-06-08.12; # UTC
# Copyright (C) 2000-2014 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.
# This file is maintained in Automake, please report
# bugs to <bug-automake@gnu.org> or send patches to
# <automake-patches@gnu.org>.
if [ -z "$PYTHON" ]; then
PYTHON=python
fi
me=py-compile
usage_error ()
{
echo "$me: $*" >&2
echo "Try '$me --help' for more information." >&2
exit 1
}
basedir=
destdir=
while test $# -ne 0; do
case "$1" in
--basedir)
if test $# -lt 2; then
usage_error "option '--basedir' requires an argument"
else
basedir=$2
fi
shift
;;
--destdir)
if test $# -lt 2; then
usage_error "option '--destdir' requires an argument"
else
destdir=$2
fi
shift
;;
-h|--help)
cat <<\EOF
Usage: py-compile [--help] [--version] [--basedir DIR] [--destdir DIR] FILES..."
Byte compile some python scripts FILES. Use --destdir to specify any
leading directory path to the FILES that you don't want to include in the
byte compiled file. Specify --basedir for any additional path information you
do want to be shown in the byte compiled file.
Example:
py-compile --destdir /tmp/pkg-root --basedir /usr/share/test test.py test2.py
Report bugs to <bug-automake@gnu.org>.
EOF
exit $?
;;
-v|--version)
echo "$me $scriptversion"
exit $?
;;
--)
shift
break
;;
-*)
usage_error "unrecognized option '$1'"
;;
*)
break
;;
esac
shift
done
files=$*
if test -z "$files"; then
usage_error "no files given"
fi
# if basedir was given, then it should be prepended to filenames before
# byte compilation.
if [ -z "$basedir" ]; then
pathtrans="path = file"
else
pathtrans="path = os.path.join('$basedir', file)"
fi
# if destdir was given, then it needs to be prepended to the filename to
# byte compile but not go into the compiled file.
if [ -z "$destdir" ]; then
filetrans="filepath = path"
else
filetrans="filepath = os.path.normpath('$destdir' + os.sep + path)"
fi
$PYTHON -c "
import sys, os, py_compile, imp
files = '''$files'''
sys.stdout.write('Byte-compiling python modules...\n')
for file in files.split():
$pathtrans
$filetrans
if not os.path.exists(filepath) or not (len(filepath) >= 3
and filepath[-3:] == '.py'):
continue
sys.stdout.write(file)
sys.stdout.flush()
if hasattr(imp, 'get_tag'):
py_compile.compile(filepath, imp.cache_from_source(filepath), path)
else:
py_compile.compile(filepath, filepath + 'c', path)
sys.stdout.write('\n')" || exit $?
# this will fail for python < 1.5, but that doesn't matter ...
$PYTHON -O -c "
import sys, os, py_compile, imp
# pypy does not use .pyo optimization
if hasattr(sys, 'pypy_translation_info'):
sys.exit(0)
files = '''$files'''
sys.stdout.write('Byte-compiling python modules (optimized versions) ...\n')
for file in files.split():
$pathtrans
$filetrans
if not os.path.exists(filepath) or not (len(filepath) >= 3
and filepath[-3:] == '.py'):
continue
sys.stdout.write(file)
sys.stdout.flush()
if hasattr(imp, 'get_tag'):
py_compile.compile(filepath, imp.cache_from_source(filepath, False), path)
else:
py_compile.compile(filepath, filepath + 'o', path)
sys.stdout.write('\n')" 2>/dev/null || :
# Local Variables:
# mode: shell-script
# sh-indentation: 2
# eval: (add-hook 'write-file-hooks 'time-stamp)
# time-stamp-start: "scriptversion="
# time-stamp-format: "%:y-%02m-%02d.%02H"
# time-stamp-time-zone: "UTC"
# time-stamp-end: "; # UTC"
# End:

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@
@ -24,7 +24,8 @@ PROFILES=$(PROFILE_TEMPLATES) \
$(srcdir)/cache-mq.profile \
$(srcdir)/cache-smq.profile \
$(srcdir)/thin-generic.profile \
$(srcdir)/thin-performance.profile
$(srcdir)/thin-performance.profile \
$(srcdir)/lvmdbusd.profile
include $(top_builddir)/make.tmpl
@ -47,8 +48,8 @@ install_localconf: $(CONFLOCAL)
fi
install_profiles: $(PROFILES)
$(INSTALL_DIR) $(DESTDIR)$(DEFAULT_PROFILE_DIR)
$(INSTALL_DATA) $(PROFILES) $(DESTDIR)$(DEFAULT_PROFILE_DIR)/
$(INSTALL_DIR) $(profiledir)
$(INSTALL_DATA) $(PROFILES) $(profiledir)/
install_lvm2: install_conf install_localconf install_profiles

View File

@ -9,6 +9,6 @@ allocation {
cache_mode = "writethrough"
cache_policy = "smq"
cache_settings {
# currently no settins for "smq" policy
# currently no settings for "smq" policy
}
}

View File

@ -11,6 +11,17 @@
# Refer to 'man lvm.conf' for further information about profiles and
# general configuration file layout.
#
allocation {
cache_mode="writethrough"
cache_settings {
}
}
log {
report_command_log=0
command_log_sort="log_seq_num"
command_log_cols="log_seq_num,log_type,log_context,log_object_type,log_object_name,log_object_id,log_object_group,log_object_group_id,log_message,log_errno,log_ret_code"
command_log_selection="!(log_type=status && message=success)"
}
global {
units="h"
si_unit_consistency=1
@ -18,7 +29,9 @@ global {
lvdisplay_shows_full_device_path=0
}
report {
output_format="basic"
compact_output=0
compact_output_cols=""
aligned=1
buffered=1
headings=1
@ -26,8 +39,9 @@ report {
list_item_separator=","
prefixes=0
quoted=1
colums_as_rows=0
columns_as_rows=0
binary_values_as_numeric=0
time_format="%Y-%m-%d %T %z"
devtypes_sort="devtype_name"
devtypes_cols="devtype_name,devtype_max_partitions,devtype_description"
devtypes_cols_verbose="devtype_name,devtype_max_partitions,devtype_description"
@ -46,4 +60,15 @@ report {
pvsegs_sort="pv_name,pvseg_start"
pvsegs_cols="pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,pvseg_start,pvseg_size"
pvsegs_cols_verbose="pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,pvseg_start,pvseg_size,lv_name,seg_start_pe,segtype,seg_pe_ranges"
vgs_cols_full="vg_all"
pvs_cols_full="pv_all"
lvs_cols_full="lv_all"
pvsegs_cols_full="pvseg_all,pv_uuid,lv_uuid"
segs_cols_full="seg_all,lv_uuid"
vgs_sort_full="vg_name"
pvs_sort_full="pv_name"
lvs_sort_full="vg_name,lv_name"
pvsegs_sort_full="pv_uuid,pvseg_start"
segs_sort_full="lv_uuid,seg_start"
mark_hidden_devices=1
}

View File

@ -299,6 +299,19 @@ devices {
# generally do. If enabled, discards will only be issued if both the
# storage and kernel provide support.
issue_discards = 0
# Configuration option devices/allow_changes_with_duplicate_pvs.
# Allow VG modification while a PV appears on multiple devices.
# When a PV appears on multiple devices, LVM attempts to choose the
# best device to use for the PV. If the devices represent the same
# underlying storage, the choice has minimal consequence. If the
# devices represent different underlying storage, the wrong choice
# can result in data loss if the VG is modified. Disabling this
# setting is the safest option because it prevents modifying a VG
# or activating LVs in it while a PV appears on multiple devices.
# Enabling this setting allows the VG to be used as usual even with
# uncertain devices.
allow_changes_with_duplicate_pvs = 0
}
# Configuration section allocation.
@ -364,10 +377,30 @@ allocation {
# The default setting changed in version 2.02.85.
mirror_logs_require_separate_pvs = 0
# Configuration option allocation/raid_stripe_all_devices.
# Stripe across all PVs when RAID stripes are not specified.
# If enabled, all PVs in the VG or on the command line are used for
# raid0/4/5/6/10 when the command does not specify the number of
# stripes to use.
# This was the default behaviour until release 2.02.162.
# This configuration option has an automatic default value.
# raid_stripe_all_devices = 0
# Configuration option allocation/cache_pool_metadata_require_separate_pvs.
# Cache pool metadata and data will always use different PVs.
cache_pool_metadata_require_separate_pvs = 0
# Configuration option allocation/cache_metadata_format.
# Sets default metadata format for new cache.
#
# Accepted values:
# 0 Automatically detected best available format
# 1 Original format
# 2 Improved 2nd. generation format
#
# This configuration option has an automatic default value.
# cache_metadata_format = 0
# Configuration option allocation/cache_mode.
# The default cache mode used for new cache.
#
@ -384,7 +417,7 @@ allocation {
# Configuration option allocation/cache_policy.
# The default cache policy used for new cache volume.
# Since kernel 4.2 the default policy is smq (Stochastic multique),
# Since kernel 4.2 the default policy is smq (Stochastic multiqueue),
# otherwise the older mq (Multiqueue) policy is selected.
# This configuration option does not have a default value defined.
@ -407,6 +440,12 @@ allocation {
# 32KiB to 1GiB in multiples of 32.
# This configuration option does not have a default value defined.
# Configuration option allocation/cache_pool_max_chunks.
# The maximum number of chunks in a cache pool.
# For cache target v1.9 the recommended maximumm is 1000000 chunks.
# Using cache pool with more chunks may degrade cache performance.
# This configuration option does not have a default value defined.
# Configuration option allocation/thin_pool_metadata_require_separate_pvs.
# Thin pool metdata and data will always use different PVs.
thin_pool_metadata_require_separate_pvs = 0
@ -465,6 +504,55 @@ allocation {
# How LVM log information is reported.
log {
# Configuration option log/report_command_log.
# Enable or disable LVM log reporting.
# If enabled, LVM will collect a log of operations, messages,
# per-object return codes with object identification and associated
# error numbers (errnos) during LVM command processing. Then the
# log is either reported solely or in addition to any existing
# reports, depending on LVM command used. If it is a reporting command
# (e.g. pvs, vgs, lvs, lvm fullreport), then the log is reported in
# addition to any existing reports. Otherwise, there's only log report
# on output. For all applicable LVM commands, you can request that
# the output has only log report by using --logonly command line
# option. Use log/command_log_cols and log/command_log_sort settings
# to define fields to display and sort fields for the log report.
# You can also use log/command_log_selection to define selection
# criteria used each time the log is reported.
# This configuration option has an automatic default value.
# report_command_log = 0
# Configuration option log/command_log_sort.
# List of columns to sort by when reporting command log.
# See <lvm command> --logonly --configreport log -o help
# for the list of possible fields.
# This configuration option has an automatic default value.
# command_log_sort = "log_seq_num"
# Configuration option log/command_log_cols.
# List of columns to report when reporting command log.
# See <lvm command> --logonly --configreport log -o help
# for the list of possible fields.
# This configuration option has an automatic default value.
# command_log_cols = "log_seq_num,log_type,log_context,log_object_type,log_object_name,log_object_id,log_object_group,log_object_group_id,log_message,log_errno,log_ret_code"
# Configuration option log/command_log_selection.
# Selection criteria used when reporting command log.
# You can define selection criteria that are applied each
# time log is reported. This way, it is possible to control the
# amount of log that is displayed on output and you can select
# only parts of the log that are important for you. To define
# selection criteria, use fields from log report. See also
# <lvm command> --logonly --configreport log -S help for the
# list of possible fields and selection operators. You can also
# define selection criteria for log report on command line directly
# using <lvm command> --configreport log -S <selection criteria>
# which has precedence over log/command_log_selection setting.
# For more information about selection criteria in general, see
# lvm(8) man page.
# This configuration option has an automatic default value.
# command_log_selection = "!(log_type=status && message=success)"
# Configuration option log/verbose.
# Controls the messages sent to stdout or stderr.
verbose = 0
@ -525,7 +613,7 @@ log {
# debug output if the class is listed here. Classes currently
# available: memory, devices, activation, allocation, lvmetad,
# metadata, cache, locking, lvmpolld. Use "all" to see everything.
debug_classes = [ "memory", "devices", "activation", "allocation", "lvmetad", "metadata", "cache", "locking", "lvmpolld" ]
debug_classes = [ "memory", "devices", "activation", "allocation", "lvmetad", "metadata", "cache", "locking", "lvmpolld", "dbus" ]
}
# Configuration section backup.
@ -589,7 +677,7 @@ global {
# Configuration option global/units.
# Default value for --units argument.
units = "h"
units = "r"
# Configuration option global/si_unit_consistency.
# Distinguish between powers of 1024 and 1000 bytes.
@ -851,13 +939,23 @@ global {
# devices/global_filter.
use_lvmetad = @DEFAULT_USE_LVMETAD@
# Configuration option global/lvmetad_update_wait_time.
# Number of seconds a command will wait for lvmetad update to finish.
# After waiting for this period, a command will not use lvmetad, and
# will revert to disk scanning.
# This configuration option has an automatic default value.
# lvmetad_update_wait_time = 10
# Configuration option global/use_lvmlockd.
# Use lvmlockd for locking among hosts using LVM on shared storage.
# See lvmlockd(8) for more information.
# Applicable only if LVM is compiled with lockd support in which
# case there is also lvmlockd(8) man page available for more
# information.
use_lvmlockd = 0
# Configuration option global/lvmlockd_lock_retries.
# Retry lvmlockd lock requests this many times.
# Applicable only if LVM is compiled with lockd support
# This configuration option has an automatic default value.
# lvmlockd_lock_retries = 3
@ -867,7 +965,8 @@ global {
# LVs have been created, the internal LV needs to be extended. lvcreate
# will automatically extend the internal LV when needed by the amount
# specified here. Setting this to 0 disables the automatic extension
# and can cause lvcreate to fail.
# and can cause lvcreate to fail. Applicable only if LVM is compiled
# with lockd support
# This configuration option has an automatic default value.
# sanlock_lv_extend = 256
@ -926,7 +1025,7 @@ global {
# Configuration option global/cache_disabled_features.
# Features to not use in the cache driver.
# This can be helpful for testing, or to avoid using a feature that is
# causing problems. Features include: policy_mq, policy_smq.
# causing problems. Features include: policy_mq, policy_smq, metadata2.
#
# Example
# cache_disabled_features = [ "policy_smq" ]
@ -971,6 +1070,12 @@ global {
# This configuration option has an automatic default value.
# cache_repair_options = [ "" ]
# Configuration option global/fsadm_executable.
# The full path to the fsadm command.
# LVM uses this command to help with lvresize -r operations.
# This configuration option has an automatic default value.
# fsadm_executable = "@FSADM_PATH@"
# Configuration option global/system_id_source.
# The method LVM uses to set the local system ID.
# Volume Groups can also be given a system ID (by vgcreate, vgchange,
@ -1014,7 +1119,14 @@ global {
# a native systemd service, which allows it to be started on demand,
# and to use its own control group. When this option is disabled, LVM
# commands will supervise long running operations by forking themselves.
# Applicable only if LVM is compiled with lvmpolld support.
use_lvmpolld = @DEFAULT_USE_LVMPOLLD@
# Configuration option global/notify_dbus.
# Enable D-Bus notification from LVM commands.
# When enabled, an LVM command that changes PVs, changes VG metadata,
# or changes the activation state of an LV will send a notification.
notify_dbus = 1
}
# Configuration section activation.
@ -1062,7 +1174,8 @@ activation {
# Configuration option activation/missing_stripe_filler.
# Method to fill missing stripes when activating an incomplete LV.
# Using 'error' will make inaccessible parts of the device return I/O
# errors on access. You can instead use a device path, in which case,
# errors on access. Using 'zero' will return success (and zero) on I/O
# You can instead use a device path, in which case,
# that device will be used in place of missing stripes. Using anything
# other than 'error' with mirrored or snapshotted volumes is likely to
# result in data corruption.
@ -1109,8 +1222,8 @@ activation {
# @*
# Selects an LV if a tag defined on the host is also set on the LV
# or VG. See tags/hosttags. If any host tags exist but volume_list
# is not defined, a default single-entry list containing '@*' is
# assumed.
# is not defined, a default single-entry list containing '@*'
# is assumed.
#
# Example
# volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]
@ -1146,11 +1259,11 @@ activation {
# @*
# Selects an LV if a tag defined on the host is also set on the LV
# or VG. See tags/hosttags. If any host tags exist but volume_list
# is not defined, a default single-entry list containing '@*' is
# assumed.
# is not defined, a default single-entry list containing '@*'
# is assumed.
#
# Example
# volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]
# auto_activation_volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]
#
# This configuration option does not have a default value defined.
@ -1172,19 +1285,20 @@ activation {
# @*
# Selects an LV if a tag defined on the host is also set on the LV
# or VG. See tags/hosttags. If any host tags exist but volume_list
# is not defined, a default single-entry list containing '@*' is
# assumed.
# is not defined, a default single-entry list containing '@*'
# is assumed.
#
# Example
# volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]
# read_only_volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]
#
# This configuration option does not have a default value defined.
# Configuration option activation/raid_region_size.
# Size in KiB of each raid or mirror synchronization region.
# For raid or mirror segment types, this is the amount of data that is
# copied at once when initializing, or moved at once by pvmove.
raid_region_size = 512
# The clean/dirty state of data is tracked for each region.
# The value is rounded down to a power of two if necessary, and
# is ignored if it is not a multiple of the machine memory page size.
raid_region_size = 2048
# Configuration option activation/error_when_full.
# Return errors if a thin pool runs out of space.
@ -1415,6 +1529,33 @@ activation {
# This configuration section has an automatic default value.
# metadata {
# Configuration option metadata/check_pv_device_sizes.
# Check device sizes are not smaller than corresponding PV sizes.
# If device size is less than corresponding PV size found in metadata,
# there is always a risk of data loss. If this option is set, then LVM
# issues a warning message each time it finds that the device size is
# less than corresponding PV size. You should not disable this unless
# you are absolutely sure about what you are doing!
# This configuration option is advanced.
# This configuration option has an automatic default value.
# check_pv_device_sizes = 1
# Configuration option metadata/record_lvs_history.
# When enabled, LVM keeps history records about removed LVs in
# metadata. The information that is recorded in metadata for
# historical LVs is reduced when compared to original
# information kept in metadata for live LVs. Currently, this
# feature is supported for thin and thin snapshot LVs only.
# This configuration option has an automatic default value.
# record_lvs_history = 0
# Configuration option metadata/lvs_history_retention_time.
# Retention time in seconds after which a record about individual
# historical logical volume is automatically destroyed.
# A value of 0 disables this feature.
# This configuration option has an automatic default value.
# lvs_history_retention_time = 0
# Configuration option metadata/pvmetadatacopies.
# Number of copies of metadata to store on each PV.
# The --pvmetadatacopies option overrides this setting.
@ -1493,6 +1634,22 @@ activation {
# This configuration section has an automatic default value.
# report {
# Configuration option report/output_format.
# Format of LVM command's report output.
# If there is more than one report per command, then the format
# is applied for all reports. You can also change output format
# directly on command line using --reportformat option which
# has precedence over log/output_format setting.
# Accepted values:
# basic
# Original format with columns and rows. If there is more than
# one report per command, each report is prefixed with report's
# name for identification.
# json
# JSON format.
# This configuration option has an automatic default value.
# output_format = "basic"
# Configuration option report/compact_output.
# Do not print empty values for all report fields.
# If enabled, all fields that don't have a value set for any of the
@ -1553,11 +1710,11 @@ activation {
# This configuration option has an automatic default value.
# quoted = 1
# Configuration option report/colums_as_rows.
# Configuration option report/columns_as_rows.
# Output each column as a row.
# If set, this also implies report/prefixes=1.
# This configuration option has an automatic default value.
# colums_as_rows = 0
# columns_as_rows = 0
# Configuration option report/binary_values_as_numeric.
# Use binary values 0 or 1 instead of descriptive literal values.
@ -1808,6 +1965,77 @@ activation {
# See 'pvs --segments -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# pvsegs_cols_verbose = "pv_name,vg_name,pv_fmt,pv_attr,pv_size,pv_free,pvseg_start,pvseg_size,lv_name,seg_start_pe,segtype,seg_pe_ranges"
# Configuration option report/vgs_cols_full.
# List of columns to report for lvm fullreport's 'vgs' subreport.
# See 'vgs -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# vgs_cols_full = "vg_all"
# Configuration option report/pvs_cols_full.
# List of columns to report for lvm fullreport's 'vgs' subreport.
# See 'pvs -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# pvs_cols_full = "pv_all"
# Configuration option report/lvs_cols_full.
# List of columns to report for lvm fullreport's 'lvs' subreport.
# See 'lvs -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# lvs_cols_full = "lv_all"
# Configuration option report/pvsegs_cols_full.
# List of columns to report for lvm fullreport's 'pvseg' subreport.
# See 'pvs --segments -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# pvsegs_cols_full = "pvseg_all,pv_uuid,lv_uuid"
# Configuration option report/segs_cols_full.
# List of columns to report for lvm fullreport's 'seg' subreport.
# See 'lvs --segments -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# segs_cols_full = "seg_all,lv_uuid"
# Configuration option report/vgs_sort_full.
# List of columns to sort by when reporting lvm fullreport's 'vgs' subreport.
# See 'vgs -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# vgs_sort_full = "vg_name"
# Configuration option report/pvs_sort_full.
# List of columns to sort by when reporting lvm fullreport's 'vgs' subreport.
# See 'pvs -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# pvs_sort_full = "pv_name"
# Configuration option report/lvs_sort_full.
# List of columns to sort by when reporting lvm fullreport's 'lvs' subreport.
# See 'lvs -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# lvs_sort_full = "vg_name,lv_name"
# Configuration option report/pvsegs_sort_full.
# List of columns to sort by when reporting for lvm fullreport's 'pvseg' subreport.
# See 'pvs --segments -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# pvsegs_sort_full = "pv_uuid,pvseg_start"
# Configuration option report/segs_sort_full.
# List of columns to sort by when reporting lvm fullreport's 'seg' subreport.
# See 'lvs --segments -o help' for the list of possible fields.
# This configuration option has an automatic default value.
# segs_sort_full = "lv_uuid,seg_start"
# Configuration option report/mark_hidden_devices.
# Use brackets [] to mark hidden devices.
# This configuration option has an automatic default value.
# mark_hidden_devices = 1
# Configuration option report/two_word_unknown_device.
# Use the two words 'unknown device' in place of '[unknown]'.
# This is displayed when the device for a PV is not known.
# This configuration option has an automatic default value.
# two_word_unknown_device = 0
# }
# Configuration section dmeventd.
@ -1840,6 +2068,15 @@ dmeventd {
# warning is repeated when 85%, 90% and 95% of the pool is filled.
thin_library = "libdevmapper-event-lvm2thin.so"
# Configuration option dmeventd/thin_command.
# The plugin runs command with each 5% increment when thin-pool data volume
# or metadata volume gets above 50%.
# Command which starts with 'lvm ' prefix is internal lvm command.
# You can write your own handler to customise behaviour in more details.
# User handler is specified with the full path starting with '/'.
# This configuration option has an automatic default value.
# thin_command = "lvm lvextend --use-policies"
# Configuration option dmeventd/executable.
# The full path to the dmeventd binary.
# This configuration option has an automatic default value.

50
conf/lvmdbusd.profile Normal file
View File

@ -0,0 +1,50 @@
#
# DO NOT EDIT THIS FILE!
#
# LVM configuration profile used by lvmdbusd daemon.
#
# This sets up LVM to produce output in the most suitable format for processing
# by lvmdbusd daemon which utilizes LVM shell to execute LVM commands.
#
# Do not edit this file in any way. This profile is distributed together with
# lvmdbusd and it contains configuration that is important for lvmdbusd to
# cooperate and interface with LVM correctly.
#
global {
# use bytes for expected and deterministic output
units=b
# no need for suffix if we have units set
suffix=0
}
report {
compact_output=0
compact_output_cols=""
binary_values_as_numeric=0
# time in number of seconds since the Epoch
time_format="%s"
mark_hidden_devices=1
# lvmdbusd expects JSON output
output_format=json
# *_cols_full for lvm fullreport's fields which lvmdbusd relies on to update its state
vgs_cols_full="vg_name,vg_uuid,vg_fmt,vg_size,vg_free,vg_sysid,vg_extent_size,vg_extent_count,vg_free_count,vg_profile,max_lv,max_pv,pv_count,lv_count,snap_count,vg_seqno,vg_mda_count,vg_mda_free,vg_mda_size,vg_mda_used_count,vg_attr,vg_tags"
pvs_cols_full="pv_name,pv_uuid,pv_fmt,pv_size,pv_free,pv_used,dev_size,pv_mda_size,pv_mda_free,pv_ba_start,pv_ba_size,pe_start,pv_pe_count,pv_pe_alloc_count,pv_attr,pv_tags,vg_name,vg_uuid"
lvs_cols_full="lv_uuid,lv_name,lv_path,lv_size,vg_name,pool_lv_uuid,pool_lv,origin_uuid,origin,data_percent,lv_attr,lv_tags,vg_uuid,lv_active,data_lv,metadata_lv,lv_parent,lv_role,lv_layout"
pvsegs_cols_full="pvseg_start,pvseg_size,segtype,pv_uuid,lv_uuid,pv_name"
segs_cols_full="seg_pe_ranges,segtype,lv_uuid"
vgs_sort_full="vg_name"
pvs_sort_full="pv_name"
lvs_sort_full="vg_name,lv_name"
pvsegs_sort_full="pv_uuid,pvseg_start"
segs_sort_full="lv_uuid,seg_start"
}
log {
# lvmdbusd relies on command log report to inspect LVM command's execution status
report_command_log=1
# display only outermost LVM shell-related log that lvmdbusd inspects first after LVM command execution (it calls 'lastlog' for more detailed log afterwards if needed)
command_log_selection="log_context=shell"
command_log_cols="log_seq_num,log_type,log_context,log_object_type,log_object_name,log_object_id,log_object_group,log_object_group_id,log_message,log_errno,log_ret_code"
command_log_sort="log_seq_num"
}

View File

@ -51,6 +51,7 @@ local {
# Configuration option local/host_id.
# The lvmlockd sanlock host_id.
# This must be unique among all hosts, and must be between 1 and 2000.
# Applicable only if LVM is compiled with lockd support
# This configuration option has an automatic default value.
# host_id = 0
}

1840
configure vendored

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
###############################################################################
## Copyright (C) 2000-2004 Sistina Software, Inc. All rights reserved.
## Copyright (C) 2004-2015 Red Hat, Inc. All rights reserved.
## Copyright (C) 2004-2016 Red Hat, Inc. All rights reserved.
##
## This copyrighted material is made available to anyone wishing to use,
## modify, copy, or redistribute it subject to the terms and conditions
@ -8,13 +8,14 @@
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software Foundation,
## Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
################################################################################
AC_PREREQ(2.61)
AC_PREREQ(2.69)
################################################################################
dnl -- Process this file with autoconf to produce a configure script.
AC_INIT
CONFIGURE_LINE="$0 $@"
AC_CONFIG_SRCDIR([lib/device/dev-cache.h])
AC_CONFIG_HEADERS([include/configure.h])
@ -37,9 +38,8 @@ case "$host_os" in
LDDEPS="$LDDEPS .export.sym"
LIB_SUFFIX=so
DEVMAPPER=yes
LVMETAD=no
LVMPOLLD=no
LVMLOCKD=no
BUILD_LVMETAD=no
BUILD_LVMPOLLD=no
LOCKDSANLOCK=no
LOCKDDLM=no
ODIRECT=yes
@ -84,8 +84,12 @@ AC_PROG_LN_S
AC_PROG_MAKE_SET
AC_PROG_MKDIR_P
AC_PROG_RANLIB
AC_CHECK_TOOL(AR, ar)
AC_PATH_TOOL(CFLOW_CMD, cflow)
AC_PATH_TOOL(CSCOPE_CMD, cscope)
AC_PATH_TOOL(CHMOD, chmod)
AC_PATH_TOOL(WC, wc)
AC_PATH_TOOL(SORT, sort)
################################################################################
dnl -- Check for header files.
@ -103,7 +107,7 @@ AC_CHECK_HEADERS([assert.h ctype.h dirent.h errno.h fcntl.h float.h \
sys/time.h sys/types.h sys/utsname.h sys/wait.h time.h \
unistd.h], , [AC_MSG_ERROR(bailing out)])
AC_CHECK_HEADERS(termios.h sys/statvfs.h sys/timerfd.h)
AC_CHECK_HEADERS(termios.h sys/statvfs.h sys/timerfd.h sys/vfs.h linux/magic.h linux/fiemap.h)
case "$host_os" in
linux*)
@ -118,6 +122,7 @@ AC_C_CONST
AC_C_INLINE
AC_CHECK_MEMBERS([struct stat.st_rdev])
AC_CHECK_TYPES([ptrdiff_t])
AC_STRUCT_ST_BLOCKS
AC_STRUCT_TM
AC_TYPE_OFF_T
AC_TYPE_PID_T
@ -134,6 +139,7 @@ AC_TYPE_UINT8_T
AC_TYPE_UINT16_T
AC_TYPE_UINT32_T
AC_TYPE_UINT64_T
AX_GCC_BUILTIN([__builtin_clz])
################################################################################
dnl -- Check for functions
@ -612,6 +618,10 @@ case "$CACHE" in
CACHE_CHECK_VERSION_WARN=y
CACHE_CHECK_NEEDS_CHECK=no
fi
if test "$CACHE_CHECK_VSN_MINOR" -lt 7 ; then
AC_MSG_WARN([$CACHE_CHECK_CMD: Old version "$CACHE_CHECK_VSN" does not support new cache format V2])
CACHE_CHECK_VERSION_WARN=y
fi
fi
fi
# Empty means a config way to ignore cache dumping
@ -665,11 +675,9 @@ AC_DEFINE_UNQUOTED([CACHE_RESTORE_CMD], ["$CACHE_RESTORE_CMD"],
################################################################################
dnl -- Disable readline
AC_MSG_CHECKING(whether to enable readline)
AC_ARG_ENABLE([readline],
AC_HELP_STRING([--disable-readline], [disable readline support]),
READLINE=$enableval, READLINE=maybe)
AC_MSG_RESULT($READLINE)
################################################################################
dnl -- Disable realtime clock support
@ -1129,9 +1137,8 @@ AC_ARG_ENABLE(lvmetad,
AC_HELP_STRING([--enable-lvmetad],
[enable the LVM Metadata Daemon]),
LVMETAD=$enableval)
AC_MSG_RESULT($LVMETAD)
BUILD_LVMETAD=$LVMETAD
test -n "$LVMETAD" && BUILD_LVMETAD=$LVMETAD
AC_MSG_RESULT($BUILD_LVMETAD)
################################################################################
dnl -- Build lvmpolld
@ -1140,63 +1147,57 @@ AC_ARG_ENABLE(lvmpolld,
AC_HELP_STRING([--enable-lvmpolld],
[enable the LVM Polling Daemon]),
LVMPOLLD=$enableval)
AC_MSG_RESULT($LVMPOLLD)
BUILD_LVMPOLLD=$LVMPOLLD
test -n "$LVMPOLLD" && BUILD_LVMPOLLD=$LVMPOLLD
AC_MSG_RESULT($BUILD_LVMPOLLD)
################################################################################
dnl -- Build lockdsanlock
AC_MSG_CHECKING(whether to build lockdsanlock)
AC_ARG_ENABLE(lockd-sanlock,
AC_HELP_STRING([--enable-lockd-sanlock],
BUILD_LVMLOCKD=no
dnl -- Build lvmlockdsanlock
AC_MSG_CHECKING(whether to build lvmlockdsanlock)
AC_ARG_ENABLE(lvmlockd-sanlock,
AC_HELP_STRING([--enable-lvmlockd-sanlock],
[enable the LVM lock daemon using sanlock]),
LOCKDSANLOCK=$enableval)
AC_MSG_RESULT($LOCKDSANLOCK)
BUILD_LOCKDSANLOCK=$LOCKDSANLOCK
if test "$BUILD_LOCKDSANLOCK" = yes; then
AC_DEFINE([LOCKDSANLOCK_SUPPORT], 1, [Define to 1 to include code that uses lvmlockd sanlock option.])
fi
################################################################################
dnl -- Look for sanlock libraries
if test "$BUILD_LOCKDSANLOCK" = yes; then
PKG_CHECK_MODULES(LOCKD_SANLOCK, libsanlock_client, [HAVE_LOCKD_SANLOCK=yes], $bailout)
PKG_CHECK_MODULES(LOCKD_SANLOCK, libsanlock_client >= 3.3.0, [HAVE_LOCKD_SANLOCK=yes], $bailout)
AC_DEFINE([LOCKDSANLOCK_SUPPORT], 1, [Define to 1 to include code that uses lvmlockd sanlock option.])
BUILD_LVMLOCKD=yes
fi
################################################################################
dnl -- Build lockddlm
AC_MSG_CHECKING(whether to build lockddlm)
AC_ARG_ENABLE(lockd-dlm,
AC_HELP_STRING([--enable-lockd-dlm],
dnl -- Build lvmlockddlm
AC_MSG_CHECKING(whether to build lvmlockddlm)
AC_ARG_ENABLE(lvmlockd-dlm,
AC_HELP_STRING([--enable-lvmlockd-dlm],
[enable the LVM lock daemon using dlm]),
LOCKDDLM=$enableval)
AC_MSG_RESULT($LOCKDDLM)
BUILD_LOCKDDLM=$LOCKDDLM
if test "$BUILD_LOCKDDLM" = yes; then
AC_DEFINE([LOCKDDLM_SUPPORT], 1, [Define to 1 to include code that uses lvmlockd dlm option.])
fi
################################################################################
dnl -- Look for dlm libraries
if test "$BUILD_LOCKDDLM" = yes; then
PKG_CHECK_MODULES(LOCKD_DLM, libdlm, [HAVE_LOCKD_DLM=yes], $bailout)
AC_DEFINE([LOCKDDLM_SUPPORT], 1, [Define to 1 to include code that uses lvmlockd dlm option.])
BUILD_LVMLOCKD=yes
fi
################################################################################
dnl -- Build lvmlockd
AC_MSG_CHECKING(whether to build lvmlockd)
AC_MSG_RESULT($BUILD_LVMLOCKD)
if test "$BUILD_LVMLOCKD" = yes; then
AS_IF([test -n "$BUILD_LVMPOLLD"], [BUILD_LVMPOLLD=yes; AC_MSG_WARN([Enabling lvmpolld - required by lvmlockd.])])
AS_IF([test -n "$BUILD_LVMETAD"], [BUILD_LVMETAD=yes; AC_MSG_WARN([Enabling lvmetad - required by lvmlockd.])])
AS_IF([test "$LVMPOLLD" = no], [AC_MSG_ERROR([cannot build lvmlockd with --disable-lvmpolld.])])
AS_IF([test "$LVMETAD" = no], [AC_MSG_ERROR([cannot build lvmlockd with --disable-lvmetad.])])
AS_IF([test "$BUILD_LVMPOLLD" = no], [BUILD_LVMPOLLD=yes; AC_MSG_WARN([Enabling lvmpolld - required by lvmlockd.])])
AS_IF([test "$BUILD_LVMETAD" = no], [BUILD_LVMETAD=yes; AC_MSG_WARN([Enabling lvmetad - required by lvmlockd.])])
AC_MSG_CHECKING([defaults for use_lvmlockd])
AC_ARG_ENABLE(use_lvmlockd,
AC_HELP_STRING([--disable-use-lvmlockd],
@ -1275,53 +1276,80 @@ fi
AC_DEFINE_UNQUOTED(DEFAULT_USE_LVMPOLLD, [$DEFAULT_USE_LVMPOLLD],
[Use lvmpolld by default.])
################################################################################
dnl -- Check dmfilemapd
AC_MSG_CHECKING(whether to build dmfilemapd)
AC_ARG_ENABLE(dmfilemapd, AC_HELP_STRING([--enable-dmfilemapd],
[enable the dmstats filemap daemon]),
BUILD_DMFILEMAPD=$enableval, BUILD_DMFILEMAPD=no)
AC_MSG_RESULT($BUILD_DMFILEMAPD)
AC_DEFINE([DMFILEMAPD], $BUILD_DMFILEMAPD, [Define to 1 to enable the device-mapper filemap daemon.])
dnl -- dmfilemapd requires FIEMAP
if test "$BUILD_DMFILEMAPD" = yes; then
AC_CHECK_HEADER([linux/fiemap.h], , [AC_MSG_ERROR(--enable-dmfilemapd requires fiemap.h)])
fi
################################################################################
dnl -- Build notifydbus
AC_MSG_CHECKING(whether to build notifydbus)
AC_ARG_ENABLE(notify-dbus,
AC_HELP_STRING([--enable-notify-dbus],
[enable LVM notification using dbus]),
NOTIFYDBUS_SUPPORT=$enableval, NOTIFYDBUS_SUPPORT=no)
AC_MSG_RESULT($NOTIFYDBUS_SUPPORT)
if test "$NOTIFYDBUS_SUPPORT" = yes; then
AC_DEFINE([NOTIFYDBUS_SUPPORT], 1, [Define to 1 to include code that uses dbus notification.])
LIBS="-lsystemd $LIBS"
fi
################################################################################
dnl -- Look for dbus libraries
if test "$NOTIFYDBUS_SUPPORT" = yes; then
PKG_CHECK_MODULES(NOTIFY_DBUS, systemd >= 221, [HAVE_NOTIFY_DBUS=yes], $bailout)
fi
################################################################################
dnl -- Enable blkid wiping functionality
AC_MSG_CHECKING(whether to enable libblkid detection of signatures when wiping)
AC_ARG_ENABLE(blkid_wiping,
AC_HELP_STRING([--disable-blkid_wiping],
[disable libblkid detection of signatures when wiping and use native code instead]),
BLKID_WIPING=$enableval, BLKID_WIPING=maybe)
AC_MSG_RESULT($BLKID_WIPING)
DEFAULT_USE_BLKID_WIPING=0
if test "$BLKID_WIPING" != no; then
pkg_config_init
PKG_CHECK_MODULES(BLKID, blkid >= 2.24,
[test "$BLKID_WIPING" = maybe && BLKID_WIPING=yes],
[if test "$BLKID_WIPING" = maybe; then
[ BLKID_WIPING=yes
BLKID_PC="blkid"
DEFAULT_USE_BLKID_WIPING=1
AC_DEFINE([BLKID_WIPING_SUPPORT], 1, [Define to 1 to use libblkid detection of signatures when wiping.])
], [if test "$BLKID_WIPING" = maybe; then
BLKID_WIPING=no
else
AC_MSG_ERROR([bailing out... blkid library >= 2.24 is required])
fi])
if test "$BLKID_WIPING" = yes; then
BLKID_PC="blkid"
DEFAULT_USE_BLKID_WIPING=1
AC_DEFINE([BLKID_WIPING_SUPPORT], 1, [Define to 1 to use libblkid detection of signatures when wiping.])
else
DEFAULT_USE_BLKID_WIPING=1
fi
else
DEFAULT_USE_BLKID_WIPING=0
fi
AC_MSG_CHECKING([whether to enable libblkid detection of signatures when wiping])
AC_MSG_RESULT($BLKID_WIPING)
AC_DEFINE_UNQUOTED(DEFAULT_USE_BLKID_WIPING, [$DEFAULT_USE_BLKID_WIPING],
[Use blkid wiping by default.])
################################################################################
dnl -- Enable udev-systemd protocol to instantiate a service for background jobs
dnl -- Requires systemd version 205 at least (including support for systemd-run)
AC_MSG_CHECKING(whether to use udev-systemd protocol for jobs in background)
AC_ARG_ENABLE(udev-systemd-background-jobs,
AC_HELP_STRING([--disable-udev-systemd-background-jobs],
[disable udev-systemd protocol to instantiate a service for background job]),
UDEV_SYSTEMD_BACKGROUND_JOBS=$enableval,
UDEV_SYSTEMD_BACKGROUND_JOBS=maybe)
AC_MSG_RESULT($UDEV_SYSTEMD_BACKGROUND_JOBS)
if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" != no; then
pkg_config_init
PKG_CHECK_MODULES(SYSTEMD, systemd >= 205,
[test "$UDEV_SYSTEMD_BACKGROUND_JOBS" = maybe && UDEV_SYSTEMD_BACKGROUND_JOBS=yes],
[UDEV_SYSTEMD_BACKGROUND_JOBS=yes],
[if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" = maybe; then
UDEV_SYSTEMD_BACKGROUND_JOBS=no
else
@ -1329,6 +1357,9 @@ if test "$UDEV_SYSTEMD_BACKGROUND_JOBS" != no; then
fi])
fi
AC_MSG_CHECKING(whether to use udev-systemd protocol for jobs in background)
AC_MSG_RESULT($UDEV_SYSTEMD_BACKGROUND_JOBS)
################################################################################
dnl -- Enable udev synchronisation
AC_MSG_CHECKING(whether to enable synchronisation with udev processing)
@ -1342,6 +1373,10 @@ if test "$UDEV_SYNC" = yes; then
pkg_config_init
PKG_CHECK_MODULES(UDEV, libudev >= 143, [UDEV_PC="libudev"])
AC_DEFINE([UDEV_SYNC_SUPPORT], 1, [Define to 1 to enable synchronisation with udev processing.])
AC_CHECK_LIB(udev, udev_device_get_is_initialized, AC_DEFINE([HAVE_LIBUDEV_UDEV_DEVICE_GET_IS_INITIALIZED], 1,
[Define to 1 if udev_device_get_is_initialized is available.]))
LIBS=$ac_check_lib_save_LIBS
fi
dnl -- Enable udev rules
@ -1441,25 +1476,76 @@ test "$CMDLIB" = yes \
&& LVM2CMD_LIB=-llvm2cmd \
|| LVM2CMD_LIB=
################################################################################
dnl -- Enable D-Bus service
AC_MSG_CHECKING(whether to include Python D-Bus support)
AC_ARG_ENABLE(dbus-service,
AC_HELP_STRING([--enable-dbus-service], [install D-Bus support]),
BUILD_LVMDBUSD=$enableval, BUILD_LVMDBUSD=no)
AC_MSG_RESULT($BUILD_LVMDBUSD)
################################################################################
dnl -- Enable Python liblvm2app bindings
AC_MSG_CHECKING(whether to build Python wrapper for liblvm2app.so)
AC_ARG_ENABLE(python_bindings,
AC_HELP_STRING([--enable-python_bindings], [build Python applib bindings]),
AC_HELP_STRING([--enable-python_bindings], [build default Python applib bindings]),
PYTHON_BINDINGS=$enableval, PYTHON_BINDINGS=no)
AC_MSG_RESULT($PYTHON_BINDINGS)
AC_MSG_CHECKING(whether to build Python2 wrapper for liblvm2app.so)
AC_ARG_ENABLE(python2_bindings,
AC_HELP_STRING([--enable-python2_bindings], [build Python2 applib bindings]),
PYTHON2_BINDINGS=$enableval, PYTHON2_BINDINGS=no)
AC_MSG_RESULT($PYTHON2_BINDINGS)
AC_MSG_CHECKING(whether to build Python3 wrapper for liblvm2app.so)
AC_ARG_ENABLE(python3_bindings,
AC_HELP_STRING([--enable-python3_bindings], [build Python3 applib bindings]),
PYTHON3_BINDINGS=$enableval, PYTHON3_BINDINGS=no)
AC_MSG_RESULT($PYTHON3_BINDINGS)
if test "$PYTHON_BINDINGS" = yes; then
test "$APPLIB" != yes && AC_MSG_ERROR([--enable-python_bindings requires --enable-applib])
AC_MSG_ERROR([--enable-python-bindings is replaced by --enable-python2-bindings and --enable-python3-bindings])
fi
AC_PATH_TOOL(PYTHON, python)
test -z "$PYTHON" && AC_MSG_ERROR([python is required for --enable-python_bindings but cannot be found])
if test "$PYTHON2_BINDINGS" = yes; then
AM_PATH_PYTHON([2])
AC_PATH_TOOL(PYTHON2, python2)
test -z "$PYTHON2" && AC_MSG_ERROR([python2 is required for --enable-python2_bindings but cannot be found])
AC_PATH_TOOL(PYTHON2_CONFIG, python2-config)
test -z "$PYTHON2_CONFIG" && AC_PATH_TOOL(PYTHON2_CONFIG, python-config)
test -z "$PYTHON2_CONFIG" && AC_MSG_ERROR([python headers are required for --enable-python2_bindings but cannot be found])
PYTHON2_INCDIRS=`"$PYTHON2_CONFIG" --includes`
PYTHON2_LIBDIRS=`"$PYTHON2_CONFIG" --libs`
PYTHON2DIR=$pythondir
PYTHON_BINDINGS=yes
fi
if test "$PYTHON3_BINDINGS" = yes -o "$BUILD_LVMDBUSD" = yes; then
unset PYTHON PYTHON_CONFIG
unset am_cv_pathless_PYTHON ac_cv_path_PYTHON am_cv_python_platform
unset am_cv_python_pythondir am_cv_python_version am_cv_python_pyexecdir
unset ac_cv_path_PYTHON_CONFIG ac_cv_path_ac_pt_PYTHON_CONFIG
AM_PATH_PYTHON([3])
PYTHON3=$PYTHON
test -z "$PYTHON3" && AC_MSG_ERROR([python3 is required for --enable-python3_bindings or --enable-dbus-service but cannot be found])
AC_PATH_TOOL(PYTHON3_CONFIG, python3-config)
test -z "$PYTHON3_CONFIG" && AC_MSG_ERROR([python3 headers are required for --enable-python3_bindings or --enable-dbus-service but cannot be found])
PYTHON3_INCDIRS=`"$PYTHON3_CONFIG" --includes`
PYTHON3_LIBDIRS=`"$PYTHON3_CONFIG" --libs`
PYTHON3DIR=$pythondir
PYTHON_BINDINGS=yes
fi
AC_PATH_TOOL(PYTHON_CONFIG, python-config)
test -z "$PYTHON_CONFIG" && AC_MSG_ERROR([python headers are required for --enable-python_bindings but cannot be found])
if test "$BUILD_LVMDBUSD" = yes; then
# To get this macro, install autoconf-archive package then run autoreconf
AC_PYTHON_MODULE([pyudev], [Required], python3)
AC_PYTHON_MODULE([dbus], [Required], python3)
fi
PYTHON_INCDIRS=`"$PYTHON_CONFIG" --includes`
PYTHON_LIBDIRS=`"$PYTHON_CONFIG" --libs`
if test "$PYTHON_BINDINGS" = yes -o "$PYTHON2_BINDINGS" = yes -o "$PYTHON3_BINDINGS" = yes; then
test "$APPLIB" != yes && AC_MSG_ERROR([Python_bindings require --enable-applib])
fi
################################################################################
@ -1634,6 +1720,7 @@ Note: (n)curses also seems to work as a substitute for termcap. This was
AC_DEFINE([READLINE_SUPPORT], 1,
[Define to 1 to include the LVM readline shell.])
dnl -- Try only with -lreadline and check for different symbol
READLINE=yes
LIBS=$lvm_saved_libs
AC_CHECK_LIB([readline], [rl_line_buffer],
[ READLINE_LIBS="-lreadline" ], [
@ -1740,6 +1827,8 @@ dnl -- Ensure additional headers required
if test "$READLINE" = yes; then
AC_CHECK_HEADERS(readline/readline.h readline/history.h,,hard_bailout)
fi
AC_MSG_CHECKING(whether to enable readline)
AC_MSG_RESULT($READLINE)
if test "$BUILD_CMIRRORD" = yes; then
AC_CHECK_FUNCS(atexit,,hard_bailout)
@ -1782,6 +1871,10 @@ if test "$UDEV_SYNC" = yes; then
AC_CHECK_HEADERS(sys/ipc.h sys/sem.h,,hard_bailout)
fi
if test "$BUILD_DMFILEMAPD" = yes; then
AC_CHECK_HEADERS([sys/inotify.h],,hard_bailout)
fi
################################################################################
AC_PATH_TOOL(MODPROBE_CMD, modprobe)
@ -1801,6 +1894,10 @@ test "$prefix" != NONE && clvmd_prefix=$prefix
CLVMD_PATH="$clvmd_prefix/sbin/clvmd"
AC_DEFINE_UNQUOTED(CLVMD_PATH, ["$CLVMD_PATH"], [Path to clvmd binary.])
FSADM_PATH="$lvm_exec_prefix/sbin/fsadm"
AC_DEFINE_UNQUOTED(FSADM_PATH, ["$FSADM_PATH"], [Path to fsadm binary.])
################################################################################
dnl -- dmeventd pidfile and executable path
if test "$BUILD_DMEVENTD" = yes; then
@ -1863,8 +1960,12 @@ AC_DEFINE_UNQUOTED(DEFAULT_CACHE_SUBDIR, ["$DEFAULT_CACHE_SUBDIR"],
AC_ARG_WITH(default-locking-dir,
AC_HELP_STRING([--with-default-locking-dir=DIR],
[default locking directory [/var/lock/lvm]]),
DEFAULT_LOCK_DIR=$withval, DEFAULT_LOCK_DIR="/var/lock/lvm")
[default locking directory [autodetect_lock_dir/lvm]]),
DEFAULT_LOCK_DIR=$withval,
[AC_MSG_CHECKING(for default lock directory)
DEFAULT_LOCK_DIR="$RUN_DIR/lock/lvm"
test -d "$RUN_DIR/lock" || DEFAULT_LOCK_DIR="/var/lock/lvm"
AC_MSG_RESULT($DEFAULT_LOCK_DIR)])
AC_DEFINE_UNQUOTED(DEFAULT_LOCK_DIR, ["$DEFAULT_LOCK_DIR"],
[Name of default locking directory.])
@ -1905,20 +2006,25 @@ LVM_MINOR=`echo "$VER" | $AWK -F '.' '{print $2}'`
LVM_PATCHLEVEL=`echo "$VER" | $AWK -F '[[(.]]' '{print $3}'`
LVM_LIBAPI=`echo "$VER" | $AWK -F '[[()]]' '{print $2}'`
AC_DEFINE_UNQUOTED(LVM_CONFIGURE_LINE, "$CONFIGURE_LINE", [configure command line used])
################################################################################
AC_SUBST(APPLIB)
AC_SUBST(AWK)
AC_SUBST(BLKID_PC)
AC_SUBST(BUILD_CMIRRORD)
AC_SUBST(BUILD_DMEVENTD)
AC_SUBST(BUILD_LVMDBUSD)
AC_SUBST(BUILD_LVMETAD)
AC_SUBST(BUILD_LVMPOLLD)
AC_SUBST(BUILD_LVMLOCKD)
AC_SUBST(BUILD_LOCKDSANLOCK)
AC_SUBST(BUILD_LOCKDDLM)
AC_SUBST(BUILD_DMFILEMAPD)
AC_SUBST(CACHE)
AC_SUBST(CFLAGS)
AC_SUBST(CFLOW_CMD)
AC_SUBST(CHMOD)
AC_SUBST(CLDFLAGS)
AC_SUBST(CLDNOWHOLEARCHIVE)
AC_SUBST(CLDWHOLEARCHIVE)
@ -1966,6 +2072,7 @@ AC_SUBST(DMEVENTD_PATH)
AC_SUBST(DM_LIB_PATCHLEVEL)
AC_SUBST(ELDFLAGS)
AC_SUBST(FSADM)
AC_SUBST(FSADM_PATH)
AC_SUBST(BLKDEACTIVATE)
AC_SUBST(HAVE_LIBDL)
AC_SUBST(HAVE_REALTIME)
@ -1991,14 +2098,22 @@ AC_SUBST(MIRRORS)
AC_SUBST(MSGFMT)
AC_SUBST(OCF)
AC_SUBST(OCFDIR)
AC_SUBST(ODIRECT)
AC_SUBST(PKGCONFIG)
AC_SUBST(POOL)
AC_SUBST(M_LIBS)
AC_SUBST(PTHREAD_LIBS)
AC_SUBST(PYTHON)
AC_SUBST(PYTHON2)
AC_SUBST(PYTHON3)
AC_SUBST(PYTHON_BINDINGS)
AC_SUBST(PYTHON_INCDIRS)
AC_SUBST(PYTHON_LIBDIRS)
AC_SUBST(PYTHON2_BINDINGS)
AC_SUBST(PYTHON3_BINDINGS)
AC_SUBST(PYTHON2_INCDIRS)
AC_SUBST(PYTHON3_INCDIRS)
AC_SUBST(PYTHON2_LIBDIRS)
AC_SUBST(PYTHON3_LIBDIRS)
AC_SUBST(PYTHON2DIR)
AC_SUBST(PYTHON3DIR)
AC_SUBST(QUORUM_CFLAGS)
AC_SUBST(QUORUM_LIBS)
AC_SUBST(RAID)
@ -2070,6 +2185,9 @@ daemons/dmeventd/plugins/raid/Makefile
daemons/dmeventd/plugins/mirror/Makefile
daemons/dmeventd/plugins/snapshot/Makefile
daemons/dmeventd/plugins/thin/Makefile
daemons/dmfilemapd/Makefile
daemons/lvmdbusd/Makefile
daemons/lvmdbusd/path.py
daemons/lvmetad/Makefile
daemons/lvmpolld/Makefile
daemons/lvmlockd/Makefile
@ -2107,12 +2225,14 @@ scripts/blk_availability_init_red_hat
scripts/blk_availability_systemd_red_hat.service
scripts/clvmd_init_red_hat
scripts/cmirrord_init_red_hat
scripts/com.redhat.lvmdbus1.service
scripts/dm_event_systemd_red_hat.service
scripts/dm_event_systemd_red_hat.socket
scripts/lvm2_cluster_activation_red_hat.sh
scripts/lvm2_cluster_activation_systemd_red_hat.service
scripts/lvm2_clvmd_systemd_red_hat.service
scripts/lvm2_cmirrord_systemd_red_hat.service
scripts/lvm2_lvmdbusd_systemd_red_hat.service
scripts/lvm2_lvmetad_init_red_hat
scripts/lvm2_lvmetad_systemd_red_hat.service
scripts/lvm2_lvmetad_systemd_red_hat.socket
@ -2125,6 +2245,7 @@ scripts/lvm2_monitoring_init_red_hat
scripts/lvm2_monitoring_systemd_red_hat.service
scripts/lvm2_pvscan_systemd_red_hat@.service
scripts/lvm2_tmpfiles_red_hat.conf
scripts/lvmdump.sh
scripts/Makefile
test/Makefile
test/api/Makefile
@ -2141,10 +2262,14 @@ AS_IF([test -n "$THIN_CONFIGURE_WARN"],
[AC_MSG_WARN([Support for thin provisioning is limited since some thin provisioning tools are missing!])])
AS_IF([test -n "$THIN_CHECK_VERSION_WARN"],
[AC_MSG_WARN([You should also install thin_check vsn 0.3.2 (or later) to use lvm2 thin provisioning])])
[AC_MSG_WARN([You should also install latest thin_check vsn 0.7.0 (or later) for lvm2 thin provisioning])])
AS_IF([test -n "$CACHE_CONFIGURE_WARN"],
[AC_MSG_WARN([Support for cache is limited since some cache tools are missing!])])
AS_IF([test -n "$CACHE_CHECK_VERSION_WARN"],
[AC_MSG_WARN([You should install latest cache_check vsn 0.7.0 to use lvm2 cache metadata format 2])])
AS_IF([test "$ODIRECT" != yes],
[AC_MSG_WARN([O_DIRECT disabled: low-memory pvmove may lock up])])

146
coverity/coverity_model.c Normal file
View File

@ -0,0 +1,146 @@
/*
* Copyright (C) 2015 Red Hat, Inc. All rights reserved.
*
* This file is part of LVM2.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License v.2.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* Coverity usage:
*
* translate model into xml
* cov-make-library -of coverity_model.xml coverity_model.c
*
* compile (using outdir 'cov'):
* cov-build --dir=cov make CC=gcc
*
* analyze (agressively, using 'cov')
* cov-analyze --dir cov --wait-for-license --hfa --concurrency --enable-fnptr --enable-constraint-fpp --security --all --aggressiveness-level=high --field-offset-escape --user-model-file=coverity/coverity_model.xml
*
* generate html output (to 'html' from 'cov'):
* cov-format-errors --dir cov --html-output html
*/
struct lv_segment;
struct logical_volume;
struct lv_segment *first_seg(const struct logical_volume *lv)
{
return ((struct lv_segment **)lv)[0];
}
struct lv_segment *last_seg(const struct logical_volume *lv)
{
return ((struct lv_segment **)lv)[0];
}
const char *find_config_tree_str(struct cmd_context *cmd, int id, struct profile *profile)
{
return "STRING";
}
struct logical_volume *origin_from_cow(const struct logical_volume *lv)
{
if (lv)
return lv;
__coverity_panic__();
}
/* simple_memccpy() from glibc */
void *memccpy(void *dest, const void *src, int c, size_t n)
{
const char *s = src;
char *d = dest;
while (n-- > 0)
if ((*d++ = *s++) == (char) c)
return d;
return 0;
}
/*
* 2 lines bellow needs to be placed in coverity/config/user_nodefs.h
* Not sure about any other way.
* Without them, coverity shows warning since x86 system header files
* are using inline assembly to reset fdset
*/
//#nodef FD_ZERO model_FD_ZERO
//void model_FD_ZERO(void *fdset);
void model_FD_ZERO(void *fdset)
{
unsigned i;
for (i = 0; i < 1024 / 8 / sizeof(long); ++i)
((long*)fdset)[i] = 0;
}
/* Resent Coverity reports quite weird errors... */
int *__errno_location(void)
{
}
const unsigned short **__ctype_b_loc (void)
{
}
/*
* Added extra pointer check to not need these models,
* for now just keep then in file
*/
/*
struct cmd_context;
struct profile;
const char *find_config_tree_str(struct cmd_context *cmd, int id, struct profile *profile)
{
return "text";
}
const char *find_config_tree_str_allow_empty(struct cmd_context *cmd, int id, struct profile *profile)
{
return "text";
}
*/
/*
* Until fixed coverity case# 00531860:
* A FORWARD_NULL false positive on a recursive function call
*
* model also these functions:
*/
/*
const struct dm_config_node;
const struct dm_config_node *find_config_tree_array(struct cmd_context *cmd, int id, struct profile *profile)
{
const struct dm_config_node *cn;
return cn;
}
const struct dm_config_node *find_config_tree_node(struct cmd_context *cmd, int id, struct profile *profile)
{
const struct dm_config_node *cn;
return cn;
}
int find_config_tree_bool(struct cmd_context *cmd, int id, struct profile *profile)
{
int b;
return b;
}
*/

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@
@ -41,11 +41,19 @@ ifeq ("@BUILD_LVMPOLLD@", "yes")
endif
ifeq ("@BUILD_LVMLOCKD@", "yes")
SUBDIRS += lvmlockd
SUBDIRS += lvmlockd
endif
ifeq ("@BUILD_LVMDBUSD@", "yes")
SUBDIRS += lvmdbusd
endif
ifeq ("@BUILD_DMFILEMAPD@", "yes")
SUBDIRS += dmfilemapd
endif
ifeq ($(MAKECMDGOALS),distclean)
SUBDIRS = clvmd cmirrord dmeventd lvmetad lvmpolld lvmlockd
SUBDIRS = clvmd cmirrord dmeventd lvmetad lvmpolld lvmlockd lvmdbusd dmfilemapd
endif
include $(top_builddir)/make.tmpl

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Definitions for CLVMD server and clients */
@ -50,7 +50,7 @@ struct clvm_header {
#define CLVMD_FLAG_REMOTE 8 /* Do this on all nodes except for the local node */
/* Name of the local socket to communicate between lvm and clvmd */
static const char CLVMD_SOCKNAME[]= DEFAULT_RUN_DIR "/clvmd.sock";
#define CLVMD_SOCKNAME DEFAULT_RUN_DIR "/clvmd.sock"
/* Internal commands & replies */
#define CLVMD_CMD_REPLY 1
@ -76,8 +76,10 @@ static const char CLVMD_SOCKNAME[]= DEFAULT_RUN_DIR "/clvmd.sock";
#define CLVMD_CMD_SYNC_NAMES 45
/* Used internally by some callers, but not part of the protocol.*/
#define NODE_ALL "*"
#define NODE_LOCAL "."
#define NODE_REMOTE "^"
#ifndef NODE_ALL
# define NODE_ALL "*"
# define NODE_LOCAL "."
# define NODE_REMOTE "^"
#endif
#endif

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
@ -532,6 +532,7 @@ static int _cluster_fd_callback(struct local_client *fd, char *buf, int len,
static int _cluster_send_message(const void *buf, int msglen, const char *csid,
const char *errtext)
{
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
struct iovec iov[2];
cs_error_t err;
int target_node;
@ -546,7 +547,10 @@ static int _cluster_send_message(const void *buf, int msglen, const char *csid,
iov[1].iov_base = (char *)buf;
iov[1].iov_len = msglen;
pthread_mutex_lock(&_mutex);
err = cpg_mcast_joined(cpg_handle, CPG_TYPE_AGREED, iov, 2);
pthread_mutex_unlock(&_mutex);
return cs_to_errno(err);
}

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "clvmd-common.h"

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
@ -374,7 +374,7 @@ int main(int argc, char *argv[])
/* Deal with command-line arguments */
opterr = 0;
optind = 0;
while ((opt = getopt_long(argc, argv, "vVhfd:t:RST:CI:E:",
while ((opt = getopt_long(argc, argv, "Vhfd:t:RST:CI:E:",
longopts, NULL)) != -1) {
switch (opt) {
case 'h':
@ -517,7 +517,7 @@ int main(int argc, char *argv[])
/* Initialise the LVM thread variables */
dm_list_init(&lvm_cmd_head);
if (pthread_attr_init(&stack_attr) ||
pthread_attr_setstacksize(&stack_attr, STACK_SIZE)) {
pthread_attr_setstacksize(&stack_attr, STACK_SIZE + getpagesize())) {
log_sys_error("pthread_attr_init", "");
exit(1);
}
@ -604,7 +604,10 @@ int main(int argc, char *argv[])
local_client_head.fd, &local_client_head, newfd->fd, newfd);
/* Don't let anyone else to do work until we are started */
pthread_create(&lvm_thread, &stack_attr, lvm_thread_fn, &lvm_params);
if (pthread_create(&lvm_thread, &stack_attr, lvm_thread_fn, &lvm_params)) {
log_sys_error("pthread_create", "");
goto out;
}
/* Don't start until the LVM thread is ready */
pthread_barrier_wait(&lvm_start_barrier);

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CLVMD_H

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "clvmd-common.h"
@ -291,6 +291,7 @@ static int hold_lock(char *resource, int mode, int flags)
}
lvi->lock_mode = mode;
lvi->lock_id = 0;
status = sync_lock(resource, mode, flags & ~LCKF_CONVERT, &lvi->lock_id);
saved_errno = errno;
if (status) {
@ -662,7 +663,8 @@ int do_refresh_cache(void)
init_full_scan_done(0);
init_ignore_suspended_devices(1);
lvmcache_label_scan(cmd, 2);
lvmcache_force_next_label_scan();
lvmcache_label_scan(cmd);
dm_pool_empty(cmd->mem);
pthread_mutex_unlock(&lvm_lock);
@ -899,8 +901,12 @@ int init_clvm(struct dm_hash_table *excl_uuid)
if (!get_initial_state(excl_uuid))
log_error("Cannot load initial lock states.");
if (!udev_init_library_context())
stack;
if (!(cmd = create_toolcontext(1, NULL, 0, 1, 1, 1))) {
log_error("Failed to allocate command context");
udev_fin_library_context();
return 0;
}
@ -927,6 +933,7 @@ void destroy_lvm(void)
if (cmd) {
memlock_dec_daemon(cmd);
destroy_toolcontext(cmd);
udev_fin_library_context();
cmd = NULL;
}
}

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Functions in lvm-functions.c */

View File

@ -10,7 +10,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* FIXME Remove duplicated functions from this file. */

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "logging.h"
#include "common.h"

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "logging.h"
#include "cluster.h"
@ -182,7 +182,7 @@ int cluster_send(struct clog_request *rq)
}
/*
* Once the request heads for the cluster, the luid looses
* Once the request heads for the cluster, the luid loses
* all its meaning.
*/
rq->u_rq.luid = 0;
@ -1440,7 +1440,7 @@ static void cpg_leave_callback(struct clog_cpg *match,
free(rq);
}
}
for (i = 0, j = 0; i < match->checkpoints_needed; i++, j++) {
for (i = 0, j = 0; (int) i < match->checkpoints_needed; i++, j++) {
match->checkpoint_requesters[j] = match->checkpoint_requesters[i];
if (match->checkpoint_requesters[i] == left->nodeid) {
LOG_ERROR("[%s] Removing pending ckpt from needed list (%u is leaving)",

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LVM_CLOG_CLUSTER_H
#define _LVM_CLOG_CLUSTER_H

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LVM_CLOG_COMMON_H
#define _LVM_CLOG_COMMON_H

View File

@ -7,11 +7,12 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "logging.h"
#include "functions.h"
#include <sys/sysmacros.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
@ -376,7 +377,7 @@ static int _clog_ctr(char *uuid, uint64_t luid,
uint32_t block_on_error = 0;
int disk_log;
char disk_path[128];
char disk_path[PATH_MAX];
int unlink_path = 0;
long page_size;
int pages;
@ -573,6 +574,12 @@ static int clog_ctr(struct dm_ulog_request *rq)
for (argc = 0, p = rq->data; (p = strstr(p, " ")); p++, argc++)
*p = '\0';
if (!argc) {
LOG_ERROR("Received constructor request with bad data %s",
rq->data);
return -EINVAL;
}
argv = malloc(argc * sizeof(char *));
if (!argv)
return -ENOMEM;

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LVM_CLOG_FUNCTIONS_H
#define _LVM_CLOG_FUNCTIONS_H

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "logging.h"
#include "link_mon.h"

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LVM_CLOG_LINK_MON_H
#define _LVM_CLOG_LINK_MON_H

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "logging.h"
#include "common.h"

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LVM_CLOG_LOCAL_H
#define _LVM_CLOG_LOCAL_H

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "logging.h"

View File

@ -7,7 +7,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LVM_CLOG_LOGGING_H

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
@ -99,13 +99,28 @@ static time_t _idle_since = 0;
static char **_initial_registrations = 0;
/* FIXME Make configurable at runtime */
__attribute__((format(printf, 4, 5)))
static void _dmeventd_log(int level, const char *file, int line,
const char *format, ...)
/* All libdm messages */
__attribute__((format(printf, 5, 6)))
static void _libdm_log(int level, const char *file, int line,
int dm_errno_or_class, const char *format, ...)
{
va_list ap;
va_start(ap, format);
dm_event_log("dm", level, file, line, 0, format, ap);
dm_event_log("#dm", level, file, line, dm_errno_or_class, format, ap);
va_end(ap);
}
/* All dmeventd messages */
#undef LOG_MESG
#define LOG_MESG(l, f, ln, e, x...) _dmeventd_log(l, f, ln, e, ## x)
__attribute__((format(printf, 5, 6)))
static void _dmeventd_log(int level, const char *file, int line,
int dm_errno_or_class, const char *format, ...)
{
va_list ap;
va_start(ap, format);
dm_event_log("dmeventd", level, file, line, dm_errno_or_class, format, ap);
va_end(ap);
}
@ -408,7 +423,7 @@ static struct thread_status *_alloc_thread_status(const struct message_data *dat
if (!(thread->device.uuid = dm_strdup(data->device_uuid)))
goto_out;
/* Until real name resolved, use UUID */
/* Until real name resolved, use UUID */
if (!(thread->device.name = dm_strdup(data->device_uuid)))
goto_out;
@ -453,7 +468,7 @@ static int _pthread_create_smallstack(pthread_t *t, void *(*fun)(void *), void *
/*
* We use a smaller stack since it gets preallocated in its entirety
*/
pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE);
pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE + getpagesize());
/*
* If no-one will be waiting, we need to detach.
@ -829,17 +844,6 @@ static void _print_sigset(const char *prefix, const sigset_t *sigset)
}
#endif
static sigset_t _unblock_sigalrm(void)
{
sigset_t set, old;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
pthread_sigmask(SIG_UNBLOCK, &set, &old);
return old;
}
enum {
DM_WAIT_RETRY,
DM_WAIT_INTR,
@ -849,7 +853,7 @@ enum {
/* Wait on a device until an event occurs. */
static int _event_wait(struct thread_status *thread)
{
sigset_t set;
sigset_t set, old;
int ret = DM_WAIT_RETRY;
struct dm_info info;
@ -859,7 +863,12 @@ static int _event_wait(struct thread_status *thread)
* This is so that you can break out of waiting on an event,
* either for a timeout event, or to cancel the thread.
*/
set = _unblock_sigalrm();
sigemptyset(&set);
sigaddset(&set, SIGALRM);
if (pthread_sigmask(SIG_UNBLOCK, &set, &old) != 0) {
log_sys_error("pthread_sigmask", "unblock alarm");
return ret; /* What better */
}
if (dm_task_run(thread->wait_task)) {
thread->current_events |= DM_EVENT_DEVICE_ERROR;
@ -883,10 +892,11 @@ static int _event_wait(struct thread_status *thread)
}
}
pthread_sigmask(SIG_SETMASK, &set, NULL);
if (pthread_sigmask(SIG_SETMASK, &old, NULL) != 0)
log_sys_error("pthread_sigmask", "block alarm");
#ifdef DEBUG_SIGNALS
_print_sigset("dmeventd blocking ", &set);
_print_sigset("dmeventd blocking ", &old);
#endif
DEBUGLOG("Completed waitevent task for %s.", thread->device.name);
@ -1355,78 +1365,89 @@ static int _get_timeout(struct message_data *message_data)
return (msg->data && msg->size) ? 0 : -ENOMEM;
}
/* Open fifos used for client communication. */
static int _open_fifos(struct dm_event_fifos *fifos)
static int _open_fifo(const char *path)
{
struct stat st;
int fd = -1;
/*
* FIXME Explicitly verify the code's requirement that path is secure:
* - All parent directories owned by root without group/other write access unless sticky.
*/
/* Create client fifo. */
(void) dm_prepare_selinux_context(fifos->client_path, S_IFIFO);
if ((mkfifo(fifos->client_path, 0600) == -1) && errno != EEXIST) {
log_sys_error("client mkfifo", fifos->client_path);
(void) dm_prepare_selinux_context(NULL, 0);
goto fail;
/* If path exists, only use it if it is root-owned fifo mode 0600 */
if ((lstat(path, &st) < 0)) {
if (errno != ENOENT) {
log_sys_error("stat", path);
return -1;
}
} else if (!S_ISFIFO(st.st_mode) || st.st_uid ||
(st.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO))) {
log_warn("WARNING: %s has wrong attributes: Replacing.", path);
if (unlink(path)) {
log_sys_error("unlink", path);
return -1;
}
}
/* Create server fifo. */
(void) dm_prepare_selinux_context(fifos->server_path, S_IFIFO);
if ((mkfifo(fifos->server_path, 0600) == -1) && errno != EEXIST) {
log_sys_error("server mkfifo", fifos->server_path);
/* Create fifo. */
(void) dm_prepare_selinux_context(path, S_IFIFO);
if ((mkfifo(path, 0600) == -1) && errno != EEXIST) {
log_sys_error("mkfifo", path);
(void) dm_prepare_selinux_context(NULL, 0);
goto fail;
}
(void) dm_prepare_selinux_context(NULL, 0);
/* Warn about wrong permissions if applicable */
if ((!stat(fifos->client_path, &st)) && (st.st_mode & 0777) != 0600)
log_warn("WARNING: Fixing wrong permissions on %s: %s.\n",
fifos->client_path, strerror(errno));
if ((!stat(fifos->server_path, &st)) && (st.st_mode & 0777) != 0600)
log_warn("WARNING: Fixing wrong permissions on %s: %s.\n",
fifos->server_path, strerror(errno));
/* If they were already there, make sure permissions are ok. */
if (chmod(fifos->client_path, 0600)) {
log_sys_error("chmod", fifos->client_path);
goto fail;
}
if (chmod(fifos->server_path, 0600)) {
log_sys_error("chmod", fifos->server_path);
goto fail;
}
/* Need to open read+write or we will block or fail */
if ((fifos->server = open(fifos->server_path, O_RDWR)) < 0) {
log_sys_error("server open", fifos->server_path);
if ((fd = open(path, O_RDWR)) < 0) {
log_sys_error("open", path);
goto fail;
}
if (fcntl(fifos->server, F_SETFD, FD_CLOEXEC) < 0) {
log_sys_error("fcntl(FD_CLOEXEC)", fifos->server_path);
/* Warn about wrong permissions if applicable */
if (fstat(fd, &st)) {
log_sys_error("fstat", path);
goto fail;
}
/* Need to open read+write for select() to work. */
if ((fifos->client = open(fifos->client_path, O_RDWR)) < 0) {
log_sys_error("client open", fifos->client_path);
if (!S_ISFIFO(st.st_mode) || st.st_uid ||
(st.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO))) {
log_error("%s: fifo has incorrect attributes", path);
goto fail;
}
if (fcntl(fifos->client, F_SETFD, FD_CLOEXEC) < 0) {
log_sys_error("fcntl(FD_CLOEXEC)", fifos->client_path);
if (fcntl(fd, F_SETFD, FD_CLOEXEC)) {
log_sys_error("fcntl(FD_CLOEXEC)", path);
goto fail;
}
return fd;
fail:
if ((fd >= 0) && close(fd))
log_sys_error("close", path);
return -1;
}
/* Open fifos used for client communication. */
static int _open_fifos(struct dm_event_fifos *fifos)
{
/* Create client fifo. */
if ((fifos->client = _open_fifo(fifos->client_path)) < 0)
goto fail;
/* Create server fifo. */
if ((fifos->server = _open_fifo(fifos->server_path)) < 0)
goto fail;
return 1;
fail:
if (fifos->server >= 0 && close(fifos->server))
log_sys_error("server close", fifos->server_path);
fail:
if (fifos->client >= 0 && close(fifos->client))
log_sys_error("client close", fifos->client_path);
log_sys_error("close", fifos->client_path);
return 0;
}
@ -1961,21 +1982,21 @@ static int _reinstate_registrations(struct dm_event_fifos *fifos)
!(dev_name = strtok(NULL, _delim)) ||
!(mask = strtok(NULL, _delim)) ||
!(timeout = strtok(NULL, _delim))) {
fprintf(stderr, _failed_parsing_msg);
fputs(_failed_parsing_msg, stderr);
continue;
}
errno = 0;
mask_value = strtoul(mask, &endp, 10);
if (errno || !endp || *endp) {
fprintf(stderr, _failed_parsing_msg);
fputs(_failed_parsing_msg, stderr);
continue;
}
errno = 0;
timeout_value = strtoul(timeout, &endp, 10);
if (errno || !endp || *endp) {
fprintf(stderr, _failed_parsing_msg);
fputs(_failed_parsing_msg, stderr);
continue;
}
@ -2185,7 +2206,7 @@ int main(int argc, char *argv[])
openlog("dmeventd", LOG_PID, LOG_DAEMON);
dm_event_log_set(_debug_level, _use_syslog);
dm_log_init(_dmeventd_log);
dm_log_with_errno_init(_libdm_log);
(void) dm_prepare_selinux_context(DMEVENTD_PIDFILE, S_IFREG);
if (dm_create_lockfile(DMEVENTD_PIDFILE) == 0)
@ -2260,9 +2281,9 @@ int main(int argc, char *argv[])
log_notice("dmeventd shutting down.");
if (close(fifos.client))
if (fifos.client >= 0 && close(fifos.client))
log_sys_error("client close", fifos.client_path);
if (close(fifos.server))
if (fifos.server >= 0 && close(fifos.server))
log_sys_error("server close", fifos.server_path);
if (_use_syslog)

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __DMEVENTD_DOT_H__

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dm-logging.h"
@ -412,28 +412,55 @@ static int _start_daemon(char *dmeventd_path, struct dm_event_fifos *fifos)
char default_dmeventd_path[] = DMEVENTD_PATH;
char *args[] = { dmeventd_path ? : default_dmeventd_path, NULL };
if (stat(fifos->client_path, &statbuf))
goto start_server;
/*
* FIXME Explicitly verify the code's requirement that client_path is secure:
* - All parent directories owned by root without group/other write access unless sticky.
*/
if (!S_ISFIFO(statbuf.st_mode)) {
log_error("%s is not a fifo.", fifos->client_path);
/* If client fifo path exists, only use it if it is root-owned fifo mode 0600 */
if ((lstat(fifos->client_path, &statbuf) < 0)) {
if (errno == ENOENT)
/* Jump ahead if fifo does not already exist. */
goto start_server;
else {
log_sys_error("stat", fifos->client_path);
return 0;
}
} else if (!S_ISFIFO(statbuf.st_mode)) {
log_error("%s must be a fifo.", fifos->client_path);
return 0;
} else if (statbuf.st_uid) {
log_error("%s must be owned by uid 0.", fifos->client_path);
return 0;
} else if (statbuf.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO)) {
log_error("%s must have mode 0600.", fifos->client_path);
return 0;
}
/* Anyone listening? If not, errno will be ENXIO */
fifos->client = open(fifos->client_path, O_WRONLY | O_NONBLOCK);
if (fifos->client >= 0) {
/* Should never happen if all the above checks passed. */
if ((fstat(fifos->client, &statbuf) < 0) ||
!S_ISFIFO(statbuf.st_mode) || statbuf.st_uid ||
(statbuf.st_mode & (S_IEXEC | S_IRWXG | S_IRWXO))) {
log_error("%s is no longer a secure root-owned fifo with mode 0600.", fifos->client_path);
if (close(fifos->client))
log_sys_debug("close", fifos->client_path);
return 0;
}
/* server is running and listening */
if (close(fifos->client))
log_sys_debug("close", fifos->client_path);
return 1;
} else if (errno != ENXIO) {
} else if (errno != ENXIO && errno != ENOENT) {
/* problem */
log_sys_error("open", fifos->client_path);
return 0;
}
start_server:
start_server:
/* server is not running */
if ((args[0][0] == '/') && stat(args[0], &statbuf)) {
@ -587,8 +614,8 @@ static int _do_event(int cmd, char *dmeventd_path, struct dm_event_daemon_messag
};
if (!_init_client(dmeventd_path, &fifos)) {
stack;
return -ESRCH;
ret = -ESRCH;
goto_out;
}
ret = daemon_talk(&fifos, msg, DM_EVENT_CMD_HELLO, NULL, NULL, 0, 0);
@ -598,7 +625,7 @@ static int _do_event(int cmd, char *dmeventd_path, struct dm_event_daemon_messag
if (!ret)
ret = daemon_talk(&fifos, msg, cmd, dso_name, dev_name, evmask, timeout);
out:
/* what is the opposite of init? */
fini_fifos(&fifos);
@ -727,6 +754,7 @@ int dm_event_get_registered_device(struct dm_event_handler *dmevh, int next)
uuid = dm_task_get_uuid(dmt);
/* FIXME Distinguish errors connecting to daemon */
if (_do_event(next ? DM_EVENT_CMD_GET_NEXT_REGISTERED_DEVICE :
DM_EVENT_CMD_GET_REGISTERED_DEVICE, dmevh->dmeventd_path,
&msg, dmevh->dso, uuid, dmevh->mask, 0)) {
@ -827,9 +855,9 @@ int dm_event_get_version(struct dm_event_fifos *fifos, int *version) {
return 1;
}
void dm_event_log_set(int debug_level, int use_syslog)
void dm_event_log_set(int debug_log_level, int use_syslog)
{
_debug_level = debug_level;
_debug_level = debug_log_level;
_use_syslog = use_syslog;
}
@ -837,28 +865,38 @@ void dm_event_log(const char *subsys, int level, const char *file,
int line, int dm_errno_or_class,
const char *format, va_list ap)
{
static int _abort_on_internal_errors = -1;
static pthread_mutex_t _log_mutex = PTHREAD_MUTEX_INITIALIZER;
static time_t start = 0;
const char *indent = "";
FILE *stream = stdout;
int prio = -1;
FILE *stream = log_stderr(level) ? stderr : stdout;
int prio;
time_t now;
int log_with_debug = 0;
switch (level & ~(_LOG_STDERR | _LOG_ONCE)) {
if (subsys[0] == '#') {
/* Subsystems starting with '#' are logged
* only when debugging is enabled. */
log_with_debug++;
subsys++;
}
switch (log_level(level)) {
case _LOG_DEBUG:
/* Never shown without -ddd */
if (_debug_level < 3)
return;
prio = LOG_DEBUG;
indent = " ";
break;
case _LOG_INFO:
if (_debug_level < 2)
if (log_with_debug && _debug_level < 2)
return;
prio = LOG_INFO;
indent = " ";
break;
case _LOG_NOTICE:
if (_debug_level < 1)
if (log_with_debug && _debug_level < 1)
return;
prio = LOG_NOTICE;
indent = " ";
@ -884,12 +922,13 @@ void dm_event_log(const char *subsys, int level, const char *file,
if (!start)
start = now;
now -= start;
fprintf(stream, "[%2d:%02d] %8x:%-6s%s",
(int)now / 60, (int)now % 60,
// TODO: Maybe use shorter ID
// ((int)(pthread_self()) >> 6) & 0xffff,
(int)pthread_self(), subsys,
(_debug_level > 3) ? "" : indent);
if (_debug_level)
fprintf(stream, "[%2d:%02d] %8x:%-6s%s",
(int)now / 60, (int)now % 60,
// TODO: Maybe use shorter ID
// ((int)(pthread_self()) >> 6) & 0xffff,
(int)pthread_self(), subsys,
(_debug_level > 3) ? "" : indent);
if (_debug_level > 3)
fprintf(stream, "%28s:%4d %s", file, line, indent);
vfprintf(stream, _(format), ap);
@ -898,6 +937,15 @@ void dm_event_log(const char *subsys, int level, const char *file,
}
pthread_mutex_unlock(&_log_mutex);
if (_abort_on_internal_errors < 0)
/* Set when env DM_ABORT_ON_INTERNAL_ERRORS is not "0" */
_abort_on_internal_errors =
strcmp(getenv("DM_ABORT_ON_INTERNAL_ERRORS") ? : "0", "0");
if (_abort_on_internal_errors &&
!strncmp(format, INTERNAL_ERROR, sizeof(INTERNAL_ERROR) - 1))
abort();
}
#if 0 /* left out for now */

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
@ -106,7 +106,7 @@ int dm_event_register_handler(const struct dm_event_handler *dmevh);
int dm_event_unregister_handler(const struct dm_event_handler *dmevh);
/* Set debug level for logging, and whether to log on stdout/stderr or syslog */
void dm_event_log_set(int debug_level, int use_syslog);
void dm_event_log_set(int debug_log_level, int use_syslog);
/* Log messages acroding to current debug level */
__attribute__((format(printf, 6, 0)))

View File

@ -10,7 +10,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "lib.h"
@ -32,7 +32,7 @@ static int _register_count = 0;
static struct dm_pool *_mem_pool = NULL;
static void *_lvm_handle = NULL;
DM_EVENT_LOG_FN("lvm")
DM_EVENT_LOG_FN("#lvm")
static void _lvm2_print_log(int level, const char *file, int line,
int dm_errno_or_class, const char *msg)
@ -121,6 +121,7 @@ int dmeventd_lvm2_run(const char *cmdline)
int dmeventd_lvm2_command(struct dm_pool *mem, char *buffer, size_t size,
const char *cmd, const char *device)
{
static char _internal_prefix[] = "_dmeventd_";
char *vg = NULL, *lv = NULL, *layer;
int r;
@ -135,6 +136,21 @@ int dmeventd_lvm2_command(struct dm_pool *mem, char *buffer, size_t size,
(layer = strstr(lv, "_mlog")))
*layer = '\0';
if (!strncmp(cmd, _internal_prefix, sizeof(_internal_prefix) - 1)) {
dmeventd_lvm2_lock();
/* output of internal command passed via env var */
if (!dmeventd_lvm2_run(cmd))
cmd = NULL;
else if ((cmd = getenv(cmd)))
cmd = dm_pool_strdup(mem, cmd); /* copy with lock */
dmeventd_lvm2_unlock();
if (!cmd) {
log_error("Unable to find configured command.");
return 0;
}
}
r = dm_snprintf(buffer, size, "%s %s/%s", cmd, vg, lv);
dm_pool_free(mem, vg);

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*

View File

@ -10,7 +10,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2005-2015 Red Hat, Inc. All rights reserved.
* Copyright (C) 2005-2017 Red Hat, Inc. All rights reserved.
*
* This file is part of LVM2.
*
@ -9,13 +9,13 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "lib.h"
#include "libdevmapper-event.h"
#include "dmeventd_lvm.h"
#include "defaults.h"
#include "activate.h" /* For TARGET_NAME* */
/* FIXME Reformat to 80 char lines. */
@ -25,14 +25,14 @@
struct dso_state {
struct dm_pool *mem;
char cmd_lvscan[512];
char cmd_lvconvert[512];
};
DM_EVENT_LOG_FN("mirr")
static int _process_status_code(const char status_code, const char *dev_name,
const char *dev_type, int r)
static void _process_status_code(dm_status_mirror_health_t health,
uint32_t major, uint32_t minor,
const char *dev_type, int *r)
{
/*
* A => Alive - No failures
@ -42,109 +42,73 @@ static int _process_status_code(const char status_code, const char *dev_name,
* R => Read - A read failure occurred, mirror data unaffected
* U => Unclassified failure (bug)
*/
if (status_code == 'F') {
log_error("%s device %s flush failed.", dev_type, dev_name);
r = ME_FAILURE;
} else if (status_code == 'S')
log_error("%s device %s sync failed.", dev_type, dev_name);
else if (status_code == 'R')
log_error("%s device %s read failed.", dev_type, dev_name);
else if (status_code != 'A') {
log_error("%s device %s has failed (%c).",
dev_type, dev_name, status_code);
r = ME_FAILURE;
switch (health) {
case DM_STATUS_MIRROR_ALIVE:
return;
case DM_STATUS_MIRROR_FLUSH_FAILED:
log_error("%s device %u:%u flush failed.",
dev_type, major, minor);
*r = ME_FAILURE;
break;
case DM_STATUS_MIRROR_SYNC_FAILED:
log_error("%s device %u:%u sync failed.",
dev_type, major, minor);
break;
case DM_STATUS_MIRROR_READ_FAILED:
log_error("%s device %u:%u read failed.",
dev_type, major, minor);
break;
default:
log_error("%s device %u:%u has failed (%c).",
dev_type, major, minor, (char)health);
*r = ME_FAILURE;
break;
}
}
static int _get_mirror_event(struct dso_state *state, char *params)
{
int r = ME_INSYNC;
unsigned i;
struct dm_status_mirror *ms;
if (!dm_get_status_mirror(state->mem, params, &ms)) {
log_error("Unable to parse mirror status string.");
return ME_IGNORE;
}
return r;
}
static int _get_mirror_event(char *params)
{
int i, r = ME_INSYNC;
char **args = NULL;
char *dev_status_str;
char *log_status_str;
char *sync_str;
char *p = NULL;
int log_argc, num_devs;
/*
* dm core parms: 0 409600 mirror
* Mirror core parms: 2 253:4 253:5 400/400
* New-style failure params: 1 AA
* New-style log params: 3 cluster 253:3 A
* or 3 disk 253:3 A
* or 1 core
*/
/* number of devices */
if (!dm_split_words(params, 1, 0, &p))
goto out_parse;
if (!(num_devs = atoi(p)) ||
(num_devs > DEFAULT_MIRROR_MAX_IMAGES) || (num_devs < 0))
goto out_parse;
p += strlen(p) + 1;
/* devices names + "400/400" + "1 AA" + 1 or 3 log parms + NULL */
args = dm_malloc((num_devs + 7) * sizeof(char *));
if (!args || dm_split_words(p, num_devs + 7, 0, args) < num_devs + 5)
goto out_parse;
/* FIXME: Code differs from lib/mirror/mirrored.c */
dev_status_str = args[2 + num_devs];
log_argc = atoi(args[3 + num_devs]);
log_status_str = args[3 + num_devs + log_argc];
sync_str = args[num_devs];
/* Check for bad mirror devices */
for (i = 0; i < num_devs; i++)
r = _process_status_code(dev_status_str[i], args[i],
i ? "Secondary mirror" : "Primary mirror", r);
for (i = 0; i < ms->dev_count; ++i)
_process_status_code(ms->devs[i].health,
ms->devs[i].major, ms->devs[i].minor,
i ? "Secondary mirror" : "Primary mirror", &r);
/* Check for bad disk log device */
if (log_argc > 1)
r = _process_status_code(log_status_str[0],
args[2 + num_devs + log_argc],
"Log", r);
for (i = 0; i < ms->log_count; ++i)
_process_status_code(ms->logs[i].health,
ms->logs[i].major, ms->logs[i].minor,
"Log", &r);
if (r == ME_FAILURE)
goto out;
/* Ignore if not in-sync */
if ((r == ME_INSYNC) && (ms->insync_regions != ms->total_regions))
r = ME_IGNORE;
p = strstr(sync_str, "/");
if (p) {
p[0] = '\0';
if (strcmp(sync_str, p+1))
r = ME_IGNORE;
p[0] = '/';
} else
goto out_parse;
dm_pool_free(state->mem, ms);
out:
dm_free(args);
return r;
out_parse:
dm_free(args);
log_error("Unable to parse mirror status string.");
return ME_IGNORE;
}
static int _remove_failed_devices(const char *cmd_lvscan, const char *cmd_lvconvert)
static int _remove_failed_devices(const char *cmd_lvconvert, const char *device)
{
int r;
if (!dmeventd_lvm2_run_with_lock(cmd_lvscan))
log_info("Re-scan of mirrored device failed.");
/* if repair goes OK, report success even if lvscan has failed */
r = dmeventd_lvm2_run_with_lock(cmd_lvconvert);
if (!dmeventd_lvm2_run_with_lock(cmd_lvconvert)) {
log_error("Repair of mirrored device %s failed.", device);
return 0;
}
log_info("Repair of mirrored device %s.",
(r) ? "finished successfully" : "failed");
log_info("Repair of mirrored device %s finished successfully.", device);
return r;
return 1;
}
void process_event(struct dm_task *dmt,
@ -167,12 +131,12 @@ void process_event(struct dm_task *dmt,
continue;
}
if (strcmp(target_type, "mirror")) {
if (strcmp(target_type, TARGET_NAME_MIRROR)) {
log_info("%s has unmirrored portion.", device);
continue;
}
switch(_get_mirror_event(params)) {
switch(_get_mirror_event(state, params)) {
case ME_INSYNC:
/* FIXME: all we really know is that this
_part_ of the device is in sync
@ -182,8 +146,7 @@ void process_event(struct dm_task *dmt,
break;
case ME_FAILURE:
log_error("Device failure in %s.", device);
if (!_remove_failed_devices(state->cmd_lvscan,
state->cmd_lvconvert))
if (!_remove_failed_devices(state->cmd_lvconvert, device))
/* FIXME Why are all the error return codes unused? Get rid of them? */
log_error("Failed to remove faulty devices in %s.",
device);
@ -197,7 +160,7 @@ void process_event(struct dm_task *dmt,
break;
default:
/* FIXME Provide value then! */
log_info("Unknown event received.");
log_warn("WARNING: %s received unknown event.", device);
}
} while (next);
}
@ -213,17 +176,10 @@ int register_device(const char *device,
if (!dmeventd_lvm2_init_with_pool("mirror_state", state))
goto_bad;
if (!dmeventd_lvm2_command(state->mem, state->cmd_lvscan, sizeof(state->cmd_lvscan),
"lvscan --cache", device)) {
dmeventd_lvm2_exit_with_pool(state);
goto_bad;
}
/* CANNOT use --config as this disables cached content */
if (!dmeventd_lvm2_command(state->mem, state->cmd_lvconvert, sizeof(state->cmd_lvconvert),
"lvconvert --repair --use-policies", device)) {
dmeventd_lvm2_exit_with_pool(state);
"lvconvert --repair --use-policies", device))
goto_bad;
}
*user = state;
@ -233,6 +189,9 @@ int register_device(const char *device,
bad:
log_error("Failed to monitor mirror %s.", device);
if (state)
dmeventd_lvm2_exit_with_pool(state);
return 0;
}

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2005-2015 Red Hat, Inc. All rights reserved.
* Copyright (C) 2005-2017 Red Hat, Inc. All rights reserved.
*
* This file is part of LVM2.
*
@ -9,18 +9,23 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "lib.h"
#include "defaults.h"
#include "dmeventd_lvm.h"
#include "libdevmapper-event.h"
/* Hold enough elements for the mximum number of RAID images */
#define RAID_DEVS_ELEMS ((DEFAULT_RAID_MAX_IMAGES + 63) / 64)
struct dso_state {
struct dm_pool *mem;
char cmd_lvscan[512];
char cmd_lvconvert[512];
uint64_t raid_devs[RAID_DEVS_ELEMS];
int failed;
int warned;
};
DM_EVENT_LOG_FN("raid")
@ -31,32 +36,70 @@ static int _process_raid_event(struct dso_state *state, char *params, const char
{
struct dm_status_raid *status;
const char *d;
int dead = 0, r = 1;
uint32_t dev;
if (!dm_get_status_raid(state->mem, params, &status)) {
log_error("Failed to process status line for %s.", device);
return 0;
}
if ((d = strchr(status->dev_health, 'D'))) {
d = status->dev_health;
while ((d = strchr(d, 'D'))) {
dev = (uint32_t)(d - status->dev_health);
if (!(state->raid_devs[dev / 64] & (UINT64_C(1) << (dev % 64)))) {
state->raid_devs[dev / 64] |= (UINT64_C(1) << (dev % 64));
log_warn("WARNING: Device #%u of %s array, %s, has failed.",
dev, status->raid_type, device);
}
d++;
dead = 1;
}
/*
* if we are converting from non-RAID to RAID (e.g. linear -> raid1)
* and too many original devices die, such that we cannot continue
* the "recover" operation, the sync action will go to "idle", the
* unsynced devs will remain at 'a', and the original devices will
* NOT SWITCH TO 'D', but will remain at 'A' - hoping to be revived.
*
* This is simply the way the kernel works...
*/
if (!strcmp(status->sync_action, "idle") &&
(status->dev_health[0] == 'a') &&
(status->insync_regions < status->total_regions)) {
log_error("Primary sources for new RAID, %s, have failed.",
device);
dead = 1; /* run it through LVM repair */
}
if (dead) {
if (status->insync_regions < status->total_regions) {
if (!state->warned) {
state->warned = 1;
log_warn("WARNING: waiting for resynchronization to finish "
"before initiating repair on RAID device %s.", device);
}
goto out; /* Not yet done syncing with accessible devices */
}
if (state->failed)
goto out; /* already reported */
log_error("Device #%d of %s array, %s, has failed.",
(int)(d - status->dev_health),
status->raid_type, device);
state->failed = 1;
if (!dmeventd_lvm2_run_with_lock(state->cmd_lvscan))
log_warn("WARNING: Re-scan of RAID device %s failed.", device);
/* if repair goes OK, report success even if lvscan has failed */
if (!dmeventd_lvm2_run_with_lock(state->cmd_lvconvert)) {
log_info("Repair of RAID device %s failed.", device);
dm_pool_free(state->mem, status);
return 0;
log_error("Repair of RAID device %s failed.", device);
r = 0;
}
} else {
state->failed = 0;
if (status->insync_regions == status->total_regions)
memset(&state->raid_devs, 0, sizeof(state->raid_devs));
log_info("%s array, %s, is %s in-sync.",
status->raid_type, device,
(status->insync_regions == status->total_regions) ? "now" : "not");
@ -64,7 +107,7 @@ static int _process_raid_event(struct dso_state *state, char *params, const char
out:
dm_pool_free(state->mem, status);
return 1;
return r;
}
void process_event(struct dm_task *dmt,
@ -109,14 +152,9 @@ int register_device(const char *device,
if (!dmeventd_lvm2_init_with_pool("raid_state", state))
goto_bad;
if (!dmeventd_lvm2_command(state->mem, state->cmd_lvscan, sizeof(state->cmd_lvscan),
"lvscan --cache", device) ||
!dmeventd_lvm2_command(state->mem, state->cmd_lvconvert, sizeof(state->cmd_lvconvert),
"lvconvert --config devices{ignore_suspended_devices=1} "
"--repair --use-policies", device)) {
dmeventd_lvm2_exit_with_pool(state);
if (!dmeventd_lvm2_command(state->mem, state->cmd_lvconvert, sizeof(state->cmd_lvconvert),
"lvconvert --repair --use-policies", device))
goto_bad;
}
*user = state;
@ -126,6 +164,9 @@ int register_device(const char *device,
bad:
log_error("Failed to monitor RAID %s.", device);
if (state)
dmeventd_lvm2_exit_with_pool(state);
return 0;
}

View File

@ -10,7 +10,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -9,13 +9,14 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "lib.h"
#include "dmeventd_lvm.h"
#include "libdevmapper-event.h"
#include <sys/sysmacros.h>
#include <sys/wait.h>
#include <stdarg.h>
#include <pthread.h>
@ -148,8 +149,8 @@ static void _umount(const char *device, int major, int minor)
continue; /* can't stat, skip this one */
if (S_ISBLK(st.st_mode) &&
major(st.st_rdev) == major &&
minor(st.st_rdev) == minor) {
(int) major(st.st_rdev) == major &&
(int) minor(st.st_rdev) == minor) {
log_error("Unmounting invalid snapshot %s from %s.", device, words[1]);
if (!_run(UMOUNT_COMMAND, "-fl", words[1], NULL))
log_error("Failed to umount snapshot %s from %s: %s.",
@ -230,7 +231,7 @@ void process_event(struct dm_task *dmt,
if (percent >= WARNING_THRESH) /* Print a warning to syslog. */
log_warn("WARNING: Snapshot %s is now %.2f%% full.",
device, dm_percent_to_float(percent));
device, dm_percent_to_round_float(percent, 2));
/* Try to extend the snapshot, in accord with user-set policies */
if (!_extend(state->cmd_lvextend))
@ -253,10 +254,8 @@ int register_device(const char *device,
if (!dmeventd_lvm2_command(state->mem, state->cmd_lvextend,
sizeof(state->cmd_lvextend),
"lvextend --use-policies", device)) {
dmeventd_lvm2_exit_with_pool(state);
"lvextend --use-policies", device))
goto_bad;
}
state->percent_check = CHECK_MINIMUM;
*user = state;
@ -267,6 +266,9 @@ int register_device(const char *device,
bad:
log_error("Failed to monitor snapshot %s.", device);
if (state)
dmeventd_lvm2_exit_with_pool(state);
return 0;
}

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2011-2015 Red Hat, Inc. All rights reserved.
* Copyright (C) 2011-2017 Red Hat, Inc. All rights reserved.
*
* This file is part of LVM2.
*
@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "lib.h" /* using here lvm log */
@ -18,7 +18,6 @@
#include <sys/wait.h>
#include <stdarg.h>
#include <pthread.h>
/* TODO - move this mountinfo code into library to be reusable */
#ifdef __linux__
@ -30,6 +29,9 @@
/* First warning when thin data or metadata is 80% full. */
#define WARNING_THRESH (DM_PERCENT_1 * 80)
/* Umount thin LVs when thin data or metadata LV is >=
* and lvextend --use-policies has failed. */
#define UMOUNT_THRESH (DM_PERCENT_1 * 95)
/* Run a check every 5%. */
#define CHECK_STEP (DM_PERCENT_1 * 5)
/* Do not bother checking thin data or metadata is less than 50% full. */
@ -37,221 +39,121 @@
#define UMOUNT_COMMAND "/bin/umount"
#define MAX_FAILS (10)
#define MAX_FAILS (256) /* ~42 mins between cmd call retry with 10s delay */
#define THIN_DEBUG 0
struct dso_state {
struct dm_pool *mem;
int metadata_percent_check;
int metadata_percent;
int data_percent_check;
int data_percent;
uint64_t known_metadata_size;
uint64_t known_data_size;
unsigned fails;
char cmd_str[1024];
unsigned max_fails;
int restore_sigset;
sigset_t old_sigset;
pid_t pid;
char *argv[3];
char *cmd_str;
};
DM_EVENT_LOG_FN("thin")
/* Get dependencies for device, and try to find matching device */
static int _has_deps(const char *name, int tp_major, int tp_minor, int *dev_minor)
{
struct dm_task *dmt;
const struct dm_deps *deps;
struct dm_info info;
int major, minor;
int r = 0;
#define UUID_PREFIX "LVM-"
if (!(dmt = dm_task_create(DM_DEVICE_DEPS)))
static int _run_command(struct dso_state *state)
{
char val[3][36];
char *env[] = { val[0], val[1], val[2], NULL };
int i;
/* Mark for possible lvm2 command we are running from dmeventd
* lvm2 will not try to talk back to dmeventd while processing it */
(void) dm_snprintf(val[0], sizeof(val[0]), "LVM_RUN_BY_DMEVENTD=1");
if (state->data_percent) {
/* Prepare some known data to env vars for easy use */
(void) dm_snprintf(val[1], sizeof(val[1]), "DMEVENTD_THIN_POOL_DATA=%d",
state->data_percent / DM_PERCENT_1);
(void) dm_snprintf(val[2], sizeof(val[2]), "DMEVENTD_THIN_POOL_METADATA=%d",
state->metadata_percent / DM_PERCENT_1);
} else {
/* For an error event it's for a user to check status and decide */
env[1] = NULL;
log_debug("Error event processing.");
}
log_verbose("Executing command: %s", state->cmd_str);
/* TODO:
* Support parallel run of 'task' and it's waitpid maintainence
* ATM we can't handle signaling of SIGALRM
* as signalling is not allowed while 'process_event()' is running
*/
if (!(state->pid = fork())) {
/* child */
(void) close(0);
for (i = 3; i < 255; ++i) (void) close(i);
execve(state->argv[0], state->argv, env);
_exit(errno);
} else if (state->pid == -1) {
log_error("Can't fork command %s.", state->cmd_str);
state->fails = 1;
return 0;
if (!dm_task_set_name(dmt, name))
goto out;
if (!dm_task_no_open_count(dmt))
goto out;
if (!dm_task_run(dmt))
goto out;
if (!dm_task_get_info(dmt, &info))
goto out;
if (!(deps = dm_task_get_deps(dmt)))
goto out;
if (!info.exists || deps->count != 1)
goto out;
major = (int) MAJOR(deps->device[0]);
minor = (int) MINOR(deps->device[0]);
if ((major != tp_major) || (minor != tp_minor))
goto out;
*dev_minor = info.minor;
#if THIN_DEBUG
{
char dev_name[PATH_MAX];
if (dm_device_get_name(major, minor, 0, dev_name, sizeof(dev_name)))
log_debug("Found %s (%u:%u) depends on %s.",
name, major, *dev_minor, dev_name);
}
#endif
r = 1;
out:
dm_task_destroy(dmt);
return r;
}
/* Get all active devices */
static int _find_all_devs(dm_bitset_t bs, int tp_major, int tp_minor)
{
struct dm_task *dmt;
struct dm_names *names;
unsigned next = 0;
int minor, r = 1;
if (!(dmt = dm_task_create(DM_DEVICE_LIST)))
return 0;
if (!dm_task_run(dmt)) {
r = 0;
goto out;
}
if (!(names = dm_task_get_names(dmt))) {
r = 0;
goto out;
}
if (!names->dev)
goto out;
do {
names = (struct dm_names *)((char *) names + next);
if (_has_deps(names->name, tp_major, tp_minor, &minor))
dm_bit_set(bs, minor);
next = names->next;
} while (next);
out:
dm_task_destroy(dmt);
return r;
}
static int _run(const char *cmd, ...)
{
va_list ap;
int argc = 1; /* for argv[0], i.e. cmd */
int i = 0;
const char **argv;
pid_t pid = fork();
int status;
if (pid == 0) { /* child */
va_start(ap, cmd);
while (va_arg(ap, const char *))
++argc;
va_end(ap);
/* + 1 for the terminating NULL */
argv = alloca(sizeof(const char *) * (argc + 1));
argv[0] = cmd;
va_start(ap, cmd);
while ((argv[++i] = va_arg(ap, const char *)));
va_end(ap);
execvp(cmd, (char **)argv);
log_sys_error("exec", cmd);
exit(127);
}
if (pid > 0) { /* parent */
if (waitpid(pid, &status, 0) != pid)
return 0; /* waitpid failed */
if (!WIFEXITED(status) || WEXITSTATUS(status))
return 0; /* the child failed */
}
if (pid < 0)
return 0; /* fork failed */
return 1; /* all good */
}
struct mountinfo_s {
const char *device;
struct dm_info info;
dm_bitset_t minors; /* Bitset for active thin pool minors */
};
static int _umount_device(char *buffer, unsigned major, unsigned minor,
char *target, void *cb_data)
{
struct mountinfo_s *data = cb_data;
if ((major == data->info.major) && dm_bit(data->minors, minor)) {
log_info("Unmounting thin volume %s from %s.",
data->device, target);
if (!_run(UMOUNT_COMMAND, "-fl", target, NULL))
log_error("Failed to umount thin %s from %s: %s.",
data->device, target, strerror(errno));
}
return 1;
}
/*
* Find all thin pool users and try to umount them.
* TODO: work with read-only thin pool support
*/
static void _umount(struct dm_task *dmt)
{
/* TODO: Convert to use hash to reduce memory usage */
static const size_t MINORS = (1U << 20); /* 20 bit */
struct mountinfo_s data = { NULL };
if (!dm_task_get_info(dmt, &data.info))
return;
data.device = dm_task_get_name(dmt);
if (!(data.minors = dm_bitset_create(NULL, MINORS))) {
log_error("Failed to allocate bitset. Not unmounting %s.", data.device);
goto out;
}
if (!_find_all_devs(data.minors, data.info.major, data.info.minor)) {
log_error("Failed to detect mounted volumes for %s.", data.device);
goto out;
}
if (!dm_mountinfo_read(_umount_device, &data)) {
log_error("Could not parse mountinfo file.");
goto out;
}
out:
if (data.minors)
dm_bitset_destroy(data.minors);
}
static void _use_policy(struct dm_task *dmt, struct dso_state *state)
static int _use_policy(struct dm_task *dmt, struct dso_state *state)
{
#if THIN_DEBUG
log_info("dmeventd executes: %s.", state->cmd_str);
log_debug("dmeventd executes: %s.", state->cmd_str);
#endif
if (state->argv[0])
return _run_command(state);
if (!dmeventd_lvm2_run_with_lock(state->cmd_str)) {
log_error("Failed to extend thin pool %s.",
dm_task_get_name(dmt));
_umount(dmt);
state->fails++;
} else
state->fails = 0;
log_error("Failed command for %s.", dm_task_get_name(dmt));
state->fails = 1;
return 0;
}
state->fails = 0;
return 1;
}
/* Check if executed command has finished
* Only 1 command may run */
static int _wait_for_pid(struct dso_state *state)
{
int status = 0;
if (state->pid == -1)
return 1;
if (!waitpid(state->pid, &status, WNOHANG))
return 0;
/* Wait for finish */
if (WIFEXITED(status)) {
log_verbose("Child %d exited with status %d.",
state->pid, WEXITSTATUS(status));
state->fails = WEXITSTATUS(status) ? 1 : 0;
} else {
if (WIFSIGNALED(status))
log_verbose("Child %d was terminated with status %d.",
state->pid, WTERMSIG(status));
state->fails = 1;
}
state->pid = -1;
return 1;
}
void process_event(struct dm_task *dmt,
@ -259,7 +161,6 @@ void process_event(struct dm_task *dmt,
void **user)
{
const char *device = dm_task_get_name(dmt);
int percent;
struct dso_state *state = *user;
struct dm_status_thin_pool *tps = NULL;
void *next = NULL;
@ -267,16 +168,48 @@ void process_event(struct dm_task *dmt,
char *target_type = NULL;
char *params;
int needs_policy = 0;
struct dm_task *new_dmt = NULL;
#if 0
/* No longer monitoring, waiting for remove */
if (!state->meta_percent_check && !state->data_percent_check)
return;
#if THIN_DEBUG
log_debug("Watch for tp-data:%.2f%% tp-metadata:%.2f%%.",
dm_percent_to_round_float(state->data_percent_check, 2),
dm_percent_to_round_float(state->metadata_percent_check, 2));
#endif
if (!_wait_for_pid(state)) {
log_warn("WARNING: Skipping event, child %d is still running (%s).",
state->pid, state->cmd_str);
return;
}
if (event & DM_EVENT_DEVICE_ERROR) {
/* Error -> no need to check and do instant resize */
_use_policy(dmt, state);
goto out;
state->data_percent = state->metadata_percent = 0;
if (_use_policy(dmt, state))
goto out;
stack;
/*
* Rather update oldish status
* since after 'command' processing
* percentage info could have changed a lot.
* If we would get above UMOUNT_THRESH
* we would wait for next sigalarm.
*/
if (!(new_dmt = dm_task_create(DM_DEVICE_STATUS)))
goto_out;
if (!dm_task_set_uuid(new_dmt, dm_task_get_uuid(dmt)))
goto_out;
/* Non-blocking status read */
if (!dm_task_no_flush(new_dmt))
log_warn("WARNING: Can't set no_flush for dm status.");
if (!dm_task_run(new_dmt))
goto_out;
dmt = new_dmt;
}
dm_get_next_target(dmt, next, &start, &length, &target_type, &params);
@ -288,7 +221,6 @@ void process_event(struct dm_task *dmt,
if (!dm_get_status_thin_pool(state->mem, params, &tps)) {
log_error("Failed to parse status.");
_umount(dmt);
goto out;
}
@ -303,41 +235,66 @@ void process_event(struct dm_task *dmt,
if (state->known_metadata_size != tps->total_metadata_blocks) {
state->metadata_percent_check = CHECK_MINIMUM;
state->known_metadata_size = tps->total_metadata_blocks;
state->fails = 0;
}
if (state->known_data_size != tps->total_data_blocks) {
state->data_percent_check = CHECK_MINIMUM;
state->known_data_size = tps->total_data_blocks;
state->fails = 0;
}
percent = dm_make_percent(tps->used_metadata_blocks, tps->total_metadata_blocks);
if (percent >= state->metadata_percent_check) {
/*
* Usage has raised more than CHECK_STEP since the last
* time. Run actions.
*/
state->metadata_percent_check = (percent / CHECK_STEP) * CHECK_STEP + CHECK_STEP;
/*
* Trigger action when threshold boundary is exceeded.
* Report 80% threshold warning when it's used above 80%.
* Only 100% is exception as it cannot be surpased so policy
* action is called for: >50%, >55% ... >95%, 100%
*/
state->metadata_percent = dm_make_percent(tps->used_metadata_blocks, tps->total_metadata_blocks);
if ((state->metadata_percent > WARNING_THRESH) &&
(state->metadata_percent > state->metadata_percent_check))
log_warn("WARNING: Thin pool %s metadata is now %.2f%% full.",
device, dm_percent_to_round_float(state->metadata_percent, 2));
if (state->metadata_percent > CHECK_MINIMUM) {
/* Run action when usage raised more than CHECK_STEP since the last time */
if (state->metadata_percent > state->metadata_percent_check)
needs_policy = 1;
state->metadata_percent_check = (state->metadata_percent / CHECK_STEP + 1) * CHECK_STEP;
if (state->metadata_percent_check == DM_PERCENT_100)
state->metadata_percent_check--; /* Can't get bigger then 100% */
} else
state->metadata_percent_check = CHECK_MINIMUM;
/* FIXME: extension of metadata needs to be written! */
if (percent >= WARNING_THRESH) /* Print a warning to syslog. */
log_warn("WARNING: Thin pool %s metadata is now %.2f%% full.",
device, dm_percent_to_float(percent));
needs_policy = 1;
}
state->data_percent = dm_make_percent(tps->used_data_blocks, tps->total_data_blocks);
if ((state->data_percent > WARNING_THRESH) &&
(state->data_percent > state->data_percent_check))
log_warn("WARNING: Thin pool %s data is now %.2f%% full.",
device, dm_percent_to_round_float(state->data_percent, 2));
if (state->data_percent > CHECK_MINIMUM) {
/* Run action when usage raised more than CHECK_STEP since the last time */
if (state->data_percent > state->data_percent_check)
needs_policy = 1;
state->data_percent_check = (state->data_percent / CHECK_STEP + 1) * CHECK_STEP;
if (state->data_percent_check == DM_PERCENT_100)
state->data_percent_check--; /* Can't get bigger then 100% */
} else
state->data_percent_check = CHECK_MINIMUM;
percent = dm_make_percent(tps->used_data_blocks, tps->total_data_blocks);
if (percent >= state->data_percent_check) {
/*
* Usage has raised more than CHECK_STEP since
* the last time. Run actions.
*/
state->data_percent_check = (percent / CHECK_STEP) * CHECK_STEP + CHECK_STEP;
if (percent >= WARNING_THRESH) /* Print a warning to syslog. */
log_warn("WARNING: Thin pool %s data is now %.2f%% full.",
device, dm_percent_to_float(percent));
needs_policy = 1;
}
/* Reduce number of _use_policy() calls by power-of-2 factor till frequency of MAX_FAILS is reached.
* Avoids too high number of error retries, yet shows some status messages in log regularly.
* i.e. PV could have been pvmoved and VG/LV was locked for a while...
*/
if (state->fails) {
if (state->fails++ <= state->max_fails) {
log_debug("Postponing frequently failing policy (%u <= %u).",
state->fails - 1, state->max_fails);
return;
}
if (state->max_fails < MAX_FAILS)
state->max_fails <<= 1;
state->fails = needs_policy = 1; /* Retry failing command */
} else
state->max_fails = 1; /* Reset on success */
if (needs_policy)
_use_policy(dmt, state);
@ -345,12 +302,43 @@ out:
if (tps)
dm_pool_free(state->mem, tps);
if (state->fails >= MAX_FAILS) {
log_warn("WARNING: Dropping monitoring of %s. "
"lvm2 command fails too often (%u times in raw).",
device, state->fails);
pthread_kill(pthread_self(), SIGALRM);
}
if (new_dmt)
dm_task_destroy(new_dmt);
}
/* Handle SIGCHLD for a thread */
static void _sig_child(int signum __attribute__((unused)))
{
/* empty SIG_IGN */;
}
/* Setup handler for SIGCHLD when executing external command
* to get quick 'waitpid()' reaction
* It will interrupt syscall just like SIGALRM and
* invoke process_event().
*/
static void _init_thread_signals(struct dso_state *state)
{
struct sigaction act = { .sa_handler = _sig_child };
sigset_t my_sigset;
sigemptyset(&my_sigset);
if (sigaction(SIGCHLD, &act, NULL))
log_warn("WARNING: Failed to set SIGCHLD action.");
else if (sigaddset(&my_sigset, SIGCHLD))
log_warn("WARNING: Failed to add SIGCHLD to set.");
else if (pthread_sigmask(SIG_UNBLOCK, &my_sigset, &state->old_sigset))
log_warn("WARNING: Failed to unblock SIGCHLD.");
else
state->restore_sigset = 1;
}
static void _restore_thread_signals(struct dso_state *state)
{
if (state->restore_sigset &&
pthread_sigmask(SIG_SETMASK, &state->old_sigset, NULL))
log_warn("WARNING: Failed to block SIGCHLD.");
}
int register_device(const char *device,
@ -360,27 +348,55 @@ int register_device(const char *device,
void **user)
{
struct dso_state *state;
char *str;
char cmd_str[PATH_MAX + 128 + 2]; /* cmd ' ' vg/lv \0 */
if (!dmeventd_lvm2_init_with_pool("thin_pool_state", state))
goto_bad;
if (!dmeventd_lvm2_command(state->mem, state->cmd_str,
sizeof(state->cmd_str),
"lvextend --use-policies",
device)) {
dmeventd_lvm2_exit_with_pool(state);
if (!dmeventd_lvm2_command(state->mem, cmd_str, sizeof(cmd_str),
"_dmeventd_thin_command", device))
goto_bad;
}
state->metadata_percent_check = CHECK_MINIMUM;
state->data_percent_check = CHECK_MINIMUM;
if (strncmp(cmd_str, "lvm ", 4) == 0) {
if (!(state->cmd_str = dm_pool_strdup(state->mem, cmd_str + 4))) {
log_error("Failed to copy lvm command.");
goto bad;
}
} else if (cmd_str[0] == '/') {
if (!(state->cmd_str = dm_pool_strdup(state->mem, cmd_str))) {
log_error("Failed to copy thin command.");
goto bad;
}
/* Find last space before 'vg/lv' */
if (!(str = strrchr(state->cmd_str, ' ')))
goto inval;
if (!(state->argv[0] = dm_pool_strndup(state->mem, state->cmd_str,
str - state->cmd_str))) {
log_error("Failed to copy command.");
goto bad;
}
state->argv[1] = str + 1; /* 1 argument - vg/lv */
_init_thread_signals(state);
} else /* Unuspported command format */
goto inval;
state->pid = -1;
*user = state;
log_info("Monitoring thin %s.", device);
log_info("Monitoring thin pool %s.", device);
return 1;
inval:
log_error("Invalid command for monitoring: %s.", cmd_str);
bad:
log_error("Failed to monitor thin %s.", device);
log_error("Failed to monitor thin pool %s.", device);
if (state)
dmeventd_lvm2_exit_with_pool(state);
return 0;
}
@ -392,9 +408,31 @@ int unregister_device(const char *device,
void **user)
{
struct dso_state *state = *user;
int i;
for (i = 0; !_wait_for_pid(state) && (i < 6); ++i) {
if (i == 0)
/* Give it 2 seconds, then try to terminate & kill it */
log_verbose("Child %d still not finished (%s) waiting.",
state->pid, state->cmd_str);
else if (i == 3) {
log_warn("WARNING: Terminating child %d.", state->pid);
kill(state->pid, SIGINT);
kill(state->pid, SIGTERM);
} else if (i == 5) {
log_warn("WARNING: Killing child %d.", state->pid);
kill(state->pid, SIGKILL);
}
sleep(1);
}
if (state->pid != -1)
log_warn("WARNING: Cannot kill child %d!", state->pid);
_restore_thread_signals(state);
dmeventd_lvm2_exit_with_pool(state);
log_info("No longer monitoring thin %s.", device);
log_info("No longer monitoring thin pool %s.", device);
return 1;
}

1
daemons/dmfilemapd/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
dmfilemapd

View File

@ -0,0 +1,68 @@
#
# Copyright (C) 2016 Red Hat, Inc. All rights reserved.
#
# This file is part of the device-mapper userspace tools.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU Lesser General Public License v.2.1.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@
top_builddir = @top_builddir@
SOURCES = dmfilemapd.c
TARGETS = dmfilemapd
.PHONY: install_dmfilemapd install_dmfilemapd_static
INSTALL_DMFILEMAPD_TARGETS = install_dmfilemapd_dynamic
CLEAN_TARGETS = dmfilemapd.static
CFLOW_LIST = $(SOURCES)
CFLOW_LIST_TARGET = $(LIB_NAME).cflow
CFLOW_TARGET = dmfilemapd
include $(top_builddir)/make.tmpl
all: device-mapper
device-mapper: $(TARGETS)
LIBS += -ldevmapper
CFLAGS_dmfilemapd.o += $(EXTRA_EXEC_CFLAGS)
dmfilemapd: $(LIB_SHARED) dmfilemapd.o
$(CC) $(CFLAGS) $(LDFLAGS) $(EXTRA_EXEC_LDFLAGS) $(ELDFLAGS) -L. -o $@ dmfilemapd.o \
$(DL_LIBS) $(LVMLIBS) $(LIBS) -rdynamic
dmfilemapd.static: $(LIB_STATIC) dmfilemapd.o $(interfacebuilddir)/libdevmapper.a
$(CC) $(CFLAGS) $(LDFLAGS) $(ELDFLAGS) -static -L. -L$(interfacebuilddir) -o $@ \
dmfilemapd.o $(DL_LIBS) $(LVMLIBS) $(LIBS) $(STATIC_LIBS)
ifneq ("$(CFLOW_CMD)", "")
CFLOW_SOURCES = $(addprefix $(srcdir)/, $(SOURCES))
-include $(top_builddir)/libdm/libdevmapper.cflow
-include $(top_builddir)/lib/liblvm-internal.cflow
-include $(top_builddir)/lib/liblvm2cmd.cflow
-include $(top_builddir)/daemons/dmfilemapd/$(LIB_NAME).cflow
endif
install_dmfilemapd_dynamic: dmfilemapd
$(INSTALL_PROGRAM) -D $< $(sbindir)/$(<F)
install_dmfilemapd_static: dmfilemapd.static
$(INSTALL_PROGRAM) -D $< $(staticdir)/$(<F)
install_dmfilemapd: $(INSTALL_DMFILEMAPD_TARGETS)
install: install_dmfilemapd
install_device-mapper: install_dmfilemapd

View File

@ -0,0 +1,829 @@
/*
* Copyright (C) 2016 Red Hat, Inc. All rights reserved.
*
* This file is part of the device-mapper userspace tools.
*
* It includes tree drawing code based on pstree: http://psmisc.sourceforge.net/
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License v.2.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tool.h"
#include "dm-logging.h"
#include "defaults.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/inotify.h>
#include <dirent.h>
#include <ctype.h>
#ifdef __linux__
# include "kdev_t.h"
#else
# define MAJOR(x) major((x))
# define MINOR(x) minor((x))
# define MKDEV(x,y) makedev((x),(y))
#endif
/* limit to two updates/sec */
#define FILEMAPD_WAIT_USECS 500000
/* how long to wait for unlinked files */
#define FILEMAPD_NOFILE_WAIT_USECS 100000
#define FILEMAPD_NOFILE_WAIT_TRIES 10
struct filemap_monitor {
dm_filemapd_mode_t mode;
const char *program_id;
uint64_t group_id;
char *path;
int fd;
int inotify_fd;
int inotify_watch_fd;
/* monitoring heuristics */
int64_t blocks; /* allocated blocks, from stat.st_blocks */
uint64_t nr_regions;
int deleted;
};
static int _foreground;
static int _verbose;
const char *const _usage = "dmfilemapd <fd> <group_id> <abs_path> <mode> "
"[<foreground>[<log_level>]]";
/*
* Daemon logging. By default, all messages are thrown away: messages
* are only written to the terminal if the daemon is run in the foreground.
*/
__attribute__((format(printf, 5, 0)))
static void _dmfilemapd_log_line(int level,
const char *file __attribute__((unused)),
int line __attribute__((unused)),
int dm_errno_or_class,
const char *f, va_list ap)
{
static int _abort_on_internal_errors = -1;
FILE *out = log_stderr(level) ? stderr : stdout;
level = log_level(level);
if (level <= _LOG_WARN || _verbose) {
if (level < _LOG_WARN)
out = stderr;
vfprintf(out, f, ap);
fputc('\n', out);
}
if (_abort_on_internal_errors < 0)
/* Set when env DM_ABORT_ON_INTERNAL_ERRORS is not "0" */
_abort_on_internal_errors =
strcmp(getenv("DM_ABORT_ON_INTERNAL_ERRORS") ? : "0", "0");
if (_abort_on_internal_errors &&
!strncmp(f, INTERNAL_ERROR, sizeof(INTERNAL_ERROR) - 1))
abort();
}
__attribute__((format(printf, 5, 6)))
static void _dmfilemapd_log_with_errno(int level,
const char *file, int line,
int dm_errno_or_class,
const char *f, ...)
{
va_list ap;
va_start(ap, f);
_dmfilemapd_log_line(level, file, line, dm_errno_or_class, f, ap);
va_end(ap);
}
/*
* Only used for reporting errors before daemonise().
*/
__attribute__((format(printf, 1, 2)))
static void _early_log(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
fputc('\n', stderr);
va_end(ap);
}
static void _setup_logging(void)
{
dm_log_init_verbose(_verbose - 1);
dm_log_with_errno_init(_dmfilemapd_log_with_errno);
}
#define PROC_FD_DELETED_STR "(deleted)"
/*
* Scan the /proc/<pid>/fd directory for pid and check for an fd
* symlink whose contents match path.
*/
static int _is_open_in_pid(pid_t pid, const char *path)
{
char deleted_path[PATH_MAX + sizeof(PROC_FD_DELETED_STR)];
struct dirent *pid_dp = NULL;
char path_buf[PATH_MAX];
char link_buf[PATH_MAX];
DIR *pid_d = NULL;
ssize_t len;
if (pid == getpid())
return 0;
if (dm_snprintf(path_buf, sizeof(path_buf),
DEFAULT_PROC_DIR "%d/fd", pid) < 0) {
log_error("Could not format pid path.");
return 0;
}
/*
* Test for the kernel 'file (deleted)' form when scanning.
*/
if (dm_snprintf(deleted_path, sizeof(deleted_path), "%s %s",
path, PROC_FD_DELETED_STR) < 0) {
log_error("Could not format check path.");
return 0;
}
pid_d = opendir(path_buf);
if (!pid_d) {
log_error("Could not open proc path: %s.", path_buf);
return 0;
}
while ((pid_dp = readdir(pid_d)) != NULL) {
if (pid_dp->d_name[0] == '.')
continue;
if ((len = readlinkat(dirfd(pid_d), pid_dp->d_name, link_buf,
sizeof(link_buf))) < 0) {
log_error("readlink failed for " DEFAULT_PROC_DIR
"/%d/fd/.", pid);
goto bad;
}
link_buf[len] = '\0';
if (!strcmp(deleted_path, link_buf)) {
if (closedir(pid_d))
log_sys_error("closedir", path_buf);
return 1;
}
}
bad:
if (closedir(pid_d))
log_sys_error("closedir", path_buf);
return 0;
}
/*
* Attempt to determine whether a file is open by any process by
* scanning symbolic links in /proc/<pid>/fd.
*
* This is a heuristic since it cannot guarantee to detect brief
* access in all cases: a process that opens and then closes the
* file rapidly may never be seen by the scan.
*
* The method will also give false-positives if a process exists
* that has a deleted file open that had the same path, but a
* different inode number, to the file being monitored.
*
* For this reason the daemon only uses _is_open() for unlinked
* files when the mode is DM_FILEMAPD_FOLLOW_INODE, since these
* files can no longer be newly opened by processes.
*
* In this situation !is_open(path) provides an indication that
* the daemon should shut down: the file has been unlinked from
* the file system and we appear to hold the final reference.
*/
static int _is_open(const char *path)
{
struct dirent *proc_dp = NULL;
DIR *proc_d = NULL;
pid_t pid;
proc_d = opendir(DEFAULT_PROC_DIR);
if (!proc_d)
return 0;
while ((proc_dp = readdir(proc_d)) != NULL) {
if (!isdigit(proc_dp->d_name[0]))
continue;
pid = (pid_t) strtol(proc_dp->d_name, NULL, 10);
if (!pid)
continue;
if (_is_open_in_pid(pid, path)) {
if (closedir(proc_d))
log_sys_error("closedir", DEFAULT_PROC_DIR);
return 1;
}
}
if (closedir(proc_d))
log_sys_error("closedir", DEFAULT_PROC_DIR);
return 0;
}
static void _filemap_monitor_wait(uint64_t usecs)
{
if (_verbose) {
if (usecs == FILEMAPD_WAIT_USECS)
log_very_verbose("Waiting for check interval");
if (usecs == FILEMAPD_NOFILE_WAIT_USECS)
log_very_verbose("Waiting for unlinked path");
}
usleep((useconds_t) usecs);
}
static int _parse_args(int argc, char **argv, struct filemap_monitor *fm)
{
char *endptr;
/* we don't care what is in argv[0]. */
argc--;
argv++;
if (argc < 5) {
_early_log("Wrong number of arguments.");
_early_log("usage: %s", _usage);
return 0;
}
/*
* We don't know the true nr_regions at daemon start time,
* and it is not worth a dm_stats_list()/group walk to count:
* we can assume that there is at least one region or the
* daemon would not have been started.
*
* A correct value will be obtained following the first update
* of the group's regions.
*/
fm->nr_regions = 1;
/* parse <fd> */
fm->fd = (int) strtol(argv[0], &endptr, 10);
if (*endptr) {
_early_log("Could not parse file descriptor: %s", argv[0]);
return 0;
}
argc--;
argv++;
/* parse <group_id> */
fm->group_id = strtoull(argv[0], &endptr, 10);
if (*endptr) {
_early_log("Could not parse group identifier: %s", argv[0]);
return 0;
}
argc--;
argv++;
/* parse <path> */
if (!argv[0] || !strlen(argv[0])) {
_early_log("Path argument is required.");
return 0;
}
if (*argv[0] != '/') {
_early_log("Path argument must specify an absolute path.");
return 0;
}
fm->path = dm_strdup(argv[0]);
if (!fm->path) {
_early_log("Could not allocate memory for path argument.");
return 0;
}
argc--;
argv++;
/* parse <mode> */
if (!argv[0] || !strlen(argv[0])) {
_early_log("Mode argument is required.");
return 0;
}
fm->mode = dm_filemapd_mode_from_string(argv[0]);
if (fm->mode == DM_FILEMAPD_FOLLOW_NONE)
return 0;
argc--;
argv++;
/* parse [<foreground>[<verbose>]] */
if (argc) {
_foreground = (int) strtol(argv[0], &endptr, 10);
if (*endptr) {
_early_log("Could not parse debug argument: %s.",
argv[0]);
return 0;
}
argc--;
argv++;
if (argc) {
_verbose = (int) strtol(argv[0], &endptr, 10);
if (*endptr) {
_early_log("Could not parse verbose "
"argument: %s", argv[0]);
return 0;
}
if (_verbose < 0 || _verbose > 3) {
_early_log("Verbose argument out of range: %d.",
_verbose);
return 0;
}
}
}
return 1;
}
static int _filemap_fd_update_blocks(struct filemap_monitor *fm)
{
struct stat buf;
if (fm->fd < 0) {
log_error("Filemap fd is not open.");
return 0;
}
if (fstat(fm->fd, &buf)) {
log_error("Failed to fstat filemap file descriptor.");
return 0;
}
fm->blocks = buf.st_blocks;
return 1;
}
static int _filemap_fd_check_changed(struct filemap_monitor *fm)
{
int64_t old_blocks;
old_blocks = fm->blocks;
if (!_filemap_fd_update_blocks(fm))
return -1;
return (fm->blocks != old_blocks);
}
static void _filemap_monitor_close_fd(struct filemap_monitor *fm)
{
if (close(fm->fd))
log_error("Error closing file descriptor.");
fm->fd = -1;
}
static void _filemap_monitor_end_notify(struct filemap_monitor *fm)
{
inotify_rm_watch(fm->inotify_fd, fm->inotify_watch_fd);
}
static int _filemap_monitor_set_notify(struct filemap_monitor *fm)
{
int inotify_fd, watch_fd;
/*
* Set IN_NONBLOCK since we do not want to block in event read()
* calls. Do not set IN_CLOEXEC as dmfilemapd is single-threaded
* and does not fork or exec.
*/
if ((inotify_fd = inotify_init1(IN_NONBLOCK)) < 0) {
log_sys_error("inotify_init1", "IN_NONBLOCK");
return 0;
}
if ((watch_fd = inotify_add_watch(inotify_fd, fm->path,
IN_MODIFY | IN_DELETE_SELF)) < 0) {
log_sys_error("inotify_add_watch", fm->path);
return 0;
}
fm->inotify_fd = inotify_fd;
fm->inotify_watch_fd = watch_fd;
return 1;
}
static int _filemap_monitor_reopen_fd(struct filemap_monitor *fm)
{
int tries = FILEMAPD_NOFILE_WAIT_TRIES;
/*
* In DM_FILEMAPD_FOLLOW_PATH mode, inotify watches must be
* re-established whenever the file at the watched path is
* changed.
*
* FIXME: stat file and skip if inode is unchanged.
*/
if (fm->fd > 0)
log_error("Filemap file descriptor already open.");
while ((fm->fd < 0) && --tries)
if (((fm->fd = open(fm->path, O_RDONLY)) < 0) && tries)
_filemap_monitor_wait(FILEMAPD_NOFILE_WAIT_USECS);
if (!tries && (fm->fd < 0)) {
log_error("Could not re-open file descriptor.");
return 0;
}
return _filemap_monitor_set_notify(fm);
}
static int _filemap_monitor_get_events(struct filemap_monitor *fm)
{
/* alignment as per man(7) inotify */
char buf[sizeof(struct inotify_event) + NAME_MAX + 1]
__attribute__ ((aligned(__alignof__(struct inotify_event))));
struct inotify_event *event;
int check = 0;
ssize_t len;
char *ptr;
/*
* Close the file descriptor for the file being monitored here
* when mode=path: this will allow the inode to be de-allocated,
* and an IN_DELETE_SELF event generated in the case that the
* daemon is holding the last open reference to the file.
*/
if (fm->mode == DM_FILEMAPD_FOLLOW_PATH) {
_filemap_monitor_end_notify(fm);
_filemap_monitor_close_fd(fm);
}
len = read(fm->inotify_fd, (void *) &buf, sizeof(buf));
/* no events to read? */
if (len < 0 && (errno == EAGAIN))
goto out;
/* interrupted by signal? */
if (len < 0 && (errno == EINTR))
goto out;
if (len < 0)
return -1;
if (!len)
goto out;
for (ptr = buf; ptr < buf + len; ptr += sizeof(*event) + event->len) {
event = (struct inotify_event *) ptr;
if (event->mask & IN_DELETE_SELF)
fm->deleted = 1;
if (event->mask & IN_MODIFY)
check = 1;
/*
* Event IN_IGNORED is generated when a file has been deleted
* and IN_DELETE_SELF generated, and indicates that the file
* watch has been automatically removed.
*
* This can only happen for the DM_FILEMAPD_FOLLOW_PATH mode,
* since inotify IN_DELETE events are generated at the time
* the inode is destroyed: DM_FILEMAPD_FOLLOW_INODE will hold
* the file descriptor open, meaning that the event will not
* be generated until after the daemon closes the file.
*
* The event is ignored here since inotify monitoring will
* be reestablished (or the daemon will terminate) following
* deletion of a DM_FILEMAPD_FOLLOW_PATH monitored file.
*/
if (event->mask & IN_IGNORED)
log_very_verbose("Inotify watch removed: IN_IGNORED "
"in event->mask");
}
out:
/*
* Re-open file descriptor if required and log disposition.
*/
if (fm->mode == DM_FILEMAPD_FOLLOW_PATH)
if (!_filemap_monitor_reopen_fd(fm))
return -1;
log_very_verbose("exiting _filemap_monitor_get_events() with "
"deleted=%d, check=%d", fm->deleted, check);
return check;
}
static void _filemap_monitor_destroy(struct filemap_monitor *fm)
{
if (fm->fd > 0) {
_filemap_monitor_end_notify(fm);
_filemap_monitor_close_fd(fm);
}
dm_free((void *) fm->program_id);
dm_free(fm->path);
}
static int _filemap_monitor_check_same_file(int fd1, int fd2)
{
struct stat buf1, buf2;
if ((fd1 < 0) || (fd2 < 0))
return 0;
if (fstat(fd1, &buf1)) {
log_error("Failed to fstat file descriptor %d", fd1);
return -1;
}
if (fstat(fd2, &buf2)) {
log_error("Failed to fstat file descriptor %d", fd2);
return -1;
}
return ((buf1.st_dev == buf2.st_dev) && (buf1.st_ino == buf2.st_ino));
}
static int _filemap_monitor_check_file_unlinked(struct filemap_monitor *fm)
{
char path_buf[PATH_MAX];
char link_buf[PATH_MAX];
int same, fd;
ssize_t len;
fm->deleted = 0;
same = 0;
if ((fd = open(fm->path, O_RDONLY)) < 0)
goto check_unlinked;
same = _filemap_monitor_check_same_file(fm->fd, fd);
if (close(fd))
log_error("Error closing fd %d", fd);
if (same < 0)
return 0;
if (same)
return 1;
check_unlinked:
/*
* The file has been unlinked from its original location: test
* whether it is still reachable in the filesystem, or if it is
* unlinked and anonymous.
*/
if (dm_snprintf(path_buf, sizeof(path_buf), DEFAULT_PROC_DIR
"/%d/fd/%d", getpid(), fm->fd) < 0) {
log_error("Could not format pid path.");
return 0;
}
if ((len = readlink(path_buf, link_buf, sizeof(link_buf) - 1)) < 0) {
log_error("readlink failed for " DEFAULT_PROC_DIR "/%d/fd/%d.",
getpid(), fm->fd);
return 0;
}
link_buf[len] = '\0';
/*
* Try to re-open the file, from the path now reported in /proc/pid/fd.
*/
if ((fd = open(link_buf, O_RDONLY)) < 0)
fm->deleted = 1;
else
same = _filemap_monitor_check_same_file(fm->fd, fd);
if ((fd >= 0) && close(fd))
log_error("Error closing fd %d", fd);
if (same < 0)
return 0;
/* Should not happen with normal /proc. */
if ((fd > 0) && !same) {
log_error("File descriptor mismatch: %d and %s (read from %s) "
"are not the same file!", fm->fd, link_buf, path_buf);
return 0;
}
return 1;
}
static int _daemonise(struct filemap_monitor *fm)
{
pid_t pid = 0, sid;
int fd;
if (!(sid = setsid())) {
_early_log("setsid failed.");
return 0;
}
if ((pid = fork()) < 0) {
_early_log("Failed to fork daemon process.");
return 0;
}
if (pid > 0) {
if (_verbose)
_early_log("Started dmfilemapd with pid=%d", pid);
exit(0);
}
if (chdir("/")) {
_early_log("Failed to change directory.");
return 0;
}
if (!_verbose) {
if (close(STDIN_FILENO))
_early_log("Error closing stdin");
if (close(STDOUT_FILENO))
_early_log("Error closing stdout");
if (close(STDERR_FILENO))
_early_log("Error closing stderr");
if ((open("/dev/null", O_RDONLY) < 0) ||
(open("/dev/null", O_WRONLY) < 0) ||
(open("/dev/null", O_WRONLY) < 0)) {
_early_log("Error opening stdio streams.");
return 0;
}
}
/* TODO: Use libdaemon/server/daemon-server.c _daemonise() */
for (fd = (int) sysconf(_SC_OPEN_MAX) - 1; fd > STDERR_FILENO; fd--) {
if (fd == fm->fd)
continue;
(void) close(fd);
}
return 1;
}
static int _update_regions(struct dm_stats *dms, struct filemap_monitor *fm)
{
uint64_t *regions = NULL, *region, nr_regions = 0;
regions = dm_stats_update_regions_from_fd(dms, fm->fd, fm->group_id);
if (!regions) {
log_error("Failed to update filemap regions for group_id="
FMTu64 ".", fm->group_id);
return 0;
}
for (region = regions; *region != DM_STATS_REGIONS_ALL; region++)
nr_regions++;
if (!nr_regions)
log_warn("File contains no extents: exiting.");
if (nr_regions && (regions[0] != fm->group_id)) {
log_warn("group_id changed from " FMTu64 " to " FMTu64,
fm->group_id, regions[0]);
fm->group_id = regions[0];
}
dm_free(regions);
fm->nr_regions = nr_regions;
return 1;
}
static int _dmfilemapd(struct filemap_monitor *fm)
{
int running = 1, check = 0, open = 0;
const char *program_id;
struct dm_stats *dms;
/*
* The correct program_id is retrieved from the group leader
* following the call to dm_stats_list().
*/
if (!(dms = dm_stats_create(NULL)))
goto_bad;
if (!dm_stats_bind_from_fd(dms, fm->fd)) {
log_error("Could not bind dm_stats handle to file descriptor "
"%d", fm->fd);
goto bad;
}
if (!_filemap_monitor_set_notify(fm))
goto bad;
if (!_filemap_fd_update_blocks(fm))
goto bad;
if (!dm_stats_list(dms, DM_STATS_ALL_PROGRAMS)) {
log_error("Failed to list stats handle.");
goto bad;
}
/*
* Take the program_id for new regions (created by calls to
* dm_stats_update_regions_from_fd()) from the value used by
* the group leader.
*/
program_id = dm_stats_get_region_program_id(dms, fm->group_id);
if (program_id)
fm->program_id = dm_strdup(program_id);
else
fm->program_id = NULL;
dm_stats_set_program_id(dms, 1, program_id);
do {
if (!dm_stats_group_present(dms, fm->group_id)) {
log_info("Filemap group removed: exiting.");
running = 0;
continue;
}
if ((check = _filemap_monitor_get_events(fm)) < 0)
goto bad;
if (!check)
goto wait;
if ((check = _filemap_fd_check_changed(fm)) < 0)
goto bad;
if (check && !_update_regions(dms, fm))
goto bad;
running = !!fm->nr_regions;
if (!running)
continue;
wait:
_filemap_monitor_wait(FILEMAPD_WAIT_USECS);
/* mode=inode termination condions */
if (fm->mode == DM_FILEMAPD_FOLLOW_INODE) {
if (!_filemap_monitor_check_file_unlinked(fm))
goto bad;
if (fm->deleted && !(open = _is_open(fm->path))) {
log_info("File unlinked and closed: exiting.");
running = 0;
} else if (fm->deleted && open)
log_verbose("File unlinked and open: "
"continuing.");
}
if (!dm_stats_list(dms, NULL)) {
log_error("Failed to list stats handle.");
goto bad;
}
} while (running);
_filemap_monitor_destroy(fm);
dm_stats_destroy(dms);
return 0;
bad:
_filemap_monitor_destroy(fm);
dm_stats_destroy(dms);
log_error("Exiting");
return 1;
}
static const char * _mode_names[] = {
"inode",
"path"
};
/*
* dmfilemapd <fd> <group_id> <path> <mode> [<foreground>[<log_level>]]
*/
int main(int argc, char **argv)
{
struct filemap_monitor fm;
memset(&fm, 0, sizeof(fm));
if (!_parse_args(argc, argv, &fm)) {
dm_free(fm.path);
return 1;
}
_setup_logging();
log_info("Starting dmfilemapd with fd=%d, group_id=" FMTu64 " "
"mode=%s, path=%s", fm.fd, fm.group_id,
_mode_names[fm.mode], fm.path);
if (!_foreground && !_daemonise(&fm))
return 1;
return _dmfilemapd(&fm);
}

1
daemons/lvmdbusd/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
path.py

View File

@ -0,0 +1,66 @@
#
# Copyright (C) 2016 Red Hat, Inc. All rights reserved.
#
# This file is part of LVM2.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@
top_builddir = @top_builddir@
lvmdbusdir = $(python3dir)/lvmdbusd
LVMDBUS_SRCDIR_FILES = \
automatedproperties.py \
background.py \
cfg.py \
cmdhandler.py \
fetch.py \
__init__.py \
job.py \
loader.py \
lvmdb.py \
main.py \
lvm_shell_proxy.py \
lv.py \
manager.py \
objectmanager.py \
pv.py \
request.py \
state.py \
udevwatch.py \
utils.py \
vg.py
LVMDBUS_BUILDDIR_FILES = \
path.py
LVMDBUSD = $(srcdir)/lvmdbusd
include $(top_builddir)/make.tmpl
.PHONY: install_lvmdbusd
install_lvmdbusd:
$(INSTALL_DIR) $(sbindir)
$(INSTALL_SCRIPT) $(LVMDBUSD) $(sbindir)
$(INSTALL_DIR) $(DESTDIR)$(lvmdbusdir)
(cd $(srcdir); $(INSTALL_DATA) $(LVMDBUS_SRCDIR_FILES) $(DESTDIR)$(lvmdbusdir))
$(INSTALL_DATA) $(LVMDBUS_BUILDDIR_FILES) $(DESTDIR)$(lvmdbusdir)
PYTHON=$(PYTHON3) $(PYCOMPILE) --destdir "$(DESTDIR)" --basedir "$(lvmdbusdir)" $(LVMDBUS_SRCDIR_FILES) $(LVMDBUS_BUILDDIR_FILES)
$(CHMOD) 755 $(DESTDIR)$(lvmdbusdir)/__pycache__
$(CHMOD) 444 $(DESTDIR)$(lvmdbusdir)/__pycache__/*.py[co]
install_lvm2: install_lvmdbusd
install: install_lvm2
DISTCLEAN_TARGETS+= \
$(LVMDBUS_BUILDDIR_FILES)

View File

@ -0,0 +1,10 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .main import main

View File

@ -0,0 +1,194 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import dbus
import dbus.service
from . import cfg
from .utils import get_properties, add_properties, get_object_property_diff, \
log_debug
from .state import State
# noinspection PyPep8Naming,PyUnresolvedReferences
class AutomatedProperties(dbus.service.Object):
"""
This class implements the needed interfaces for:
org.freedesktop.DBus.Properties
Other classes inherit from it to get the same behavior
"""
def __init__(self, object_path, search_method=None):
dbus.service.Object.__init__(self, cfg.bus, object_path)
self._ap_interface = []
self._ap_o_path = object_path
self._ap_search_method = search_method
self.state = None
def dbus_object_path(self):
return self._ap_o_path
def emit_data(self):
props = {}
for i in self.interface():
props[i] = AutomatedProperties._get_all_prop(self, i)
return self._ap_o_path, props
def set_interface(self, interface):
"""
With inheritance we can't easily tell what interfaces a class provides
so we will have each class that implements an interface tell the
base AutomatedProperties what it is they do provide. This is kind of
clunky and perhaps we can figure out a better way to do this later.
:param interface: An interface the object supports
:return:
"""
if interface not in self._ap_interface:
self._ap_interface.append(interface)
# noinspection PyUnusedLocal
def interface(self, all_interfaces=False):
if all_interfaces:
cpy = list(self._ap_interface)
cpy.extend(
["org.freedesktop.DBus.Introspectable",
"org.freedesktop.DBus.Properties"])
return cpy
return self._ap_interface
@staticmethod
def _get_prop(obj, interface_name, property_name):
value = getattr(obj, property_name)
# Note: If we get an exception in this handler we won't know about it,
# only the side effect of no returned value!
log_debug('Get (%s), type (%s), value(%s)' %
(property_name, str(type(value)), str(value)))
return value
# Properties
# noinspection PyUnusedLocal
@dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE,
in_signature='ss', out_signature='v',
async_callbacks=('cb', 'cbe'))
def Get(self, interface_name, property_name, cb, cbe):
# Note: If we get an exception in this handler we won't know about it,
# only the side effect of no returned value!
r = cfg.create_request_entry(
-1, AutomatedProperties._get_prop,
(self, interface_name, property_name),
cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _get_all_prop(obj, interface_name):
if interface_name in obj.interface(True):
# Using introspection, lets build this dynamically
properties = get_properties(obj)
if interface_name in properties:
return properties[interface_name][1]
return {}
raise dbus.exceptions.DBusException(
obj._ap_interface,
'The object %s does not implement the %s interface'
% (obj.__class__, interface_name))
@dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE,
in_signature='s', out_signature='a{sv}',
async_callbacks=('cb', 'cbe'))
def GetAll(self, interface_name, cb, cbe):
r = cfg.create_request_entry(
-1, AutomatedProperties._get_all_prop,
(self, interface_name),
cb, cbe, False)
cfg.worker_q.put(r)
@dbus.service.method(dbus_interface=dbus.PROPERTIES_IFACE,
in_signature='ssv')
def Set(self, interface_name, property_name, new_value):
setattr(self, property_name, new_value)
self.PropertiesChanged(interface_name,
{property_name: new_value}, [])
# As dbus-python does not support introspection for properties we will
# get the autogenerated xml and then add our wanted properties to it.
@dbus.service.method(dbus_interface=dbus.INTROSPECTABLE_IFACE,
out_signature='s')
def Introspect(self):
r = dbus.service.Object.Introspect(self, self._ap_o_path, cfg.bus)
# Look at the properties in the class
props = get_properties(self)
for int_f, v in props.items():
r = add_properties(r, int_f, v[0])
return r
@dbus.service.signal(dbus_interface=dbus.PROPERTIES_IFACE,
signature='sa{sv}as')
def PropertiesChanged(self, interface_name, changed_properties,
invalidated_properties):
log_debug(('SIGNAL: PropertiesChanged(%s, %s, %s, %s)' %
(str(self._ap_o_path), str(interface_name),
str(changed_properties), str(invalidated_properties))))
def refresh(self, search_key=None, object_state=None):
"""
Take the values (properties) of an object and update them with what
lvm currently has. You can either fetch the new ones or supply the
new state to be updated with
:param search_key: The value to use to search for
:param object_state: Use this as the new object state
"""
num_changed = 0
# If we can't do a lookup, bail now, this happens if we blindly walk
# through all dbus objects as some don't have a search method, like
# 'Manager' object.
if not self._ap_search_method:
return
search = self.lvm_id
if search_key:
search = search_key
# Either we have the new object state or we need to go fetch it
if object_state:
new_state = object_state
else:
new_state = self._ap_search_method([search])[0]
assert isinstance(new_state, State)
assert new_state
# When we refresh an object the object identifiers might have changed
# because LVM allows the user to change them (name & uuid), thus if
# they have changed we need to update the object manager so that
# look-ups will happen correctly
old_id = self.state.identifiers()
new_id = new_state.identifiers()
if old_id[0] != new_id[0] or old_id[1] != new_id[1]:
cfg.om.lookup_update(self, new_id[0], new_id[1])
# Grab the properties values, then replace the state of the object
# and retrieve the new values.
o_prop = get_properties(self)
self.state = new_state
n_prop = get_properties(self)
changed = get_object_property_diff(o_prop, n_prop)
if changed:
for int_f, v in changed.items():
self.PropertiesChanged(int_f, v, [])
num_changed += 1
return num_changed

View File

@ -0,0 +1,162 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import subprocess
from . import cfg
from .cmdhandler import options_to_cli_args, LvmExecutionMeta
import dbus
from .utils import pv_range_append, pv_dest_ranges, log_error, log_debug,\
add_no_notify
import os
import threading
import time
def pv_move_lv_cmd(move_options, lv_full_name,
pv_source, pv_source_range, pv_dest_range_list):
cmd = ['pvmove', '-i', '1']
cmd.extend(options_to_cli_args(move_options))
if lv_full_name:
cmd.extend(['-n', lv_full_name])
pv_range_append(cmd, pv_source, *pv_source_range)
pv_dest_ranges(cmd, pv_dest_range_list)
return cmd
def lv_merge_cmd(merge_options, lv_full_name):
cmd = ['lvconvert', '--merge', '-i', '1']
cmd.extend(options_to_cli_args(merge_options))
cmd.append(lv_full_name)
return cmd
def _move_merge(interface_name, command, job_state):
# We need to execute these command stand alone by forking & exec'ing
# the command always as we will be getting periodic output from them on
# the status of the long running operation.
command.insert(0, cfg.LVM_CMD)
# Instruct lvm to not register an event with us
command = add_no_notify(command)
#(self, start, ended, cmd, ec, stdout_txt, stderr_txt)
meta = LvmExecutionMeta(time.time(), 0, command, -1000, None, None)
cfg.blackbox.add(meta)
process = subprocess.Popen(command, stdout=subprocess.PIPE,
env=os.environ,
stderr=subprocess.PIPE, close_fds=True)
log_debug("Background process for %s is %d" %
(str(command), process.pid))
lines_iterator = iter(process.stdout.readline, b"")
for line in lines_iterator:
line_str = line.decode("utf-8")
# Check to see if the line has the correct number of separators
try:
if line_str.count(':') == 2:
(device, ignore, percentage) = line_str.split(':')
job_state.Percent = round(
float(percentage.strip()[:-1]), 1)
# While the move is in progress we need to periodically update
# the state to reflect where everything is at.
cfg.load()
except ValueError:
log_error("Trying to parse percentage which failed for %s" %
line_str)
out = process.communicate()
with meta.lock:
meta.ended = time.time()
meta.ec = process.returncode
meta.stderr_txt = out[1]
if process.returncode == 0:
job_state.Percent = 100
else:
raise dbus.exceptions.DBusException(
interface_name,
'Exit code %s, stderr = %s' % (str(process.returncode), out[1]))
cfg.load()
return '/'
def move(interface_name, lv_name, pv_src_obj, pv_source_range,
pv_dests_and_ranges, move_options, job_state):
"""
Common code for the pvmove handling.
:param interface_name: What dbus interface we are providing for
:param lv_name: Optional (None or name of LV to move)
:param pv_src_obj: dbus object patch for source PV
:param pv_source_range: (0,0 to ignore, else start, end segments)
:param pv_dests_and_ranges: Array of PV object paths and start/end segs
:param move_options: Hash with optional arguments
:param job_state: Used to convey information about jobs between processes
:return: '/' When complete, the empty object path
"""
pv_dests = []
pv_src = cfg.om.get_object_by_path(pv_src_obj)
if pv_src:
# Check to see if we are handling a move to a specific
# destination(s)
if len(pv_dests_and_ranges):
for pr in pv_dests_and_ranges:
pv_dbus_obj = cfg.om.get_object_by_path(pr[0])
if not pv_dbus_obj:
raise dbus.exceptions.DBusException(
interface_name,
'PV Destination (%s) not found' % pr[0])
pv_dests.append((pv_dbus_obj.lvm_id, pr[1], pr[2]))
cmd = pv_move_lv_cmd(move_options,
lv_name,
pv_src.lvm_id,
pv_source_range,
pv_dests)
return _move_merge(interface_name, cmd, job_state)
else:
raise dbus.exceptions.DBusException(
interface_name, 'pv_src_obj (%s) not found' % pv_src_obj)
def merge(interface_name, lv_uuid, lv_name, merge_options, job_state):
# Make sure we have a dbus object representing it
dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name)
if dbo:
cmd = lv_merge_cmd(merge_options, dbo.lvm_id)
return _move_merge(interface_name, cmd, job_state)
else:
raise dbus.exceptions.DBusException(
interface_name,
'LV with uuid %s and name %s not present!' % (lv_uuid, lv_name))
def _run_cmd(req):
log_debug(
"_run_cmd: Running method: %s with args %s" %
(str(req.method), str(req.arguments)))
req.run_cmd()
log_debug("_run_cmd: complete!")
def cmd_runner(request):
t = threading.Thread(target=_run_cmd, args=(request,))
t.start()

89
daemons/lvmdbusd/cfg.py Normal file
View File

@ -0,0 +1,89 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import multiprocessing
import queue
import itertools
from lvmdbusd import path
LVM_CMD = os.getenv('LVM_BINARY', path.LVM_BINARY)
# This is the global object manager
om = None
# This is the global bus connection
bus = None
# Command line args
args = None
# Set to true if we are depending on external events for updates
got_external_event = False
# Shared state variable across all processes
run = multiprocessing.Value('i', 1)
# If this is set to true, the current setup support lvm shell and we are
# running in that mode of operation
SHELL_IN_USE = None
# Lock used by pprint
stdout_lock = multiprocessing.Lock()
worker_q = queue.Queue()
# Main event loop
loop = None
BUS_NAME = os.getenv('LVM_DBUS_NAME', 'com.redhat.lvmdbus1')
BASE_INTERFACE = 'com.redhat.lvmdbus1'
PV_INTERFACE = BASE_INTERFACE + '.Pv'
VG_INTERFACE = BASE_INTERFACE + '.Vg'
LV_INTERFACE = BASE_INTERFACE + '.Lv'
LV_COMMON_INTERFACE = BASE_INTERFACE + '.LvCommon'
THIN_POOL_INTERFACE = BASE_INTERFACE + '.ThinPool'
CACHE_POOL_INTERFACE = BASE_INTERFACE + '.CachePool'
LV_CACHED = BASE_INTERFACE + '.CachedLv'
SNAPSHOT_INTERFACE = BASE_INTERFACE + '.Snapshot'
MANAGER_INTERFACE = BASE_INTERFACE + '.Manager'
JOB_INTERFACE = BASE_INTERFACE + '.Job'
BASE_OBJ_PATH = '/' + BASE_INTERFACE.replace('.', '/')
PV_OBJ_PATH = BASE_OBJ_PATH + '/Pv'
VG_OBJ_PATH = BASE_OBJ_PATH + '/Vg'
LV_OBJ_PATH = BASE_OBJ_PATH + '/Lv'
THIN_POOL_PATH = BASE_OBJ_PATH + "/ThinPool"
CACHE_POOL_PATH = BASE_OBJ_PATH + "/CachePool"
HIDDEN_LV_PATH = BASE_OBJ_PATH + "/HiddenLv"
MANAGER_OBJ_PATH = BASE_OBJ_PATH + '/Manager'
JOB_OBJ_PATH = BASE_OBJ_PATH + '/Job'
# Counters for object path generation
pv_id = itertools.count()
vg_id = itertools.count()
lv_id = itertools.count()
thin_id = itertools.count()
cache_pool_id = itertools.count()
job_id = itertools.count()
hidden_lv = itertools.count()
# Used to prevent circular imports...
load = None
event = None
# Global cached state
db = None
# lvm flight recorder
blackbox = None
# RequestEntry ctor
create_request_entry = None

View File

@ -0,0 +1,754 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from subprocess import Popen, PIPE
import time
import threading
from itertools import chain
import collections
import traceback
import os
from lvmdbusd import cfg
from lvmdbusd.utils import pv_dest_ranges, log_debug, log_error, add_no_notify
from lvmdbusd.lvm_shell_proxy import LVMShellProxy
try:
import simplejson as json
except ImportError:
import json
SEP = '{|}'
total_time = 0.0
total_count = 0
# We need to prevent different threads from using the same lvm shell
# at the same time.
cmd_lock = threading.RLock()
class LvmExecutionMeta(object):
def __init__(self, start, ended, cmd, ec, stdout_txt, stderr_txt):
self.lock = threading.RLock()
self.start = start
self.ended = ended
self.cmd = cmd
self.ec = ec
self.stdout_txt = stdout_txt
self.stderr_txt = stderr_txt
def __str__(self):
with self.lock:
return "EC= %d for %s\n" \
"STARTED: %f, ENDED: %f\n" \
"STDOUT=%s\n" \
"STDERR=%s\n" % \
(self.ec, str(self.cmd), self.start, self.ended, self.stdout_txt,
self.stderr_txt)
class LvmFlightRecorder(object):
def __init__(self, size=16):
self.queue = collections.deque(maxlen=size)
def add(self, lvm_exec_meta):
self.queue.append(lvm_exec_meta)
def dump(self):
with cmd_lock:
if len(self.queue):
log_error("LVM dbus flight recorder START")
for c in self.queue:
log_error(str(c))
log_error("LVM dbus flight recorder END")
cfg.blackbox = LvmFlightRecorder()
def _debug_c(cmd, exit_code, out):
log_error('CMD= %s' % ' '.join(cmd))
log_error(("EC= %d" % exit_code))
log_error(("STDOUT=\n %s\n" % out[0]))
log_error(("STDERR=\n %s\n" % out[1]))
def call_lvm(command, debug=False):
"""
Call an executable and return a tuple of exitcode, stdout, stderr
:param command: Command to execute
:param debug: Dump debug to stdout
"""
# print 'STACK:'
# for line in traceback.format_stack():
# print line.strip()
# Prepend the full lvm executable so that we can run different versions
# in different locations on the same box
command.insert(0, cfg.LVM_CMD)
command = add_no_notify(command)
process = Popen(command, stdout=PIPE, stderr=PIPE, close_fds=True,
env=os.environ)
out = process.communicate()
stdout_text = bytes(out[0]).decode("utf-8")
stderr_text = bytes(out[1]).decode("utf-8")
if debug or process.returncode != 0:
_debug_c(command, process.returncode, (stdout_text, stderr_text))
return process.returncode, stdout_text, stderr_text
# The actual method which gets called to invoke the lvm command, can vary
# from forking a new process to using lvm shell
_t_call = call_lvm
def _shell_cfg():
global _t_call
# noinspection PyBroadException
try:
lvm_shell = LVMShellProxy()
_t_call = lvm_shell.call_lvm
cfg.SHELL_IN_USE = lvm_shell
return True
except Exception:
_t_call = call_lvm
cfg.SHELL_IN_USE = None
log_error(traceback.format_exc())
log_error("Unable to utilize lvm shell, dropping back to fork & exec")
return False
def set_execution(shell):
global _t_call
with cmd_lock:
# If the user requested lvm shell and we are currently setup that
# way, just return
if cfg.SHELL_IN_USE and shell:
return True
else:
if not shell and cfg.SHELL_IN_USE:
cfg.SHELL_IN_USE.exit_shell()
cfg.SHELL_IN_USE = None
_t_call = call_lvm
if shell:
if cfg.args.use_json:
return _shell_cfg()
else:
return False
return True
def time_wrapper(command, debug=False):
global total_time
global total_count
with cmd_lock:
start = time.time()
results = _t_call(command, debug)
ended = time.time()
total_time += (ended - start)
total_count += 1
cfg.blackbox.add(LvmExecutionMeta(start, ended, command, *results))
return results
call = time_wrapper
# Default cmd
# Place default arguments for every command here.
def _dc(cmd, args):
c = [cmd, '--noheading', '--separator', '%s' % SEP, '--nosuffix',
'--unbuffered', '--units', 'b']
c.extend(args)
return c
def parse(out):
rc = []
for line in out.split('\n'):
# This line includes separators, so process them
if SEP in line:
elem = line.split(SEP)
cleaned_elem = []
for e in elem:
e = e.strip()
cleaned_elem.append(e)
if len(cleaned_elem) > 1:
rc.append(cleaned_elem)
else:
t = line.strip()
if len(t) > 0:
rc.append(t)
return rc
def parse_column_names(out, column_names):
lines = parse(out)
rc = []
for i in range(0, len(lines)):
d = dict(list(zip(column_names, lines[i])))
rc.append(d)
return rc
def options_to_cli_args(options):
rc = []
for k, v in list(dict(options).items()):
if k.startswith("-"):
rc.append(k)
else:
rc.append("--%s" % k)
if v != "":
rc.append(str(v))
return rc
def pv_remove(device, remove_options):
cmd = ['pvremove']
cmd.extend(options_to_cli_args(remove_options))
cmd.append(device)
return call(cmd)
def _qt(tag_name):
return '@%s' % tag_name
def _tag(operation, what, add, rm, tag_options):
cmd = [operation]
cmd.extend(options_to_cli_args(tag_options))
if isinstance(what, list):
cmd.extend(what)
else:
cmd.append(what)
if add:
cmd.extend(list(chain.from_iterable(
('--addtag', _qt(x)) for x in add)))
if rm:
cmd.extend(list(chain.from_iterable(
('--deltag', _qt(x)) for x in rm)))
return call(cmd, False)
def pv_tag(pv_devices, add, rm, tag_options):
return _tag('pvchange', pv_devices, add, rm, tag_options)
def vg_tag(vg_name, add, rm, tag_options):
return _tag('vgchange', vg_name, add, rm, tag_options)
def lv_tag(lv_name, add, rm, tag_options):
return _tag('lvchange', lv_name, add, rm, tag_options)
def vg_rename(vg, new_name, rename_options):
cmd = ['vgrename']
cmd.extend(options_to_cli_args(rename_options))
cmd.extend([vg, new_name])
return call(cmd)
def vg_remove(vg_name, remove_options):
cmd = ['vgremove']
cmd.extend(options_to_cli_args(remove_options))
cmd.extend(['-f', vg_name])
return call(cmd)
def vg_lv_create(vg_name, create_options, name, size_bytes, pv_dests):
cmd = ['lvcreate']
cmd.extend(options_to_cli_args(create_options))
cmd.extend(['--size', str(size_bytes) + 'B'])
cmd.extend(['--name', name, vg_name, '--yes'])
pv_dest_ranges(cmd, pv_dests)
return call(cmd)
def vg_lv_snapshot(vg_name, snapshot_options, name, size_bytes):
cmd = ['lvcreate']
cmd.extend(options_to_cli_args(snapshot_options))
cmd.extend(["-s"])
if size_bytes != 0:
cmd.extend(['--size', str(size_bytes) + 'B'])
cmd.extend(['--name', name, vg_name])
return call(cmd)
def _vg_lv_create_common_cmd(create_options, size_bytes, thin_pool):
cmd = ['lvcreate']
cmd.extend(options_to_cli_args(create_options))
if not thin_pool:
cmd.extend(['--size', str(size_bytes) + 'B'])
else:
cmd.extend(['--thin', '--size', str(size_bytes) + 'B'])
cmd.extend(['--yes'])
return cmd
def vg_lv_create_linear(vg_name, create_options, name, size_bytes, thin_pool):
cmd = _vg_lv_create_common_cmd(create_options, size_bytes, thin_pool)
cmd.extend(['--name', name, vg_name])
return call(cmd)
def vg_lv_create_striped(vg_name, create_options, name, size_bytes,
num_stripes, stripe_size_kb, thin_pool):
cmd = _vg_lv_create_common_cmd(create_options, size_bytes, thin_pool)
cmd.extend(['--stripes', str(num_stripes)])
if stripe_size_kb != 0:
cmd.extend(['--stripesize', str(stripe_size_kb)])
cmd.extend(['--name', name, vg_name])
return call(cmd)
def _vg_lv_create_raid(vg_name, create_options, name, raid_type, size_bytes,
num_stripes, stripe_size_kb):
cmd = ['lvcreate']
cmd.extend(options_to_cli_args(create_options))
cmd.extend(['--type', raid_type])
cmd.extend(['--size', str(size_bytes) + 'B'])
if num_stripes != 0:
cmd.extend(['--stripes', str(num_stripes)])
if stripe_size_kb != 0:
cmd.extend(['--stripesize', str(stripe_size_kb)])
cmd.extend(['--name', name, vg_name, '--yes'])
return call(cmd)
def vg_lv_create_raid(vg_name, create_options, name, raid_type, size_bytes,
num_stripes, stripe_size_kb):
cmd = ['lvcreate']
cmd.extend(options_to_cli_args(create_options))
return _vg_lv_create_raid(vg_name, create_options, name, raid_type,
size_bytes, num_stripes, stripe_size_kb)
def vg_lv_create_mirror(
vg_name, create_options, name, size_bytes, num_copies):
cmd = ['lvcreate']
cmd.extend(options_to_cli_args(create_options))
cmd.extend(['--type', 'mirror'])
cmd.extend(['--mirrors', str(num_copies)])
cmd.extend(['--size', str(size_bytes) + 'B'])
cmd.extend(['--name', name, vg_name, '--yes'])
return call(cmd)
def vg_create_cache_pool(md_full_name, data_full_name, create_options):
cmd = ['lvconvert']
cmd.extend(options_to_cli_args(create_options))
cmd.extend(['--type', 'cache-pool', '--force', '-y',
'--poolmetadata', md_full_name, data_full_name])
return call(cmd)
def vg_create_thin_pool(md_full_name, data_full_name, create_options):
cmd = ['lvconvert']
cmd.extend(options_to_cli_args(create_options))
cmd.extend(['--type', 'thin-pool', '--force', '-y',
'--poolmetadata', md_full_name, data_full_name])
return call(cmd)
def lv_remove(lv_path, remove_options):
cmd = ['lvremove']
cmd.extend(options_to_cli_args(remove_options))
cmd.extend(['-f', lv_path])
return call(cmd)
def lv_rename(lv_path, new_name, rename_options):
cmd = ['lvrename']
cmd.extend(options_to_cli_args(rename_options))
cmd.extend([lv_path, new_name])
return call(cmd)
def lv_resize(lv_full_name, size_change, pv_dests,
resize_options):
cmd = ['lvresize', '--force']
cmd.extend(options_to_cli_args(resize_options))
if size_change < 0:
cmd.append("-L-%dB" % (-size_change))
else:
cmd.append("-L+%dB" % (size_change))
cmd.append(lv_full_name)
pv_dest_ranges(cmd, pv_dests)
return call(cmd)
def lv_lv_create(lv_full_name, create_options, name, size_bytes):
cmd = ['lvcreate']
cmd.extend(options_to_cli_args(create_options))
cmd.extend(['--virtualsize', str(size_bytes) + 'B', '-T'])
cmd.extend(['--name', name, lv_full_name, '--yes'])
return call(cmd)
def lv_cache_lv(cache_pool_full_name, lv_full_name, cache_options):
# lvconvert --type cache --cachepool VG/CachePoolLV VG/OriginLV
cmd = ['lvconvert']
cmd.extend(options_to_cli_args(cache_options))
cmd.extend(['-y', '--type', 'cache', '--cachepool',
cache_pool_full_name, lv_full_name])
return call(cmd)
def lv_detach_cache(lv_full_name, detach_options, destroy_cache):
cmd = ['lvconvert']
if destroy_cache:
option = '--uncache'
else:
# Currently fairly dangerous
# see: https://bugzilla.redhat.com/show_bug.cgi?id=1248972
option = '--splitcache'
cmd.extend(options_to_cli_args(detach_options))
# needed to prevent interactive questions
cmd.extend(["--yes", "--force"])
cmd.extend([option, lv_full_name])
return call(cmd)
def supports_json():
cmd = ['help']
rc, out, err = call(cmd)
if rc == 0:
if cfg.SHELL_IN_USE:
return True
else:
if 'fullreport' in err:
return True
return False
def lvm_full_report_json():
pv_columns = ['pv_name', 'pv_uuid', 'pv_fmt', 'pv_size', 'pv_free',
'pv_used', 'dev_size', 'pv_mda_size', 'pv_mda_free',
'pv_ba_start', 'pv_ba_size', 'pe_start', 'pv_pe_count',
'pv_pe_alloc_count', 'pv_attr', 'pv_tags', 'vg_name',
'vg_uuid', 'pv_missing']
pv_seg_columns = ['pvseg_start', 'pvseg_size', 'segtype',
'pv_uuid', 'lv_uuid', 'pv_name']
vg_columns = ['vg_name', 'vg_uuid', 'vg_fmt', 'vg_size', 'vg_free',
'vg_sysid', 'vg_extent_size', 'vg_extent_count',
'vg_free_count', 'vg_profile', 'max_lv', 'max_pv',
'pv_count', 'lv_count', 'snap_count', 'vg_seqno',
'vg_mda_count', 'vg_mda_free', 'vg_mda_size',
'vg_mda_used_count', 'vg_attr', 'vg_tags']
lv_columns = ['lv_uuid', 'lv_name', 'lv_path', 'lv_size',
'vg_name', 'pool_lv_uuid', 'pool_lv', 'origin_uuid',
'origin', 'data_percent',
'lv_attr', 'lv_tags', 'vg_uuid', 'lv_active', 'data_lv',
'metadata_lv', 'lv_parent', 'lv_role', 'lv_layout',
'snap_percent', 'metadata_percent', 'copy_percent',
'sync_percent', 'lv_metadata_size', 'move_pv', 'move_pv_uuid']
lv_seg_columns = ['seg_pe_ranges', 'segtype', 'lv_uuid']
cmd = _dc('fullreport', [
'-a', # Need hidden too
'--configreport', 'pv', '-o', ','.join(pv_columns),
'--configreport', 'vg', '-o', ','.join(vg_columns),
'--configreport', 'lv', '-o', ','.join(lv_columns),
'--configreport', 'seg', '-o', ','.join(lv_seg_columns),
'--configreport', 'pvseg', '-o', ','.join(pv_seg_columns),
'--reportformat', 'json'
])
rc, out, err = call(cmd)
if rc == 0:
# With the current implementation, if we are using the shell then we
# are using JSON and JSON is returned back to us as it was parsed to
# figure out if we completed OK or not
if cfg.SHELL_IN_USE:
assert(type(out) == dict)
return out
else:
return json.loads(out)
return None
def pv_retrieve_with_segs(device=None):
d = []
err = ""
out = ""
rc = 0
columns = ['pv_name', 'pv_uuid', 'pv_fmt', 'pv_size', 'pv_free',
'pv_used', 'dev_size', 'pv_mda_size', 'pv_mda_free',
'pv_ba_start', 'pv_ba_size', 'pe_start', 'pv_pe_count',
'pv_pe_alloc_count', 'pv_attr', 'pv_tags', 'vg_name',
'vg_uuid', 'pvseg_start', 'pvseg_size', 'segtype', 'pv_missing']
# Lvm has some issues where it returns failure when querying pvs when other
# operations are in process, see:
# https://bugzilla.redhat.com/show_bug.cgi?id=1274085
for i in range(0, 10):
cmd = _dc('pvs', ['-o', ','.join(columns)])
if device:
cmd.extend(device)
rc, out, err = call(cmd)
if rc == 0:
d = parse_column_names(out, columns)
break
else:
time.sleep(0.2)
log_debug("LVM Bug workaround, retrying pvs command...")
if rc != 0:
msg = "We were unable to get pvs to return without error after " \
"trying 10 times, RC=%d, STDERR=(%s), STDOUT=(%s)" % \
(rc, err, out)
log_error(msg)
raise RuntimeError(msg)
return d
def pv_resize(device, size_bytes, create_options):
cmd = ['pvresize']
cmd.extend(options_to_cli_args(create_options))
if size_bytes != 0:
cmd.extend(['--yes', '--setphysicalvolumesize', str(size_bytes) + 'B'])
cmd.extend([device])
return call(cmd)
def pv_create(create_options, devices):
cmd = ['pvcreate', '-ff']
cmd.extend(options_to_cli_args(create_options))
cmd.extend(devices)
return call(cmd)
def pv_allocatable(device, yes, allocation_options):
yn = 'n'
if yes:
yn = 'y'
cmd = ['pvchange']
cmd.extend(options_to_cli_args(allocation_options))
cmd.extend(['-x', yn, device])
return call(cmd)
def pv_scan(activate, cache, device_paths, major_minors, scan_options):
cmd = ['pvscan']
cmd.extend(options_to_cli_args(scan_options))
if activate:
cmd.extend(['--activate', "ay"])
if cache:
cmd.append('--cache')
if len(device_paths) > 0:
for d in device_paths:
cmd.append(d)
if len(major_minors) > 0:
for mm in major_minors:
cmd.append("%s:%s" % (mm))
return call(cmd)
def vg_create(create_options, pv_devices, name):
cmd = ['vgcreate']
cmd.extend(options_to_cli_args(create_options))
cmd.append(name)
cmd.extend(pv_devices)
return call(cmd)
def vg_change(change_options, name):
cmd = ['vgchange']
cmd.extend(options_to_cli_args(change_options))
cmd.append(name)
return call(cmd)
def vg_reduce(vg_name, missing, pv_devices, reduce_options):
cmd = ['vgreduce']
cmd.extend(options_to_cli_args(reduce_options))
if missing:
cmd.append('--removemissing')
elif len(pv_devices) == 0:
cmd.append('--all')
cmd.append(vg_name)
cmd.extend(pv_devices)
return call(cmd)
def vg_extend(vg_name, extend_devices, extend_options):
cmd = ['vgextend']
cmd.extend(options_to_cli_args(extend_options))
cmd.append(vg_name)
cmd.extend(extend_devices)
return call(cmd)
def _vg_value_set(name, arguments, options):
cmd = ['vgchange']
cmd.extend(options_to_cli_args(options))
cmd.append(name)
cmd.extend(arguments)
return call(cmd)
def vg_allocation_policy(vg_name, policy, policy_options):
return _vg_value_set(vg_name, ['--alloc', policy], policy_options)
def vg_max_pv(vg_name, number, max_options):
return _vg_value_set(vg_name, ['--maxphysicalvolumes', str(number)],
max_options)
def vg_max_lv(vg_name, number, max_options):
return _vg_value_set(vg_name, ['-l', str(number)], max_options)
def vg_uuid_gen(vg_name, ignore, options):
assert ignore is None
return _vg_value_set(vg_name, ['--uuid'], options)
def activate_deactivate(op, name, activate, control_flags, options):
cmd = [op]
cmd.extend(options_to_cli_args(options))
op = '-a'
if control_flags:
# Autoactivation
if (1 << 0) & control_flags:
op += 'a'
# Exclusive locking (Cluster)
if (1 << 1) & control_flags:
op += 'e'
# Local node activation
if (1 << 2) & control_flags:
op += 'l'
# Activation modes
if (1 << 3) & control_flags:
cmd.extend(['--activationmode', 'complete'])
elif (1 << 4) & control_flags:
cmd.extend(['--activationmode', 'partial'])
# Ignore activation skip
if (1 << 5) & control_flags:
cmd.append('--ignoreactivationskip')
if activate:
op += 'y'
else:
op += 'n'
cmd.append(op)
cmd.append(name)
return call(cmd)
def vg_retrieve(vg_specific):
if vg_specific:
assert isinstance(vg_specific, list)
columns = ['vg_name', 'vg_uuid', 'vg_fmt', 'vg_size', 'vg_free',
'vg_sysid', 'vg_extent_size', 'vg_extent_count',
'vg_free_count', 'vg_profile', 'max_lv', 'max_pv',
'pv_count', 'lv_count', 'snap_count', 'vg_seqno',
'vg_mda_count', 'vg_mda_free', 'vg_mda_size',
'vg_mda_used_count', 'vg_attr', 'vg_tags']
cmd = _dc('vgs', ['-o', ','.join(columns)])
if vg_specific:
cmd.extend(vg_specific)
d = []
rc, out, err = call(cmd)
if rc == 0:
d = parse_column_names(out, columns)
return d
def lv_retrieve_with_segments():
columns = ['lv_uuid', 'lv_name', 'lv_path', 'lv_size',
'vg_name', 'pool_lv_uuid', 'pool_lv', 'origin_uuid',
'origin', 'data_percent',
'lv_attr', 'lv_tags', 'vg_uuid', 'lv_active', 'data_lv',
'metadata_lv', 'seg_pe_ranges', 'segtype', 'lv_parent',
'lv_role', 'lv_layout',
'snap_percent', 'metadata_percent', 'copy_percent',
'sync_percent', 'lv_metadata_size', 'move_pv', 'move_pv_uuid']
cmd = _dc('lvs', ['-a', '-o', ','.join(columns)])
rc, out, err = call(cmd)
d = []
if rc == 0:
d = parse_column_names(out, columns)
return d
if __name__ == '__main__':
pv_data = pv_retrieve_with_segs()
for p in pv_data:
print(str(p))

167
daemons/lvmdbusd/fetch.py Normal file
View File

@ -0,0 +1,167 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .pv import load_pvs
from .vg import load_vgs
from .lv import load_lvs
from . import cfg
from .utils import MThreadRunner, log_debug, log_error
import threading
import queue
import traceback
def _main_thread_load(refresh=True, emit_signal=True):
num_total_changes = 0
num_total_changes += load_pvs(
refresh=refresh,
emit_signal=emit_signal,
cache_refresh=False)[1]
num_total_changes += load_vgs(
refresh=refresh,
emit_signal=emit_signal,
cache_refresh=False)[1]
num_total_changes += load_lvs(
refresh=refresh,
emit_signal=emit_signal,
cache_refresh=False)[1]
return num_total_changes
def load(refresh=True, emit_signal=True, cache_refresh=True, log=True,
need_main_thread=True):
# Go through and load all the PVs, VGs and LVs
if cache_refresh:
cfg.db.refresh(log)
if need_main_thread:
rc = MThreadRunner(_main_thread_load, refresh, emit_signal).done()
else:
rc = _main_thread_load(refresh, emit_signal)
return rc
# Even though lvm can handle multiple changes concurrently it really doesn't
# make sense to make a 1-1 fetch of data for each change of lvm because when
# we fetch the data once all previous changes are reflected.
class StateUpdate(object):
class UpdateRequest(object):
def __init__(self, refresh, emit_signal, cache_refresh, log,
need_main_thread):
self.is_done = False
self.refresh = refresh
self.emit_signal = emit_signal
self.cache_refresh = cache_refresh
self.log = log
self.need_main_thread = need_main_thread
self.result = None
self.cond = threading.Condition(threading.Lock())
def done(self):
with self.cond:
if not self.is_done:
self.cond.wait()
return self.result
def set_result(self, result):
with self.cond:
self.result = result
self.is_done = True
self.cond.notify_all()
@staticmethod
def update_thread(obj):
queued_requests = []
while cfg.run.value != 0:
# noinspection PyBroadException
try:
refresh = True
emit_signal = True
cache_refresh = True
log = True
need_main_thread = True
with obj.lock:
wait = not obj.deferred
obj.deferred = False
if len(queued_requests) == 0 and wait:
queued_requests.append(obj.queue.get(True, 2))
# Ok we have one or the deferred queue has some,
# check if any others
try:
while True:
queued_requests.append(obj.queue.get(False))
except queue.Empty:
pass
if len(queued_requests) > 1:
log_debug("Processing %d updates!" % len(queued_requests),
'bg_black', 'fg_light_green')
# We have what we can, run the update with the needed options
for i in queued_requests:
if not i.refresh:
refresh = False
if not i.emit_signal:
emit_signal = False
if not i.cache_refresh:
cache_refresh = False
if not i.log:
log = False
if not i.need_main_thread:
need_main_thread = False
num_changes = load(refresh, emit_signal, cache_refresh, log,
need_main_thread)
# Update is done, let everyone know!
for i in queued_requests:
i.set_result(num_changes)
# Only clear out the requests after we have given them a result
# otherwise we can orphan the waiting threads and they never
# wake up if we get an exception
queued_requests = []
except queue.Empty:
pass
except Exception:
st = traceback.format_exc()
log_error("update_thread exception: \n%s" % st)
cfg.blackbox.dump()
def __init__(self):
self.lock = threading.RLock()
self.queue = queue.Queue()
self.deferred = False
# Do initial load
load(refresh=False, emit_signal=False, need_main_thread=False)
self.thread = threading.Thread(target=StateUpdate.update_thread,
args=(self,))
def load(self, refresh=True, emit_signal=True, cache_refresh=True,
log=True, need_main_thread=True):
# Place this request on the queue and wait for it to be completed
req = StateUpdate.UpdateRequest(refresh, emit_signal, cache_refresh,
log, need_main_thread)
self.queue.put(req)
return req.done()
def event(self):
with self.lock:
self.deferred = True

228
daemons/lvmdbusd/job.py Normal file
View File

@ -0,0 +1,228 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .automatedproperties import AutomatedProperties
from .utils import job_obj_path_generate, mt_async_result, mt_run_no_wait
from . import cfg
from .cfg import JOB_INTERFACE
import dbus
import threading
# noinspection PyUnresolvedReferences
from gi.repository import GLib
# Class that handles a client waiting for something to be complete. We either
# get a timeout or the operation is done.
class WaitingClient(object):
# A timeout occurred
@staticmethod
def _timeout(wc):
with wc.rlock:
if wc.in_use:
wc.in_use = False
# Remove ourselves from waiting client
wc.job_state.remove_waiting_client(wc)
wc.timer_id = -1
mt_async_result(wc.cb, wc.job_state.Complete)
wc.job_state = None
def __init__(self, job_state, tmo, cb, cbe):
self.rlock = threading.RLock()
self.job_state = job_state
self.cb = cb
self.cbe = cbe
self.in_use = True # Indicates if object is in play
self.timer_id = -1
if tmo > 0:
self.timer_id = GLib.timeout_add_seconds(
tmo, WaitingClient._timeout, self)
# The job finished before the timer popped and we are being notified that
# it's done
def notify(self):
with self.rlock:
if self.in_use:
self.in_use = False
# Clear timer
if self.timer_id != -1:
GLib.source_remove(self.timer_id)
self.timer_id = -1
mt_async_result(self.cb, self.job_state.Complete)
self.job_state = None
# noinspection PyPep8Naming
class JobState(object):
def __init__(self, request=None):
self.rlock = threading.RLock()
self._percent = 0
self._complete = False
self._request = request
self._ec = 0
self._stderr = ''
self._waiting_clients = []
# This is an lvm command that is just taking too long and doesn't
# support background operation
if self._request:
# Faking the percentage when we don't have one
self._percent = 1
@property
def Percent(self):
with self.rlock:
return self._percent
@Percent.setter
def Percent(self, value):
with self.rlock:
self._percent = value
@property
def Complete(self):
with self.rlock:
if self._request:
self._complete = self._request.is_done()
return self._complete
@Complete.setter
def Complete(self, value):
with self.rlock:
self._complete = value
self._percent = 100
self.notify_waiting_clients()
@property
def GetError(self):
with self.rlock:
if self.Complete:
if self._request:
(rc, error) = self._request.get_errors()
return (rc, str(error))
else:
return (self._ec, self._stderr)
else:
return (-1, 'Job is not complete!')
def dtor(self):
with self.rlock:
self._request = None
@property
def Result(self):
with self.rlock:
if self._request:
return self._request.result()
return '/'
def add_waiting_client(self, client):
with self.rlock:
# Avoid race condition where it goes complete before we get added
# to the list of waiting clients
if self.Complete:
client.notify()
else:
self._waiting_clients.append(client)
def remove_waiting_client(self, client):
# If a waiting client timer pops before the job is done we will allow
# the client to remove themselves from the list. As we have a lock
# here and a lock in the waiting client too, and they can be obtained
# in different orders, a dead lock can occur.
# As this remove is really optional, we will try to acquire the lock
# and remove. If we are unsuccessful it's not fatal, we just delay
# the time when the objects can be garbage collected by python
if self.rlock.acquire(False):
try:
self._waiting_clients.remove(client)
finally:
self.rlock.release()
def notify_waiting_clients(self):
with self.rlock:
for c in self._waiting_clients:
c.notify()
self._waiting_clients = []
# noinspection PyPep8Naming
class Job(AutomatedProperties):
_Percent_meta = ('d', JOB_INTERFACE)
_Complete_meta = ('b', JOB_INTERFACE)
_Result_meta = ('o', JOB_INTERFACE)
_GetError_meta = ('(is)', JOB_INTERFACE)
def __init__(self, request, job_state=None):
super(Job, self).__init__(job_obj_path_generate())
self.set_interface(JOB_INTERFACE)
if job_state:
self.state = job_state
else:
self.state = JobState(request)
@property
def Percent(self):
return dbus.Double(float(self.state.Percent))
@property
def Complete(self):
return dbus.Boolean(self.state.Complete)
@staticmethod
def _signal_complete(obj):
obj.PropertiesChanged(
JOB_INTERFACE, dict(Complete=dbus.Boolean(obj.state.Complete)), [])
@Complete.setter
def Complete(self, value):
self.state.Complete = value
mt_run_no_wait(Job._signal_complete, self)
@property
def GetError(self):
return dbus.Struct(self.state.GetError, signature="(is)")
@dbus.service.method(dbus_interface=JOB_INTERFACE)
def Remove(self):
if self.state.Complete:
cfg.om.remove_object(self, True)
self.state.dtor()
else:
raise dbus.exceptions.DBusException(
JOB_INTERFACE, 'Job is not complete!')
@dbus.service.method(dbus_interface=JOB_INTERFACE,
in_signature='i',
out_signature='b',
async_callbacks=('cb', 'cbe'))
def Wait(self, timeout, cb, cbe):
if timeout == 0 or self.state.Complete:
cb(dbus.Boolean(self.state.Complete))
else:
self.state.add_waiting_client(
WaitingClient(self.state, timeout, cb, cbe))
@property
def Result(self):
return dbus.ObjectPath(self.state.Result)
@property
def lvm_id(self):
return str(id(self))
@property
def Uuid(self):
import uuid
return uuid.uuid1()

View File

@ -0,0 +1,85 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from . import cfg
def _compare_construction(o_state, new_state):
# We need to check to see if the objects would get constructed
# the same
existing_ctor, existing_path = o_state.creation_signature()
new_ctor, new_path = new_state.creation_signature()
# print("%s == %s and %s == %s" % (str(existing_ctor), str(new_ctor),
# str(existing_path), str(new_path)))
return ((existing_ctor == new_ctor) and (existing_path == new_path))
def common(retrieve, o_type, search_keys,
object_path, refresh, emit_signal, cache_refresh):
num_changes = 0
existing_paths = []
rc = []
if search_keys:
assert isinstance(search_keys, list)
if cache_refresh:
cfg.db.refresh()
objects = retrieve(search_keys, cache_refresh=False)
# If we are doing a refresh we need to know what we have in memory, what's
# in lvm and add those that are new and remove those that are gone!
if refresh:
existing_paths = cfg.om.object_paths_by_type(o_type)
for o in objects:
# Assume we need to add this one to dbus, unless we are refreshing
# and it's already present
return_object = True
if refresh:
# We are refreshing all the PVs from LVM, if this one exists
# we need to refresh our state.
dbus_object = cfg.om.get_object_by_uuid_lvm_id(*o.identifiers())
if dbus_object:
del existing_paths[dbus_object.dbus_object_path()]
# If the old object state and new object state wouldn't be
# created with the same path and same object constructor we
# need to remove the old object and construct the new one
# instead!
if not _compare_construction(dbus_object.state, o):
# Remove existing and construct new one
cfg.om.remove_object(dbus_object, emit_signal)
dbus_object = o.create_dbus_object(None)
cfg.om.register_object(dbus_object, emit_signal)
num_changes += 1
else:
num_changes += dbus_object.refresh(object_state=o)
return_object = False
if return_object:
dbus_object = o.create_dbus_object(object_path)
cfg.om.register_object(dbus_object, emit_signal)
rc.append(dbus_object)
object_path = None
if refresh:
for k in list(existing_paths.keys()):
cfg.om.remove_object(cfg.om.get_object_by_path(k), True)
num_changes += 1
num_changes += len(rc)
return rc, num_changes

832
daemons/lvmdbusd/lv.py Normal file
View File

@ -0,0 +1,832 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .automatedproperties import AutomatedProperties
from . import utils
from .utils import vg_obj_path_generate
import dbus
from . import cmdhandler
from . import cfg
from .cfg import LV_INTERFACE, THIN_POOL_INTERFACE, SNAPSHOT_INTERFACE, \
LV_COMMON_INTERFACE, CACHE_POOL_INTERFACE, LV_CACHED
from .request import RequestEntry
from .utils import n, n32
from .loader import common
from .state import State
from . import background
from .utils import round_size, mt_remove_dbus_objects
from .job import JobState
# Try and build a key for a LV, so that we sort the LVs with least dependencies
# first. This may be error prone because of the flexibility LVM
# provides and what you can stack.
def get_key(i):
name = i['lv_name']
parent = i['lv_parent']
pool = i['pool_lv']
a1 = ""
a2 = ""
if name[0] == '[':
a1 = '#'
# We have a parent
if parent:
# Check if parent is hidden
if parent[0] == '[':
a2 = '##'
else:
a2 = '#'
# If a LV has a pool, then it should be sorted/loaded after the pool
# lv, unless it's a hidden too, then after other hidden, but before visible
if pool:
if pool[0] != '[':
a2 += '~'
else:
a1 = '$' + a1
return "%s%s%s" % (a1, a2, name)
# noinspection PyUnusedLocal
def lvs_state_retrieve(selection, cache_refresh=True):
rc = []
if cache_refresh:
cfg.db.refresh()
# When building up the model, it's best to process LVs with the least
# dependencies to those that are dependant upon other LVs. Otherwise, when
# we are trying to gather information we could be in a position where we
# don't have information available yet.
lvs = sorted(cfg.db.fetch_lvs(selection), key=get_key)
for l in lvs:
rc.append(LvState(
l['lv_uuid'], l['lv_name'],
l['lv_path'], n(l['lv_size']),
l['vg_name'],
l['vg_uuid'], l['pool_lv_uuid'],
l['pool_lv'], l['origin_uuid'], l['origin'],
n32(l['data_percent']), l['lv_attr'],
l['lv_tags'], l['lv_active'], l['data_lv'],
l['metadata_lv'], l['segtype'], l['lv_role'],
l['lv_layout'],
n32(l['snap_percent']),
n32(l['metadata_percent']),
n32(l['copy_percent']),
n32(l['sync_percent']),
n(l['lv_metadata_size']),
l['move_pv'],
l['move_pv_uuid']))
return rc
def load_lvs(lv_name=None, object_path=None, refresh=False, emit_signal=False,
cache_refresh=True):
# noinspection PyUnresolvedReferences
return common(
lvs_state_retrieve,
(LvCommon, Lv, LvThinPool, LvSnapShot),
lv_name, object_path, refresh, emit_signal, cache_refresh)
# noinspection PyPep8Naming,PyUnresolvedReferences,PyUnusedLocal
class LvState(State):
@staticmethod
def _pv_devices(uuid):
rc = []
for pv in sorted(cfg.db.lv_contained_pv(uuid)):
(pv_uuid, pv_name, pv_segs) = pv
pv_obj = cfg.om.get_object_path_by_uuid_lvm_id(pv_uuid, pv_name)
segs_decorate = []
for i in pv_segs:
segs_decorate.append((dbus.UInt64(i[0]),
dbus.UInt64(i[1]),
dbus.String(i[2])))
rc.append((dbus.ObjectPath(pv_obj), segs_decorate))
return dbus.Array(rc, signature="(oa(tts))")
def vg_name_lookup(self):
return cfg.om.get_object_by_path(self.Vg).Name
@property
def lvm_id(self):
return "%s/%s" % (self.vg_name_lookup(), self.Name)
def identifiers(self):
return (self.Uuid, self.lvm_id)
def _get_hidden_lv(self):
rc = dbus.Array([], "o")
vg_name = self.vg_name_lookup()
for l in cfg.db.hidden_lvs(self.Uuid):
full_name = "%s/%s" % (vg_name, l[1])
op = cfg.om.get_object_path_by_uuid_lvm_id(l[0], full_name)
assert op
rc.append(dbus.ObjectPath(op))
return rc
def __init__(self, Uuid, Name, Path, SizeBytes,
vg_name, vg_uuid, pool_lv_uuid, PoolLv,
origin_uuid, OriginLv, DataPercent, Attr, Tags, active,
data_lv, metadata_lv, segtypes, role, layout, SnapPercent,
MetaDataPercent, CopyPercent, SyncPercent, MetaDataSizeBytes,
move_pv, move_pv_uuid):
utils.init_class_from_arguments(self)
# The segtypes is possibly an array with potentially dupes or a single
# value
self._segs = dbus.Array([], signature='s')
if not isinstance(segtypes, list):
self._segs.append(dbus.String(segtypes))
else:
self._segs.extend([dbus.String(x) for x in set(segtypes)])
self.Vg = cfg.om.get_object_path_by_uuid_lvm_id(
vg_uuid, vg_name, vg_obj_path_generate)
self.Devices = LvState._pv_devices(self.Uuid)
if PoolLv:
gen = utils.lv_object_path_method(Name, (Attr, layout, role))
self.PoolLv = cfg.om.get_object_path_by_uuid_lvm_id(
pool_lv_uuid, '%s/%s' % (vg_name, PoolLv), gen)
else:
self.PoolLv = '/'
if OriginLv:
self.OriginLv = \
cfg.om.get_object_path_by_uuid_lvm_id(
origin_uuid, '%s/%s' % (vg_name, OriginLv),
vg_obj_path_generate)
else:
self.OriginLv = '/'
self.HiddenLvs = self._get_hidden_lv()
@property
def SegType(self):
return self._segs
def _object_path_create(self):
return utils.lv_object_path_method(
self.Name, (self.Attr, self.layout, self.role))
def _object_type_create(self):
if self.Attr[0] == 't':
return LvThinPool
elif self.Attr[0] == 'C':
if 'pool' in self.layout:
return LvCachePool
else:
return LvCacheLv
elif self.Name[0] == '[':
return LvCommon
elif self.OriginLv != '/':
return LvSnapShot
else:
return Lv
def create_dbus_object(self, path):
if not path:
path = cfg.om.get_object_path_by_uuid_lvm_id(
self.Uuid, self.lvm_id, self._object_path_create())
obj_ctor = self._object_type_create()
return obj_ctor(path, self)
def creation_signature(self):
klass = self._object_type_create()
path_method = self._object_path_create()
return (klass, path_method)
# noinspection PyPep8Naming
@utils.dbus_property(LV_COMMON_INTERFACE, 'Uuid', 's')
@utils.dbus_property(LV_COMMON_INTERFACE, 'Name', 's')
@utils.dbus_property(LV_COMMON_INTERFACE, 'Path', 's')
@utils.dbus_property(LV_COMMON_INTERFACE, 'SizeBytes', 't')
@utils.dbus_property(LV_COMMON_INTERFACE, 'SegType', 'as')
@utils.dbus_property(LV_COMMON_INTERFACE, 'Vg', 'o')
@utils.dbus_property(LV_COMMON_INTERFACE, 'OriginLv', 'o')
@utils.dbus_property(LV_COMMON_INTERFACE, 'PoolLv', 'o')
@utils.dbus_property(LV_COMMON_INTERFACE, 'Devices', "a(oa(tts))")
@utils.dbus_property(LV_COMMON_INTERFACE, 'HiddenLvs', "ao")
@utils.dbus_property(LV_COMMON_INTERFACE, 'Attr', 's')
@utils.dbus_property(LV_COMMON_INTERFACE, 'DataPercent', 'u')
@utils.dbus_property(LV_COMMON_INTERFACE, 'SnapPercent', 'u')
@utils.dbus_property(LV_COMMON_INTERFACE, 'DataPercent', 'u')
@utils.dbus_property(LV_COMMON_INTERFACE, 'MetaDataPercent', 'u')
@utils.dbus_property(LV_COMMON_INTERFACE, 'CopyPercent', 'u')
@utils.dbus_property(LV_COMMON_INTERFACE, 'SyncPercent', 'u')
@utils.dbus_property(LV_COMMON_INTERFACE, 'MetaDataSizeBytes', 't')
class LvCommon(AutomatedProperties):
_Tags_meta = ("as", LV_COMMON_INTERFACE)
_Roles_meta = ("as", LV_COMMON_INTERFACE)
_IsThinVolume_meta = ("b", LV_COMMON_INTERFACE)
_IsThinPool_meta = ("b", LV_COMMON_INTERFACE)
_Active_meta = ("b", LV_COMMON_INTERFACE)
_VolumeType_meta = ("(ss)", LV_COMMON_INTERFACE)
_Permissions_meta = ("(ss)", LV_COMMON_INTERFACE)
_AllocationPolicy_meta = ("(ss)", LV_COMMON_INTERFACE)
_State_meta = ("(ss)", LV_COMMON_INTERFACE)
_TargetType_meta = ("(ss)", LV_COMMON_INTERFACE)
_Health_meta = ("(ss)", LV_COMMON_INTERFACE)
_FixedMinor_meta = ('b', LV_COMMON_INTERFACE)
_ZeroBlocks_meta = ('b', LV_COMMON_INTERFACE)
_SkipActivation_meta = ('b', LV_COMMON_INTERFACE)
_MovePv_meta = ('o', LV_COMMON_INTERFACE)
def _get_move_pv(self):
path = None
# It's likely that the move_pv is empty
if self.state.move_pv_uuid and self.state.move_pv:
path = cfg.om.get_object_path_by_uuid_lvm_id(
self.state.move_pv_uuid, self.state.move_pv)
if not path:
path = '/'
return path
# noinspection PyUnusedLocal,PyPep8Naming
def __init__(self, object_path, object_state):
super(LvCommon, self).__init__(object_path, lvs_state_retrieve)
self.set_interface(LV_COMMON_INTERFACE)
self.state = object_state
self._move_pv = self._get_move_pv()
@staticmethod
def handle_execute(rc, out, err):
if rc == 0:
cfg.load()
else:
# Need to work on error handling, need consistent
raise dbus.exceptions.DBusException(
LV_INTERFACE,
'Exit code %s, stderr = %s' % (str(rc), err))
@staticmethod
def validate_dbus_object(lv_uuid, lv_name):
dbo = cfg.om.get_object_by_uuid_lvm_id(lv_uuid, lv_name)
if not dbo:
raise dbus.exceptions.DBusException(
LV_INTERFACE,
'LV with uuid %s and name %s not present!' %
(lv_uuid, lv_name))
return dbo
@property
def VolumeType(self):
type_map = {'C': 'Cache', 'm': 'mirrored',
'M': 'Mirrored without initial sync', 'o': 'origin',
'O': 'Origin with merging snapshot', 'r': 'raid',
'R': 'Raid without initial sync', 's': 'snapshot',
'S': 'merging Snapshot', 'p': 'pvmove',
'v': 'virtual', 'i': 'mirror or raid image',
'I': 'mirror or raid Image out-of-sync',
'l': 'mirror log device', 'c': 'under conversion',
'V': 'thin Volume', 't': 'thin pool', 'T': 'Thin pool data',
'e': 'raid or pool metadata or pool metadata spare',
'-': 'Unspecified'}
return dbus.Struct((self.state.Attr[0], type_map[self.state.Attr[0]]),
signature="as")
@property
def Permissions(self):
type_map = {'w': 'writable', 'r': 'read-only',
'R': 'Read-only activation of non-read-only volume',
'-': 'Unspecified'}
return dbus.Struct((self.state.Attr[1], type_map[self.state.Attr[1]]),
signature="(ss)")
@property
def AllocationPolicy(self):
type_map = {'a': 'anywhere', 'A': 'anywhere locked',
'c': 'contiguous', 'C': 'contiguous locked',
'i': 'inherited', 'I': 'inherited locked',
'l': 'cling', 'L': 'cling locked',
'n': 'normal', 'N': 'normal locked', '-': 'Unspecified'}
return dbus.Struct((self.state.Attr[2], type_map[self.state.Attr[2]]),
signature="(ss)")
@property
def FixedMinor(self):
return dbus.Boolean(self.state.Attr[3] == 'm')
@property
def State(self):
type_map = {'a': 'active', 's': 'suspended', 'I': 'Invalid snapshot',
'S': 'invalid Suspended snapshot',
'm': 'snapshot merge failed',
'M': 'suspended snapshot (M)erge failed',
'd': 'mapped device present without tables',
'i': 'mapped device present with inactive table',
'X': 'unknown', '-': 'Unspecified'}
return dbus.Struct((self.state.Attr[4], type_map[self.state.Attr[4]]),
signature="(ss)")
@property
def TargetType(self):
type_map = {'C': 'Cache', 'm': 'mirror', 'r': 'raid',
's': 'snapshot', 't': 'thin', 'u': 'unknown',
'v': 'virtual', '-': 'Unspecified'}
return dbus.Struct((self.state.Attr[6], type_map[self.state.Attr[6]]),
signature="(ss)")
@property
def ZeroBlocks(self):
return dbus.Boolean(self.state.Attr[7] == 'z')
@property
def Health(self):
type_map = {'p': 'partial', 'r': 'refresh',
'm': 'mismatches', 'w': 'writemostly',
'X': 'X unknown', '-': 'Unspecified'}
return dbus.Struct((self.state.Attr[8], type_map[self.state.Attr[8]]),
signature="(ss)")
@property
def SkipActivation(self):
return dbus.Boolean(self.state.Attr[9] == 'k')
def vg_name_lookup(self):
return self.state.vg_name_lookup()
def lv_full_name(self):
return "%s/%s" % (self.state.vg_name_lookup(), self.state.Name)
@property
def identifiers(self):
return self.state.identifiers
@property
def Tags(self):
return utils.parse_tags(self.state.Tags)
@property
def Roles(self):
return utils.parse_tags(self.state.role)
@property
def lvm_id(self):
return self.state.lvm_id
@property
def IsThinVolume(self):
return dbus.Boolean(self.state.Attr[0] == 'V')
@property
def IsThinPool(self):
return dbus.Boolean(self.state.Attr[0] == 't')
@property
def Active(self):
return dbus.Boolean(self.state.active == "active")
@property
def MovePv(self):
return dbus.ObjectPath(self._move_pv)
# noinspection PyPep8Naming
class Lv(LvCommon):
def _fetch_hidden(self, name):
# The name is vg/name
full_name = "%s/%s" % (self.vg_name_lookup(), name)
return cfg.om.get_object_path_by_lvm_id(full_name)
def _get_data_meta(self):
# Get the data
return (self._fetch_hidden(self.state.data_lv),
self._fetch_hidden(self.state.metadata_lv))
# noinspection PyUnusedLocal,PyPep8Naming
def __init__(self, object_path, object_state):
super(Lv, self).__init__(object_path, object_state)
self.set_interface(LV_INTERFACE)
self.state = object_state
@staticmethod
def _remove(lv_uuid, lv_name, remove_options):
# Make sure we have a dbus object representing it
LvCommon.validate_dbus_object(lv_uuid, lv_name)
# Remove the LV, if successful then remove from the model
rc, out, err = cmdhandler.lv_remove(lv_name, remove_options)
LvCommon.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Remove(self, tmo, remove_options, cb, cbe):
r = RequestEntry(
tmo, Lv._remove,
(self.Uuid, self.lvm_id, remove_options),
cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _rename(lv_uuid, lv_name, new_name, rename_options):
# Make sure we have a dbus object representing it
LvCommon.validate_dbus_object(lv_uuid, lv_name)
# Rename the logical volume
rc, out, err = cmdhandler.lv_rename(lv_name, new_name,
rename_options)
LvCommon.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='sia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Rename(self, name, tmo, rename_options, cb, cbe):
utils.validate_lv_name(LV_INTERFACE, self.vg_name_lookup(), name)
r = RequestEntry(
tmo, Lv._rename,
(self.Uuid, self.lvm_id, name, rename_options),
cb, cbe, False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='o(tt)a(ott)ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Move(self, pv_src_obj, pv_source_range,
pv_dests_and_ranges,
tmo, move_options, cb, cbe):
job_state = JobState()
r = RequestEntry(
tmo, background.move,
(LV_INTERFACE, self.lvm_id, pv_src_obj, pv_source_range,
pv_dests_and_ranges, move_options, job_state), cb, cbe, False,
job_state)
background.cmd_runner(r)
@staticmethod
def _snap_shot(lv_uuid, lv_name, name, optional_size,
snapshot_options):
# Make sure we have a dbus object representing it
dbo = LvCommon.validate_dbus_object(lv_uuid, lv_name)
# If you specify a size you get a 'thick' snapshot even if
# it is a thin lv
if not dbo.IsThinVolume:
if optional_size == 0:
space = dbo.SizeBytes / 80
remainder = space % 512
optional_size = space + 512 - remainder
rc, out, err = cmdhandler.vg_lv_snapshot(
lv_name, snapshot_options, name, optional_size)
LvCommon.handle_execute(rc, out, err)
full_name = "%s/%s" % (dbo.vg_name_lookup(), name)
return cfg.om.get_object_path_by_lvm_id(full_name)
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='stia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def Snapshot(self, name, optional_size, tmo,
snapshot_options, cb, cbe):
utils.validate_lv_name(LV_INTERFACE, self.vg_name_lookup(), name)
r = RequestEntry(
tmo, Lv._snap_shot,
(self.Uuid, self.lvm_id, name,
optional_size, snapshot_options), cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _resize(lv_uuid, lv_name, new_size_bytes, pv_dests_and_ranges,
resize_options):
# Make sure we have a dbus object representing it
pv_dests = []
dbo = LvCommon.validate_dbus_object(lv_uuid, lv_name)
# If we have PVs, verify them
if len(pv_dests_and_ranges):
for pr in pv_dests_and_ranges:
pv_dbus_obj = cfg.om.get_object_by_path(pr[0])
if not pv_dbus_obj:
raise dbus.exceptions.DBusException(
LV_INTERFACE,
'PV Destination (%s) not found' % pr[0])
pv_dests.append((pv_dbus_obj.lvm_id, pr[1], pr[2]))
size_change = new_size_bytes - dbo.SizeBytes
rc, out, err = cmdhandler.lv_resize(dbo.lvm_id, size_change,
pv_dests, resize_options)
LvCommon.handle_execute(rc, out, err)
return "/"
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='ta(ott)ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Resize(self, new_size_bytes, pv_dests_and_ranges, tmo,
resize_options, cb, cbe):
"""
Resize a LV
:param new_size_bytes: The requested final size in bytes
:param pv_dests_and_ranges: An array of pv object paths and src &
dst. segment ranges
:param tmo: -1 to wait forever, 0 to return job immediately, else
number of seconds to wait for operation to complete
before getting a job
:param resize_options: key/value hash of options
:param cb: Used by framework not client facing API
:param cbe: Used by framework not client facing API
:return: '/' if complete, else job object path
"""
r = RequestEntry(
tmo, Lv._resize,
(self.Uuid, self.lvm_id, round_size(new_size_bytes),
pv_dests_and_ranges,
resize_options), cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@staticmethod
def _lv_activate_deactivate(uuid, lv_name, activate, control_flags,
options):
# Make sure we have a dbus object representing it
LvCommon.validate_dbus_object(uuid, lv_name)
rc, out, err = cmdhandler.activate_deactivate(
'lvchange', lv_name, activate, control_flags, options)
LvCommon.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='tia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Activate(self, control_flags, tmo, activate_options, cb, cbe):
r = RequestEntry(
tmo, Lv._lv_activate_deactivate,
(self.state.Uuid, self.state.lvm_id, True,
control_flags, activate_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
# noinspection PyProtectedMember
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='tia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Deactivate(self, control_flags, tmo, activate_options, cb, cbe):
r = RequestEntry(
tmo, Lv._lv_activate_deactivate,
(self.state.Uuid, self.state.lvm_id, False,
control_flags, activate_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@staticmethod
def _add_rm_tags(uuid, lv_name, tags_add, tags_del, tag_options):
# Make sure we have a dbus object representing it
LvCommon.validate_dbus_object(uuid, lv_name)
rc, out, err = cmdhandler.lv_tag(
lv_name, tags_add, tags_del, tag_options)
LvCommon.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='asia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def TagsAdd(self, tags, tmo, tag_options, cb, cbe):
for t in tags:
utils.validate_tag(LV_INTERFACE, t)
r = RequestEntry(
tmo, Lv._add_rm_tags,
(self.state.Uuid, self.state.lvm_id,
tags, None, tag_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=LV_INTERFACE,
in_signature='asia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def TagsDel(self, tags, tmo, tag_options, cb, cbe):
for t in tags:
utils.validate_tag(LV_INTERFACE, t)
r = RequestEntry(
tmo, Lv._add_rm_tags,
(self.state.Uuid, self.state.lvm_id,
None, tags, tag_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
# noinspection PyPep8Naming
class LvThinPool(Lv):
_DataLv_meta = ("o", THIN_POOL_INTERFACE)
_MetaDataLv_meta = ("o", THIN_POOL_INTERFACE)
def __init__(self, object_path, object_state):
super(LvThinPool, self).__init__(object_path, object_state)
self.set_interface(THIN_POOL_INTERFACE)
self._data_lv, self._metadata_lv = self._get_data_meta()
@property
def DataLv(self):
return dbus.ObjectPath(self._data_lv)
@property
def MetaDataLv(self):
return dbus.ObjectPath(self._metadata_lv)
@staticmethod
def _lv_create(lv_uuid, lv_name, name, size_bytes, create_options):
# Make sure we have a dbus object representing it
dbo = LvCommon.validate_dbus_object(lv_uuid, lv_name)
rc, out, err = cmdhandler.lv_lv_create(
lv_name, create_options, name, size_bytes)
LvCommon.handle_execute(rc, out, err)
full_name = "%s/%s" % (dbo.vg_name_lookup(), name)
return cfg.om.get_object_path_by_lvm_id(full_name)
@dbus.service.method(
dbus_interface=THIN_POOL_INTERFACE,
in_signature='stia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def LvCreate(self, name, size_bytes, tmo, create_options, cb, cbe):
utils.validate_lv_name(THIN_POOL_INTERFACE, self.vg_name_lookup(), name)
r = RequestEntry(
tmo, LvThinPool._lv_create,
(self.Uuid, self.lvm_id, name,
round_size(size_bytes), create_options), cb, cbe)
cfg.worker_q.put(r)
# noinspection PyPep8Naming
class LvCachePool(Lv):
_DataLv_meta = ("o", CACHE_POOL_INTERFACE)
_MetaDataLv_meta = ("o", CACHE_POOL_INTERFACE)
def __init__(self, object_path, object_state):
super(LvCachePool, self).__init__(object_path, object_state)
self.set_interface(CACHE_POOL_INTERFACE)
self._data_lv, self._metadata_lv = self._get_data_meta()
@property
def DataLv(self):
return dbus.ObjectPath(self._data_lv)
@property
def MetaDataLv(self):
return dbus.ObjectPath(self._metadata_lv)
@staticmethod
def _cache_lv(lv_uuid, lv_name, lv_object_path, cache_options):
# Make sure we have a dbus object representing cache pool
dbo = LvCommon.validate_dbus_object(lv_uuid, lv_name)
# Make sure we have dbus object representing lv to cache
lv_to_cache = cfg.om.get_object_by_path(lv_object_path)
if lv_to_cache:
fcn = lv_to_cache.lv_full_name()
rc, out, err = cmdhandler.lv_cache_lv(
dbo.lv_full_name(), fcn, cache_options)
if rc == 0:
# When we cache an LV, the cache pool and the lv that is getting
# cached need to be removed from the object manager and
# re-created as their interfaces have changed!
mt_remove_dbus_objects((dbo, lv_to_cache))
cfg.load()
lv_converted = cfg.om.get_object_path_by_lvm_id(fcn)
else:
raise dbus.exceptions.DBusException(
LV_INTERFACE,
'Exit code %s, stderr = %s' % (str(rc), err))
else:
raise dbus.exceptions.DBusException(
LV_INTERFACE, 'LV to cache with object path %s not present!' %
lv_object_path)
return lv_converted
@dbus.service.method(
dbus_interface=CACHE_POOL_INTERFACE,
in_signature='oia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def CacheLv(self, lv_object, tmo, cache_options, cb, cbe):
r = RequestEntry(
tmo, LvCachePool._cache_lv,
(self.Uuid, self.lvm_id, lv_object,
cache_options), cb, cbe)
cfg.worker_q.put(r)
# noinspection PyPep8Naming
class LvCacheLv(Lv):
_CachePool_meta = ("o", LV_CACHED)
def __init__(self, object_path, object_state):
super(LvCacheLv, self).__init__(object_path, object_state)
self.set_interface(LV_CACHED)
@property
def CachePool(self):
return dbus.ObjectPath(self.state.PoolLv)
@staticmethod
def _detach_lv(lv_uuid, lv_name, detach_options, destroy_cache):
# Make sure we have a dbus object representing cache pool
dbo = LvCommon.validate_dbus_object(lv_uuid, lv_name)
# Get current cache name
cache_pool = cfg.om.get_object_by_path(dbo.CachePool)
rc, out, err = cmdhandler.lv_detach_cache(
dbo.lv_full_name(), detach_options, destroy_cache)
if rc == 0:
# The cache pool gets removed as hidden and put back to
# visible, so lets delete
mt_remove_dbus_objects((cache_pool, dbo))
cfg.load()
uncached_lv_path = cfg.om.get_object_path_by_lvm_id(lv_name)
else:
raise dbus.exceptions.DBusException(
LV_INTERFACE,
'Exit code %s, stderr = %s' % (str(rc), err))
return uncached_lv_path
@dbus.service.method(
dbus_interface=LV_CACHED,
in_signature='bia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def DetachCachePool(self, destroy_cache, tmo, detach_options, cb, cbe):
r = RequestEntry(
tmo, LvCacheLv._detach_lv,
(self.Uuid, self.lvm_id, detach_options,
destroy_cache), cb, cbe)
cfg.worker_q.put(r)
# noinspection PyPep8Naming
class LvSnapShot(Lv):
def __init__(self, object_path, object_state):
super(LvSnapShot, self).__init__(object_path, object_state)
self.set_interface(SNAPSHOT_INTERFACE)
@dbus.service.method(
dbus_interface=SNAPSHOT_INTERFACE,
in_signature='ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Merge(self, tmo, merge_options, cb, cbe):
job_state = JobState()
r = RequestEntry(tmo, background.merge,
(SNAPSHOT_INTERFACE, self.Uuid, self.lvm_id,
merge_options, job_state), cb, cbe, False,
job_state)
background.cmd_runner(r)

View File

@ -0,0 +1,269 @@
#!/usr/bin/env python3
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2015-2016, Vratislav Podzimek <vpodzime@redhat.com>
import subprocess
import shlex
from fcntl import fcntl, F_GETFL, F_SETFL
import os
import traceback
import sys
import tempfile
import time
import select
import copy
try:
import simplejson as json
except ImportError:
import json
from lvmdbusd.cfg import LVM_CMD
from lvmdbusd.utils import log_debug, log_error, add_no_notify
SHELL_PROMPT = "lvm> "
def _quote_arg(arg):
if len(shlex.split(arg)) > 1:
return '"%s"' % arg
else:
return arg
class LVMShellProxy(object):
@staticmethod
def _read(stream):
tmp = stream.read()
if tmp:
return tmp.decode("utf-8")
return ''
# Read until we get prompt back and a result
# @param: no_output Caller expects no output to report FD
# Returns stdout, report, stderr (report is JSON!)
def _read_until_prompt(self, no_output=False):
stdout = ""
report = ""
stderr = ""
keep_reading = True
extra_passes = 3
report_json = {}
prev_report_len = 0
# Try reading from all FDs to prevent one from filling up and causing
# a hang. Keep reading until we get the prompt back and the report
# FD does not contain valid JSON
while keep_reading:
try:
rd_fd = [
self.lvm_shell.stdout.fileno(),
self.report_stream.fileno(),
self.lvm_shell.stderr.fileno()]
ready = select.select(rd_fd, [], [], 2)
for r in ready[0]:
if r == self.lvm_shell.stdout.fileno():
stdout += LVMShellProxy._read(self.lvm_shell.stdout)
elif r == self.report_stream.fileno():
report += LVMShellProxy._read(self.report_stream)
elif r == self.lvm_shell.stderr.fileno():
stderr += LVMShellProxy._read(self.lvm_shell.stderr)
# Check to see if the lvm process died on us
if self.lvm_shell.poll():
raise Exception(self.lvm_shell.returncode, "%s" % stderr)
if stdout.endswith(SHELL_PROMPT):
if no_output:
keep_reading = False
else:
cur_report_len = len(report)
if cur_report_len != 0:
# Only bother to parse if we have more data
if prev_report_len != cur_report_len:
prev_report_len = cur_report_len
# Parse the JSON if it's good we are done,
# if not we will try to read some more.
try:
report_json = json.loads(report)
keep_reading = False
except ValueError:
pass
if keep_reading:
extra_passes -= 1
if extra_passes <= 0:
if len(report):
raise ValueError("Invalid json: %s" %
report)
else:
raise ValueError(
"lvm returned no JSON output!")
except IOError as ioe:
log_debug(str(ioe))
pass
return stdout, report_json, stderr
def _write_cmd(self, cmd):
cmd_bytes = bytes(cmd, "utf-8")
num_written = self.lvm_shell.stdin.write(cmd_bytes)
assert (num_written == len(cmd_bytes))
self.lvm_shell.stdin.flush()
@staticmethod
def _make_non_block(stream):
flags = fcntl(stream, F_GETFL)
fcntl(stream, F_SETFL, flags | os.O_NONBLOCK)
def __init__(self):
# Create a temp directory
tmp_dir = tempfile.mkdtemp(prefix="lvmdbus_")
tmp_file = "%s/lvmdbus_report" % (tmp_dir)
try:
# Lets create fifo for the report output
os.mkfifo(tmp_file, 0o600)
except FileExistsError:
pass
# We have to open non-blocking as the other side isn't open until
# we actually fork the process.
self.report_fd = os.open(tmp_file, os.O_NONBLOCK)
self.report_stream = os.fdopen(self.report_fd, 'rb', 0)
# Setup the environment for using our own socket for reporting
local_env = copy.deepcopy(os.environ)
local_env["LVM_REPORT_FD"] = "32"
local_env["LVM_COMMAND_PROFILE"] = "lvmdbusd"
# Disable the abort logic if lvm logs too much, which easily happens
# when utilizing the lvm shell.
local_env["LVM_LOG_FILE_MAX_LINES"] = "0"
# run the lvm shell
self.lvm_shell = subprocess.Popen(
[LVM_CMD + " 32>%s" % tmp_file],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=local_env,
stderr=subprocess.PIPE, close_fds=True, shell=True)
try:
LVMShellProxy._make_non_block(self.lvm_shell.stdout)
LVMShellProxy._make_non_block(self.lvm_shell.stderr)
# wait for the first prompt
errors = self._read_until_prompt(no_output=True)[2]
if errors and len(errors):
raise RuntimeError(errors)
except:
raise
finally:
# These will get deleted when the FD count goes to zero so we
# can be sure to clean up correctly no matter how we finish
os.unlink(tmp_file)
os.rmdir(tmp_dir)
def get_error_msg(self):
# We got an error, lets go fetch the error message
self._write_cmd('lastlog\n')
# read everything from the STDOUT to the next prompt
stdout, report_json, stderr = self._read_until_prompt()
if 'log' in report_json:
error_msg = ""
# Walk the entire log array and build an error string
for log_entry in report_json['log']:
if log_entry['log_type'] == "error":
if error_msg:
error_msg += ', ' + log_entry['log_message']
else:
error_msg = log_entry['log_message']
return error_msg
return 'No error reason provided! (missing "log" section)'
def call_lvm(self, argv, debug=False):
rc = 1
error_msg = ""
if self.lvm_shell.poll():
raise Exception(
self.lvm_shell.returncode,
"Underlying lvm shell process is not present!")
argv = add_no_notify(argv)
# create the command string
cmd = " ".join(_quote_arg(arg) for arg in argv)
cmd += "\n"
# run the command by writing it to the shell's STDIN
self._write_cmd(cmd)
# read everything from the STDOUT to the next prompt
stdout, report_json, stderr = self._read_until_prompt()
# Parse the report to see what happened
if 'log' in report_json:
if report_json['log'][-1:][0]['log_ret_code'] == '1':
rc = 0
else:
error_msg = self.get_error_msg()
if debug or rc != 0:
log_error(('CMD: %s' % cmd))
log_error(("EC = %d" % rc))
log_error(("ERROR_MSG=\n %s\n" % error_msg))
return rc, report_json, error_msg
def exit_shell(self):
try:
self._write_cmd('exit\n')
except Exception as e:
log_error(str(e))
def __del__(self):
try:
self.lvm_shell.terminate()
except:
pass
if __name__ == "__main__":
shell = LVMShellProxy()
in_line = "start"
try:
while in_line:
in_line = input("lvm> ")
if in_line:
start = time.time()
ret, out, err = shell.call_lvm(in_line.split())
end = time.time()
print(("RC: %d" % ret))
print(("OUT:\n%s" % out))
print(("ERR:\n%s" % err))
print("Command = %f seconds" % (end - start))
except KeyboardInterrupt:
pass
except EOFError:
pass
except Exception:
traceback.print_exc(file=sys.stdout)

540
daemons/lvmdbusd/lvmdb.py Executable file
View File

@ -0,0 +1,540 @@
#!/usr/bin/env python3
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from collections import OrderedDict
import pprint as prettyprint
import os
import sys
from lvmdbusd import cmdhandler
from lvmdbusd.utils import log_debug, log_error
class DataStore(object):
def __init__(self, usejson=True):
self.pvs = {}
self.vgs = {}
self.lvs = {}
self.pv_lvs = {}
self.lv_pvs = {}
self.lvs_hidden = {}
self.pv_path_to_uuid = {}
self.vg_name_to_uuid = {}
self.lv_full_name_to_uuid = {}
self.lvs_in_vgs = {}
self.pvs_in_vgs = {}
# self.refresh()
self.num_refreshes = 0
if usejson:
self.json = cmdhandler.supports_json()
else:
self.json = usejson
@staticmethod
def _insert_record(table, key, record, allowed_multiple):
if key in table:
existing = table[key]
for rec_k, rec_v in record.items():
if rec_k in allowed_multiple:
# This column name allows us to store multiple value for
# each type
if not isinstance(existing[rec_k], list):
existing_value = existing[rec_k]
existing[rec_k] = [existing_value, rec_v]
else:
existing[rec_k].append(rec_v)
else:
# If something is not expected to have changing values
# lets ensure that
if existing[rec_k] != rec_v:
raise RuntimeError(
"existing[%s]=%s != %s" %
(rec_k, str(existing[rec_k]),
str(rec_v)))
else:
table[key] = record
@staticmethod
def _pvs_parse_common(c_pvs, c_pvs_in_vgs, c_lookup):
for p in c_pvs.values():
# Capture which PVs are associated with which VG
if p['vg_uuid'] not in c_pvs_in_vgs:
c_pvs_in_vgs[p['vg_uuid']] = []
if p['vg_name']:
c_pvs_in_vgs[p['vg_uuid']].append(
(p['pv_name'], p['pv_uuid']))
# Lookup for translating between /dev/<name> and pv uuid
c_lookup[p['pv_name']] = p['pv_uuid']
@staticmethod
def _parse_pvs(_pvs):
pvs = sorted(_pvs, key=lambda pk: pk['pv_name'])
c_pvs = OrderedDict()
c_lookup = {}
c_pvs_in_vgs = {}
for p in pvs:
DataStore._insert_record(
c_pvs, p['pv_uuid'], p,
['pvseg_start', 'pvseg_size', 'segtype'])
DataStore._pvs_parse_common(c_pvs, c_pvs_in_vgs, c_lookup)
return c_pvs, c_lookup, c_pvs_in_vgs
@staticmethod
def _parse_pvs_json(_all):
c_pvs = OrderedDict()
c_lookup = {}
c_pvs_in_vgs = {}
# Each item item in the report is a collection of information pertaining
# to the vg
for r in _all['report']:
tmp_pv = []
# Get the pv data for this VG.
if 'pv' in r:
tmp_pv.extend(r['pv'])
# Sort them
sorted_tmp_pv = sorted(tmp_pv, key=lambda pk: pk['pv_name'])
# Add them to result set
for p in sorted_tmp_pv:
c_pvs[p['pv_uuid']] = p
if 'pvseg' in r:
for s in r['pvseg']:
r = c_pvs[s['pv_uuid']]
r.setdefault('pvseg_start', []).append(s['pvseg_start'])
r.setdefault('pvseg_size', []).append(s['pvseg_size'])
r.setdefault('segtype', []).append(s['segtype'])
# TODO: Remove this bug work around when we have orphan segs.
for i in c_pvs.values():
if 'pvseg_start' not in i:
i['pvseg_start'] = '0'
i['pvseg_size'] = i['pv_pe_count']
i['segtype'] = 'free'
DataStore._pvs_parse_common(c_pvs, c_pvs_in_vgs, c_lookup)
return c_pvs, c_lookup, c_pvs_in_vgs
@staticmethod
def _parse_vgs(_vgs):
vgs = sorted(_vgs, key=lambda vk: vk['vg_name'])
c_vgs = OrderedDict()
c_lookup = {}
for i in vgs:
c_lookup[i['vg_name']] = i['vg_uuid']
DataStore._insert_record(c_vgs, i['vg_uuid'], i, [])
return c_vgs, c_lookup
@staticmethod
def _parse_vgs_json(_all):
tmp_vg = []
for r in _all['report']:
# Get the pv data for this VG.
if 'vg' in r:
tmp_vg.extend(r['vg'])
# Sort for consistent output, however this is optional
vgs = sorted(tmp_vg, key=lambda vk: vk['vg_name'])
c_vgs = OrderedDict()
c_lookup = {}
for i in vgs:
c_lookup[i['vg_name']] = i['vg_uuid']
c_vgs[i['vg_uuid']] = i
return c_vgs, c_lookup
@staticmethod
def _parse_lvs_common(c_lvs, c_lv_full_lookup):
c_lvs_in_vgs = OrderedDict()
c_lvs_hidden = OrderedDict()
for i in c_lvs.values():
if i['vg_uuid'] not in c_lvs_in_vgs:
c_lvs_in_vgs[i['vg_uuid']] = []
c_lvs_in_vgs[
i['vg_uuid']].append(
(i['lv_name'],
(i['lv_attr'], i['lv_layout'], i['lv_role']),
i['lv_uuid']))
if i['lv_parent']:
# Lookup what the parent refers too
parent_name = i['lv_parent']
full_parent_name = "%s/%s" % (i['vg_name'], parent_name)
if full_parent_name not in c_lv_full_lookup:
parent_name = '[%s]' % (parent_name)
full_parent_name = "%s/%s" % (i['vg_name'], parent_name)
parent_uuid = c_lv_full_lookup[full_parent_name]
if parent_uuid not in c_lvs_hidden:
c_lvs_hidden[parent_uuid] = []
c_lvs_hidden[parent_uuid].append(
(i['lv_uuid'], i['lv_name']))
return c_lvs, c_lvs_in_vgs, c_lvs_hidden, c_lv_full_lookup
@staticmethod
def _parse_lvs(_lvs):
lvs = sorted(_lvs, key=lambda vk: vk['lv_name'])
c_lvs = OrderedDict()
c_lv_full_lookup = OrderedDict()
for i in lvs:
full_name = "%s/%s" % (i['vg_name'], i['lv_name'])
c_lv_full_lookup[full_name] = i['lv_uuid']
DataStore._insert_record(
c_lvs, i['lv_uuid'], i,
['seg_pe_ranges', 'segtype'])
return DataStore._parse_lvs_common(c_lvs, c_lv_full_lookup)
@staticmethod
def _parse_lvs_json(_all):
c_lvs = OrderedDict()
c_lv_full_lookup = {}
# Each item item in the report is a collection of information pertaining
# to the vg
for r in _all['report']:
# Get the lv data for this VG.
if 'lv' in r:
# Add them to result set
for i in r['lv']:
full_name = "%s/%s" % (i['vg_name'], i['lv_name'])
c_lv_full_lookup[full_name] = i['lv_uuid']
c_lvs[i['lv_uuid']] = i
# Add in the segment data
if 'seg' in r:
for s in r['seg']:
r = c_lvs[s['lv_uuid']]
r.setdefault('seg_pe_ranges', []).append(s['seg_pe_ranges'])
r.setdefault('segtype', []).append(s['segtype'])
return DataStore._parse_lvs_common(c_lvs, c_lv_full_lookup)
@staticmethod
def _make_list(l):
if not isinstance(l, list):
l = [l]
return l
@staticmethod
def _parse_seg_entry(se, segtype):
if se:
# print("_parse_seg_entry %s %s" % (str(se), str(segtype)))
device, segs = se.split(":")
start, end = segs.split('-')
return (device, (start, end), segtype)
else:
return ("", (), segtype)
@staticmethod
def _build_segments(l, seg_types):
rc = []
l = DataStore._make_list(l)
s = DataStore._make_list(seg_types)
assert len(l) == len(s)
ls = list(zip(l, s))
for i in ls:
if ' ' in i[0]:
tmp = i[0].split(' ')
for t in tmp:
rc.append(DataStore._parse_seg_entry(t, i[1]))
else:
rc.append(DataStore._parse_seg_entry(*i))
return rc
@staticmethod
def _pv_device_lv_entry(table, pv_device, lv_uuid, meta, lv_attr,
segment_info):
if pv_device not in table:
table[pv_device] = {}
if lv_uuid not in table[pv_device]:
table[pv_device][lv_uuid] = {}
table[pv_device][lv_uuid]['segs'] = [segment_info]
table[pv_device][lv_uuid]['name'] = meta
table[pv_device][lv_uuid]['meta'] = lv_attr
else:
table[pv_device][lv_uuid]['segs'].append(segment_info)
@staticmethod
def _pv_device_lv_format(pv_device_lvs):
rc = {}
for pv_device, pd in pv_device_lvs.items():
lvs = []
for lv_uuid, ld in sorted(pd.items()):
lvs.append((lv_uuid, ld['name'], ld['meta'], ld['segs']))
rc[pv_device] = lvs
return rc
@staticmethod
def _lvs_device_pv_entry(table, lv_uuid, pv_device, pv_uuid, segment_info):
if lv_uuid not in table:
table[lv_uuid] = {}
if pv_device not in table[lv_uuid]:
table[lv_uuid][pv_device] = {}
table[lv_uuid][pv_device]['segs'] = [segment_info]
table[lv_uuid][pv_device]['pv_uuid'] = pv_uuid
else:
table[lv_uuid][pv_device]['segs'].append(segment_info)
@staticmethod
def _lvs_device_pv_format(lvs_device_pvs):
rc = {}
for lv_uuid, ld in lvs_device_pvs.items():
pvs = []
for pv_device, pd in sorted(ld.items()):
pvs.append((pd['pv_uuid'], pv_device, pd['segs']))
rc[lv_uuid] = pvs
return rc
def _parse_pv_in_lvs(self):
pv_device_lvs = {} # What LVs are stored on a PV
lvs_device_pv = {} # Where LV data is stored
for i in self.lvs.values():
segs = self._build_segments(i['seg_pe_ranges'], i['segtype'])
for s in segs:
# We are referring to physical device
if '/dev/' in s[0]:
device, r, seg_type = s
DataStore._pv_device_lv_entry(
pv_device_lvs, device, i['lv_uuid'], i['lv_name'],
(i['lv_attr'], i['lv_layout'], i['lv_role']),
(r[0], r[1], seg_type))
# (pv_name, pv_segs, pv_uuid)
DataStore._lvs_device_pv_entry(
lvs_device_pv, i['lv_uuid'], device,
self.pv_path_to_uuid[device], (r[0], r[1], seg_type))
else:
# TODO Handle the case where the segments refer to a LV
# and not a PV
pass
# print("Handle this %s %s %s" % (s[0], s[1], s[2]))
# Convert form to needed result for consumption
pv_device_lvs_result = DataStore._pv_device_lv_format(pv_device_lvs)
lvs_device_pv_result = DataStore._lvs_device_pv_format(lvs_device_pv)
return pv_device_lvs_result, lvs_device_pv_result
def refresh(self, log=True):
"""
Go out and query lvm for the latest data in as few trips as possible
:param log Add debug log entry/exit messages
:return: None
"""
self.num_refreshes += 1
if log:
log_debug("lvmdb - refresh entry")
# Grab everything first then parse it
if self.json:
# Do a single lvm retrieve for everything in json
a = cmdhandler.lvm_full_report_json()
_pvs, _pvs_lookup, _pvs_in_vgs = self._parse_pvs_json(a)
_vgs, _vgs_lookup = self._parse_vgs_json(a)
_lvs, _lvs_in_vgs, _lvs_hidden, _lvs_lookup = self._parse_lvs_json(a)
else:
_raw_pvs = cmdhandler.pv_retrieve_with_segs()
_raw_vgs = cmdhandler.vg_retrieve(None)
_raw_lvs = cmdhandler.lv_retrieve_with_segments()
_pvs, _pvs_lookup, _pvs_in_vgs = self._parse_pvs(_raw_pvs)
_vgs, _vgs_lookup = self._parse_vgs(_raw_vgs)
_lvs, _lvs_in_vgs, _lvs_hidden, _lvs_lookup = self._parse_lvs(_raw_lvs)
# Set all
self.pvs = _pvs
self.pv_path_to_uuid = _pvs_lookup
self.vg_name_to_uuid = _vgs_lookup
self.lv_full_name_to_uuid = _lvs_lookup
self.vgs = _vgs
self.lvs = _lvs
self.lvs_in_vgs = _lvs_in_vgs
self.pvs_in_vgs = _pvs_in_vgs
self.lvs_hidden = _lvs_hidden
# Create lookup table for which LV and segments are on each PV
self.pv_lvs, self.lv_pvs = self._parse_pv_in_lvs()
if log:
log_debug("lvmdb - refresh exit")
def fetch_pvs(self, pv_name):
if not pv_name:
return self.pvs.values()
else:
rc = []
for s in pv_name:
# Ths user could be using a symlink instead of the actual
# block device, make sure we are using actual block device file
# if the pv name isn't in the lookup
if s not in self.pv_path_to_uuid:
s = os.path.realpath(s)
rc.append(self.pvs[self.pv_path_to_uuid[s]])
return rc
def pv_missing(self, pv_uuid):
if pv_uuid in self.pvs:
if self.pvs[pv_uuid]['pv_missing'] == '':
return False
return True
def fetch_vgs(self, vg_name):
if not vg_name:
return self.vgs.values()
else:
rc = []
for s in vg_name:
rc.append(self.vgs[self.vg_name_to_uuid[s]])
return rc
def fetch_lvs(self, lv_names):
try:
if not lv_names:
return self.lvs.values()
else:
rc = []
for s in lv_names:
rc.append(self.lvs[self.lv_full_name_to_uuid[s]])
return rc
except KeyError as ke:
log_error("Key %s not found!" % (str(lv_names)))
log_error("lv name to uuid lookup")
for keys in sorted(self.lv_full_name_to_uuid.keys()):
log_error("%s" % (keys))
log_error("lvs entries by uuid")
for keys in sorted(self.lvs.keys()):
log_error("%s" % (keys))
raise ke
def pv_pe_segments(self, pv_uuid):
pv = self.pvs[pv_uuid]
return list(zip(pv['pvseg_start'], pv['pvseg_size']))
def pv_contained_lv(self, pv_device):
rc = []
if pv_device in self.pv_lvs:
rc = self.pv_lvs[pv_device]
return rc
def lv_contained_pv(self, lv_uuid):
rc = []
if lv_uuid in self.lv_pvs:
rc = self.lv_pvs[lv_uuid]
return rc
def lvs_in_vg(self, vg_uuid):
# Return an array of
# (lv_name, (lv_attr, lv_layout, lv_role), lv_uuid)
rc = []
if vg_uuid in self.lvs_in_vgs:
rc = self.lvs_in_vgs[vg_uuid]
return rc
def pvs_in_vg(self, vg_uuid):
# Returns an array of (pv_name, pv_uuid)
rc = []
if vg_uuid in self.pvs_in_vgs:
rc = self.pvs_in_vgs[vg_uuid]
return rc
def hidden_lvs(self, lv_uuid):
# For a specified LV, return a list of hidden lv_uuid, lv_name
# for it
rc = []
if lv_uuid in self.lvs_hidden:
rc = self.lvs_hidden[lv_uuid]
return rc
if __name__ == "__main__":
pp = prettyprint.PrettyPrinter(indent=4)
use_json = False
if len(sys.argv) != 1:
print(len(sys.argv))
use_json = True
ds = DataStore(use_json)
ds.refresh()
print("PVS")
for v in ds.pvs.values():
pp.pprint(v)
print('PV missing is %s' % ds.pv_missing(v['pv_uuid']))
print("VGS")
for v in ds.vgs.values():
pp.pprint(v)
print("LVS")
for v in ds.lvs.values():
pp.pprint(v)
print("LVS in VG")
for k, v in ds.lvs_in_vgs.items():
print("VG uuid = %s" % (k))
pp.pprint(v)
print("pv_in_lvs")
for k, v in ds.pv_lvs.items():
print("PV %s contains LVS:" % (k))
pp.pprint(v)
for k, v in ds.lv_pvs.items():
print("LV device = %s" % (k))
pp.pprint(v)

16
daemons/lvmdbusd/lvmdbusd Executable file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env python3
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from lvmdbusd import main
if __name__ == '__main__':
sys.exit(main())

180
daemons/lvmdbusd/main.py Normal file
View File

@ -0,0 +1,180 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from . import cfg
from . import objectmanager
from . import utils
from .cfg import BUS_NAME, BASE_INTERFACE, BASE_OBJ_PATH, MANAGER_OBJ_PATH
import threading
from . import cmdhandler
import time
import signal
import dbus
import dbus.mainloop.glib
from . import lvmdb
# noinspection PyUnresolvedReferences
from gi.repository import GLib
from .fetch import StateUpdate
from .manager import Manager
import traceback
import queue
from . import udevwatch
from .utils import log_debug, log_error
import argparse
import os
import sys
from .cmdhandler import LvmFlightRecorder
from .request import RequestEntry
class Lvm(objectmanager.ObjectManager):
def __init__(self, object_path):
super(Lvm, self).__init__(object_path, BASE_INTERFACE)
def process_request():
while cfg.run.value != 0:
# noinspection PyBroadException
try:
req = cfg.worker_q.get(True, 5)
log_debug(
"Running method: %s with args %s" %
(str(req.method), str(req.arguments)))
req.run_cmd()
log_debug("Method complete ")
except queue.Empty:
pass
except Exception:
st = traceback.format_exc()
utils.log_error("process_request exception: \n%s" % st)
def check_bb_size(value):
v = int(value)
if v < 0:
raise argparse.ArgumentTypeError(
"positive integers only ('%s' invalid)" % value)
return v
def main():
start = time.time()
# Add simple command line handling
parser = argparse.ArgumentParser()
parser.add_argument(
"--udev", action='store_true',
help="Use udev for updating state",
default=False,
dest='use_udev')
parser.add_argument(
"--debug", action='store_true',
help="Dump debug messages", default=False,
dest='debug')
parser.add_argument(
"--nojson", action='store_false',
help="Do not use LVM JSON output (disables lvmshell)", default=True,
dest='use_json')
parser.add_argument(
"--lvmshell", action='store_true',
help="Use the lvm shell, not fork & exec lvm",
default=False,
dest='use_lvm_shell')
parser.add_argument(
"--blackboxsize",
help="Size of the black box flight recorder, 0 to disable",
default=10,
type=check_bb_size,
dest='bb_size')
use_session = os.getenv('LVMDBUSD_USE_SESSION', False)
# Ensure that we get consistent output for parsing stdout/stderr
os.environ["LC_ALL"] = "C"
cfg.args = parser.parse_args()
cfg.create_request_entry = RequestEntry
# We create a flight recorder in cmdhandler too, but we replace it here
# as the user may be specifying a different size. The default one in
# cmdhandler is for when we are running other code with a different main.
cfg.blackbox = LvmFlightRecorder(cfg.args.bb_size)
if cfg.args.use_lvm_shell and not cfg.args.use_json:
log_error("You cannot specify --lvmshell and --nojson")
sys.exit(1)
# List of threads that we start up
thread_list = []
# Install signal handlers
for s in [signal.SIGHUP, signal.SIGINT]:
try:
signal.signal(s, utils.handler)
except RuntimeError:
pass
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
dbus.mainloop.glib.threads_init()
cmdhandler.set_execution(cfg.args.use_lvm_shell)
if use_session:
cfg.bus = dbus.SessionBus()
else:
cfg.bus = dbus.SystemBus()
# The base name variable needs to exist for things to work.
# noinspection PyUnusedLocal
base_name = dbus.service.BusName(BUS_NAME, cfg.bus)
cfg.om = Lvm(BASE_OBJ_PATH)
cfg.om.register_object(Manager(MANAGER_OBJ_PATH))
cfg.db = lvmdb.DataStore(cfg.args.use_json)
# Using a thread to process requests, we cannot hang the dbus library
# thread that is handling the dbus interface
thread_list.append(threading.Thread(target=process_request))
# Have a single thread handling updating lvm and the dbus model so we
# don't have multiple threads doing this as the same time
updater = StateUpdate()
thread_list.append(updater.thread)
cfg.load = updater.load
cfg.loop = GLib.MainLoop()
for thread in thread_list:
thread.damon = True
thread.start()
# Add udev watching
if cfg.args.use_udev:
log_debug('Utilizing udev to trigger updates')
# In all cases we are going to monitor for udev until we get an
# ExternalEvent. In the case where we get an external event and the user
# didn't specify --udev we will stop monitoring udev
udevwatch.add()
end = time.time()
log_debug(
'Service ready! total time= %.4f, lvm time= %.4f count= %d' %
(end - start, cmdhandler.total_time, cmdhandler.total_count),
'bg_black', 'fg_light_green')
try:
if cfg.run.value != 0:
cfg.loop.run()
udevwatch.remove()
for thread in thread_list:
thread.join()
except KeyboardInterrupt:
utils.handler(signal.SIGINT, None)
return 0

267
daemons/lvmdbusd/manager.py Normal file
View File

@ -0,0 +1,267 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .automatedproperties import AutomatedProperties
from . import utils
from .cfg import MANAGER_INTERFACE
import dbus
from . import cfg
from . import cmdhandler
from .request import RequestEntry
from . import udevwatch
# noinspection PyPep8Naming
class Manager(AutomatedProperties):
_Version_meta = ("s", MANAGER_INTERFACE)
def __init__(self, object_path):
super(Manager, self).__init__(object_path)
self.set_interface(MANAGER_INTERFACE)
@property
def Version(self):
return dbus.String('1.0.0')
@staticmethod
def handle_execute(rc, out, err):
if rc == 0:
cfg.load()
else:
# Need to work on error handling, need consistent
raise dbus.exceptions.DBusException(
MANAGER_INTERFACE,
'Exit code %s, stderr = %s' % (str(rc), err))
@staticmethod
def _pv_create(device, create_options):
# Check to see if we are already trying to create a PV for an existing
# PV
pv = cfg.om.get_object_path_by_uuid_lvm_id(device, device)
if pv:
raise dbus.exceptions.DBusException(
MANAGER_INTERFACE, "PV %s Already exists!" % device)
rc, out, err = cmdhandler.pv_create(create_options, [device])
Manager.handle_execute(rc, out, err)
return cfg.om.get_object_path_by_lvm_id(device)
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE,
in_signature='sia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def PvCreate(self, device, tmo, create_options, cb, cbe):
utils.validate_device_path(MANAGER_INTERFACE, device)
r = RequestEntry(
tmo, Manager._pv_create,
(device, create_options), cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _create_vg(name, pv_object_paths, create_options):
pv_devices = []
for p in pv_object_paths:
pv = cfg.om.get_object_by_path(p)
if pv:
pv_devices.append(pv.Name)
else:
raise dbus.exceptions.DBusException(
MANAGER_INTERFACE, 'object path = %s not found' % p)
rc, out, err = cmdhandler.vg_create(create_options, pv_devices, name)
Manager.handle_execute(rc, out, err)
return cfg.om.get_object_path_by_lvm_id(name)
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE,
in_signature='saoia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def VgCreate(self, name, pv_object_paths, tmo, create_options, cb, cbe):
utils.validate_vg_name(MANAGER_INTERFACE, name)
r = RequestEntry(
tmo, Manager._create_vg,
(name, pv_object_paths, create_options,),
cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _refresh():
utils.log_debug('Manager.Refresh - entry')
# This is a diagnostic and should not be run in normal operation, so
# lets remove the log entries for refresh as it's implied.
# Run an internal diagnostic on the object manager look up tables
lc = cfg.om.validate_lookups()
rc = cfg.load(log=False)
if rc != 0:
utils.log_debug('Manager.Refresh - exit %d' % (rc),
'bg_black', 'fg_light_red')
else:
utils.log_debug('Manager.Refresh - exit %d' % (rc))
return rc + lc
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE,
out_signature='t',
async_callbacks=('cb', 'cbe'))
def Refresh(self, cb, cbe):
"""
Take all the objects we know about and go out and grab the latest
more of a test method at the moment to make sure we are handling object
paths correctly.
:param cb Callback for result
:param cbe Callback for errors
Returns the number of changes, object add/remove/properties changed
"""
r = RequestEntry(-1, Manager._refresh, (), cb, cbe, False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE)
def FlightRecorderDump(self):
"""
Dump the flight recorder to syslog
"""
cfg.blackbox.dump()
@staticmethod
def _lookup_by_lvm_id(key):
p = cfg.om.get_object_path_by_uuid_lvm_id(key, key)
if not p:
p = '/'
utils.log_debug('LookUpByLvmId: key = %s, result = %s' % (key, p))
return p
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE,
in_signature='s',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def LookUpByLvmId(self, key, cb, cbe):
"""
Given a lvm id in one of the forms:
/dev/sda
some_vg
some_vg/some_lv
Oe1rPX-Pf0W-15E5-n41N-ZmtF-jXS0-Osg8fn
return the object path in O(1) time.
:param key: The lookup value
:return: Return the object path. If object not found you will get '/'
"""
r = RequestEntry(-1, Manager._lookup_by_lvm_id, (key,), cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _use_lvm_shell(yes_no):
return dbus.Boolean(cmdhandler.set_execution(yes_no))
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE,
in_signature='b', out_signature='b',
async_callbacks=('cb', 'cbe'))
def UseLvmShell(self, yes_no, cb, cbe):
"""
Allow the client to enable/disable lvm shell, used for testing
:param yes_no:
:param cb: dbus python call back parameter, not client visible
:param cbe: dbus python error call back parameter, not client visible
:return: Boolean
"""
r = RequestEntry(-1, Manager._use_lvm_shell, (yes_no,), cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _external_event(command):
utils.log_debug("Processing _external_event= %s" % command,
'bg_black', 'fg_orange')
cfg.load()
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE,
in_signature='s', out_signature='i')
def ExternalEvent(self, command):
utils.log_debug("ExternalEvent %s" % command)
# If a user didn't explicitly specify udev, we will turn it off now.
if not cfg.args.use_udev:
if udevwatch.remove():
utils.log_debug("ExternalEvent received, disabling "
"udev monitoring")
# We are dependent on external events now to stay current!
cfg.got_external_event = True
r = RequestEntry(
-1, Manager._external_event, (command,), None, None, False)
cfg.worker_q.put(r)
return dbus.Int32(0)
@staticmethod
def _pv_scan(activate, cache, device_path, major_minor, scan_options):
rc, out, err = cmdhandler.pv_scan(
activate, cache, device_path,
major_minor, scan_options)
Manager.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=MANAGER_INTERFACE,
in_signature='bbasa(ii)ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def PvScan(self, activate, cache, device_paths, major_minors,
tmo, scan_options, cb, cbe):
"""
Scan all supported LVM block devices in the system for physical volumes
NOTE: major_minors & device_paths only usable when cache == True
:param activate: If True, activate any newly found LVs
:param cache: If True, update lvmetad
:param device_paths: Array of device paths or empty
:param major_minors: Array of structures (major,minor)
:param tmo: Timeout for operation
:param scan_options: Additional options to pvscan
:param cb: Not visible in API (used for async. callback)
:param cbe: Not visible in API (used for async. error callback)
:return: '/' if operation done, else job path
"""
for d in device_paths:
utils.validate_device_path(MANAGER_INTERFACE, d)
r = RequestEntry(
tmo, Manager._pv_scan,
(activate, cache, device_paths, major_minors,
scan_options), cb, cbe, False)
cfg.worker_q.put(r)
@property
def lvm_id(self):
"""
Intended to be overridden by classes that inherit
"""
return str(id(self))
@property
def Uuid(self):
"""
Intended to be overridden by classes that inherit
"""
import uuid
return uuid.uuid1()

View File

@ -0,0 +1,385 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import threading
import traceback
import dbus
import os
import copy
from . import cfg
from .utils import log_debug, pv_obj_path_generate, log_error
from .automatedproperties import AutomatedProperties
# noinspection PyPep8Naming
class ObjectManager(AutomatedProperties):
"""
Implements the org.freedesktop.DBus.ObjectManager interface
"""
def __init__(self, object_path, interface):
super(ObjectManager, self).__init__(object_path, interface)
self.set_interface(interface)
self._ap_o_path = object_path
self._objects = {}
self._id_to_object_path = {}
self.rlock = threading.RLock()
@staticmethod
def _get_managed_objects(obj):
with obj.rlock:
rc = {}
try:
for k, v in list(obj._objects.items()):
path, props = v[0].emit_data()
rc[path] = props
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(1)
return rc
@dbus.service.method(
dbus_interface="org.freedesktop.DBus.ObjectManager",
out_signature='a{oa{sa{sv}}}', async_callbacks=('cb', 'cbe'))
def GetManagedObjects(self, cb, cbe):
r = cfg.create_request_entry(-1, ObjectManager._get_managed_objects,
(self, ), cb, cbe, False)
cfg.worker_q.put(r)
def locked(self):
"""
If some external code need to run across a number of different
calls into ObjectManager while blocking others they can use this method
to lock others out.
:return:
"""
return ObjectManagerLock(self.rlock)
@dbus.service.signal(
dbus_interface="org.freedesktop.DBus.ObjectManager",
signature='oa{sa{sv}}')
def InterfacesAdded(self, object_path, int_name_prop_dict):
log_debug(
('SIGNAL: InterfacesAdded(%s, %s)' %
(str(object_path), str(int_name_prop_dict))))
@dbus.service.signal(
dbus_interface="org.freedesktop.DBus.ObjectManager",
signature='oas')
def InterfacesRemoved(self, object_path, interface_list):
log_debug(('SIGNAL: InterfacesRemoved(%s, %s)' %
(str(object_path), str(interface_list))))
def validate_lookups(self):
with self.rlock:
tmp_lookups = copy.deepcopy(self._id_to_object_path)
# iterate over all we know, removing from the copy. If all is well
# we will have zero items left over
for path, md in self._objects.items():
obj, lvm_id, uuid = md
if lvm_id:
assert path == tmp_lookups[lvm_id]
del tmp_lookups[lvm_id]
if uuid:
assert path == tmp_lookups[uuid]
del tmp_lookups[uuid]
rc = len(tmp_lookups)
if rc:
# Error condition
log_error("_id_to_object_path has extraneous lookups!")
for key, path in tmp_lookups.items():
log_error("Key= %s, path= %s" % (key, path))
return rc
def _lookup_add(self, obj, path, lvm_id, uuid):
"""
Store information about what we added to the caches so that we
can remove it cleanly
:param obj: The dbus object we are storing
:param lvm_id: The lvm id for the asset
:param uuid: The uuid for the asset
:return:
"""
# Note: Only called internally, lock implied
# We could have a temp entry from the forward creation of a path
self._lookup_remove(path)
self._objects[path] = (obj, lvm_id, uuid)
# Make sure we have one or the other
assert lvm_id or uuid
if lvm_id:
self._id_to_object_path[lvm_id] = path
if uuid:
self._id_to_object_path[uuid] = path
def _lookup_remove(self, obj_path):
# Note: Only called internally, lock implied
if obj_path in self._objects:
(obj, lvm_id, uuid) = self._objects[obj_path]
if lvm_id in self._id_to_object_path:
del self._id_to_object_path[lvm_id]
if uuid in self._id_to_object_path:
del self._id_to_object_path[uuid]
del self._objects[obj_path]
def lookup_update(self, dbus_obj, new_uuid, new_lvm_id):
with self.rlock:
obj_path = dbus_obj.dbus_object_path()
self._lookup_remove(obj_path)
self._lookup_add(
dbus_obj, obj_path,
new_lvm_id, new_uuid)
def object_paths_by_type(self, o_type):
with self.rlock:
rc = {}
for k, v in list(self._objects.items()):
if isinstance(v[0], o_type):
rc[k] = True
return rc
def register_object(self, dbus_object, emit_signal=False):
"""
Given a dbus object add it to the collection
:param dbus_object: Dbus object to register
:param emit_signal: If true emit a signal for interfaces added
"""
with self.rlock:
path, props = dbus_object.emit_data()
# print('Registering object path %s for %s' %
# (path, dbus_object.lvm_id))
# We want fast access to the object by a number of different ways
# so we use multiple hashs with different keys
self._lookup_add(dbus_object, path, dbus_object.lvm_id,
dbus_object.Uuid)
if emit_signal:
self.InterfacesAdded(path, props)
def remove_object(self, dbus_object, emit_signal=False):
"""
Given a dbus object, remove it from the collection and remove it
from the dbus framework as well
:param dbus_object: Dbus object to remove
:param emit_signal: If true emit the interfaces removed signal
"""
with self.rlock:
# Store off the object path and the interface first
path = dbus_object.dbus_object_path()
interfaces = dbus_object.interface()
# print 'UN-Registering object path %s for %s' % \
# (path, dbus_object.lvm_id)
self._lookup_remove(path)
# Remove from dbus library
dbus_object.remove_from_connection(cfg.bus, path)
# Optionally emit a signal
if emit_signal:
self.InterfacesRemoved(path, interfaces)
def get_object_by_path(self, path):
"""
Given a dbus path return the object registered for it
:param path: The dbus path
:return: The object
"""
with self.rlock:
if path in self._objects:
return self._objects[path][0]
return None
def get_object_by_uuid_lvm_id(self, uuid, lvm_id):
with self.rlock:
return self.get_object_by_path(
self.get_object_path_by_uuid_lvm_id(uuid, lvm_id))
def get_object_by_lvm_id(self, lvm_id):
"""
Given an lvm identifier, return the object registered for it
:param lvm_id: The lvm identifier
"""
with self.rlock:
lookup_rc = self._id_lookup(lvm_id)
if lookup_rc:
return self.get_object_by_path(lookup_rc)
return None
def get_object_path_by_lvm_id(self, lvm_id):
"""
Given an lvm identifier, return the object path for it
:param lvm_id: The lvm identifier
:return: Object path or '/' if not found
"""
with self.rlock:
lookup_rc = self._id_lookup(lvm_id)
if lookup_rc:
return lookup_rc
return '/'
def _uuid_verify(self, path, uuid, lvm_id):
"""
Ensure uuid is present for a successful lvm_id lookup
NOTE: Internal call, assumes under object manager lock
:param path: Path to object we looked up
:param uuid: lvm uuid to verify
:param lvm_id: lvm_id used to find object
:return: None
"""
# This gets called when we found an object based on lvm_id, ensure
# uuid is correct too, as they can change. There is no durable
# non-changeable name in lvm
if lvm_id != uuid:
if uuid and uuid not in self._id_to_object_path:
obj = self.get_object_by_path(path)
self._lookup_add(obj, path, lvm_id, uuid)
def _lvm_id_verify(self, path, uuid, lvm_id):
"""
Ensure lvm_id is present for a successful uuid lookup
NOTE: Internal call, assumes under object manager lock
:param path: Path to object we looked up
:param uuid: uuid used to find object
:param lvm_id: lvm_id to verify
:return: None
"""
# This gets called when we found an object based on uuid, ensure
# lvm_id is correct too, as they can change. There is no durable
# non-changeable name in lvm
if lvm_id != uuid:
if lvm_id and lvm_id not in self._id_to_object_path:
obj = self.get_object_by_path(path)
self._lookup_add(obj, path, lvm_id, uuid)
def _id_lookup(self, the_id):
path = None
if the_id:
# The _id_to_object_path contains hash keys for everything, so
# uuid and lvm_id
if the_id in self._id_to_object_path:
path = self._id_to_object_path[the_id]
else:
if "/" in the_id:
if the_id.startswith('/'):
# We could have a pv device path lookup that failed,
# lets try canonical form and try again.
canonical = os.path.realpath(the_id)
if canonical in self._id_to_object_path:
path = self._id_to_object_path[canonical]
else:
vg, lv = the_id.split("/", 1)
int_lvm_id = vg + "/" + ("[%s]" % lv)
if int_lvm_id in self._id_to_object_path:
path = self._id_to_object_path[int_lvm_id]
return path
def get_object_path_by_uuid_lvm_id(self, uuid, lvm_id, path_create=None):
"""
For a given lvm asset return the dbus object path registered for it.
This method first looks up by uuid and then by lvm_id. You
can search by just one by setting uuid == lvm_id (uuid or lvm_id).
If the object is not found and path_create is a not None, the
path_create function will be called to create a new object path and
register it with the object manager for the specified uuid & lvm_id.
Note: If path create is not None, uuid and lvm_id cannot be equal
:param uuid: The uuid for the lvm object we are searching for
:param lvm_id: The lvm name (eg. pv device path, vg name, lv full name)
:param path_create: If not None, create the path using this function if
we fail to find the object by uuid or lvm_id.
:returns None if lvm asset not found and path_create == None otherwise
a valid dbus object path
"""
with self.rlock:
assert lvm_id
assert uuid
if path_create:
assert uuid != lvm_id
# Check for Manager.LookUpByLvmId query, we cannot
# check/verify/update the uuid and lvm_id lookups so don't!
if uuid == lvm_id:
path = self._id_lookup(lvm_id)
else:
# We have a uuid and a lvm_id we can do sanity checks to ensure
# that they are consistent
# If a PV is missing it's device path is '[unknown]' or some
# other text derivation of unknown. When we find that a PV is
# missing we will clear out the lvm_id as it's likely not unique
# and thus not useful and potentially harmful for lookups.
if path_create == pv_obj_path_generate and \
cfg.db.pv_missing(uuid):
lvm_id = None
# Lets check for the uuid first
path = self._id_lookup(uuid)
if path:
# Verify the lvm_id is sane
self._lvm_id_verify(path, uuid, lvm_id)
else:
# Unable to find by UUID, lets lookup by lvm_id
path = self._id_lookup(lvm_id)
if path:
# Verify the uuid is sane
self._uuid_verify(path, uuid, lvm_id)
else:
# We have exhausted all lookups, let's create if we can
if path_create:
path = path_create()
self._lookup_add(None, path, lvm_id, uuid)
# print('get_object_path_by_lvm_id(%s, %s, %s, %s: return %s' %
# (uuid, lvm_id, str(path_create), str(gen_new), path))
return path
class ObjectManagerLock(object):
"""
The sole purpose of this class is to allow other code the ability to
lock the object manager using a `with` statement, eg.
with cfg.om.locked():
# Do stuff with object manager
This will ensure that the lock is always released (assuming this is done
correctly)
"""
def __init__(self, recursive_lock):
self._lock = recursive_lock
def __enter__(self):
# Acquire lock
self._lock.acquire()
# noinspection PyUnusedLocal
def __exit__(self, e_type, e_value, e_traceback):
# Release lock
self._lock.release()
self._lock = None

View File

@ -0,0 +1,10 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
LVM_BINARY = "@LVM_PATH@"

258
daemons/lvmdbusd/pv.py Normal file
View File

@ -0,0 +1,258 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .automatedproperties import AutomatedProperties
from . import utils
from . import cfg
import dbus
from .cfg import PV_INTERFACE
from . import cmdhandler
from .utils import vg_obj_path_generate, n, pv_obj_path_generate, \
lv_object_path_method
from .loader import common
from .request import RequestEntry
from .state import State
from .utils import round_size
# noinspection PyUnusedLocal
def pvs_state_retrieve(selection, cache_refresh=True):
rc = []
if cache_refresh:
cfg.db.refresh()
for p in cfg.db.fetch_pvs(selection):
rc.append(
PvState(
p["pv_name"], p["pv_uuid"], p["pv_name"],
p["pv_fmt"], n(p["pv_size"]), n(p["pv_free"]),
n(p["pv_used"]), n(p["dev_size"]), n(p["pv_mda_size"]),
n(p["pv_mda_free"]), int(p["pv_ba_start"]),
n(p["pv_ba_size"]), n(p["pe_start"]),
int(p["pv_pe_count"]), int(p["pv_pe_alloc_count"]),
p["pv_attr"], p["pv_tags"], p["vg_name"], p["vg_uuid"]))
return rc
def load_pvs(device=None, object_path=None, refresh=False, emit_signal=False,
cache_refresh=True):
return common(
pvs_state_retrieve, (Pv,), device, object_path, refresh,
emit_signal, cache_refresh)
# noinspection PyUnresolvedReferences
class PvState(State):
@property
def lvm_id(self):
return self.lvm_path
def _lv_object_list(self, vg_name):
rc = []
if vg_name:
for lv in sorted(cfg.db.pv_contained_lv(self.lvm_id)):
lv_uuid, lv_name, meta, segs = lv
full_name = "%s/%s" % (vg_name, lv_name)
path_create = lv_object_path_method(lv_name, meta)
lv_path = cfg.om.get_object_path_by_uuid_lvm_id(
lv_uuid, full_name, path_create)
rc.append((lv_path, segs))
return rc
# noinspection PyUnusedLocal,PyPep8Naming
def __init__(self, lvm_path, Uuid, Name,
Fmt, SizeBytes, FreeBytes, UsedBytes, DevSizeBytes,
MdaSizeBytes, MdaFreeBytes, BaStart, BaSizeBytes,
PeStart, PeCount, PeAllocCount, attr, Tags, vg_name,
vg_uuid):
utils.init_class_from_arguments(self)
self.pe_segments = cfg.db.pv_pe_segments(Uuid)
self.lv = self._lv_object_list(vg_name)
if vg_name:
self.vg_path = cfg.om.get_object_path_by_uuid_lvm_id(
vg_uuid, vg_name, vg_obj_path_generate)
else:
self.vg_path = '/'
def identifiers(self):
return (self.Uuid, self.lvm_path)
def create_dbus_object(self, path):
if not path:
path = cfg.om.get_object_path_by_uuid_lvm_id(self.Uuid, self.Name,
pv_obj_path_generate)
return Pv(path, self)
# noinspection PyMethodMayBeStatic
def creation_signature(self):
return (Pv, pv_obj_path_generate)
# noinspection PyPep8Naming
@utils.dbus_property(PV_INTERFACE, 'Uuid', 's') # PV UUID/pv_uuid
@utils.dbus_property(PV_INTERFACE, 'Name', 's') # PV/pv_name
@utils.dbus_property(PV_INTERFACE, 'Fmt', 's') # Fmt/pv_fmt
@utils.dbus_property(PV_INTERFACE, 'SizeBytes', 't') # PSize/pv_size
@utils.dbus_property(PV_INTERFACE, 'FreeBytes', 't') # PFree/pv_free
@utils.dbus_property(PV_INTERFACE, 'UsedBytes', 't') # Used/pv_used
@utils.dbus_property(PV_INTERFACE, 'DevSizeBytes', 't') # DevSize/dev_size
@utils.dbus_property(PV_INTERFACE, 'MdaSizeBytes', 't') # PMdaSize/pv_mda_size
@utils.dbus_property(PV_INTERFACE, 'MdaFreeBytes', 't') # PMdaFree/pv_mda_free
@utils.dbus_property(PV_INTERFACE, 'BaStart', 't') # BA start/pv_ba_start
@utils.dbus_property(PV_INTERFACE, 'BaSizeBytes', 't') # BA size/pv_ba_size
@utils.dbus_property(PV_INTERFACE, 'PeStart', 't') # 1st PE/pe_start
@utils.dbus_property(PV_INTERFACE, 'PeCount', 't') # PE/pv_pe_count
@utils.dbus_property(PV_INTERFACE, 'PeAllocCount', 't') # PE Allocation count
class Pv(AutomatedProperties):
# For properties that we need custom handlers we need these, otherwise
# we won't get our introspection data
_Tags_meta = ("as", PV_INTERFACE)
_PeSegments_meta = ("a(tt)", PV_INTERFACE)
_Exportable_meta = ("b", PV_INTERFACE)
_Allocatable_meta = ("b", PV_INTERFACE)
_Missing_meta = ("b", PV_INTERFACE)
_Lv_meta = ("a(oa(tts))", PV_INTERFACE)
_Vg_meta = ("o", PV_INTERFACE)
# noinspection PyUnusedLocal,PyPep8Naming
def __init__(self, object_path, state_obj):
super(Pv, self).__init__(object_path, pvs_state_retrieve)
self.set_interface(PV_INTERFACE)
self.state = state_obj
@staticmethod
def _remove(pv_uuid, pv_name, remove_options):
# Remove the PV, if successful then remove from the model
# Make sure we have a dbus object representing it
Pv.validate_dbus_object(pv_uuid, pv_name)
rc, out, err = cmdhandler.pv_remove(pv_name, remove_options)
Pv.handle_execute(rc, out, err)
return '/'
@staticmethod
def handle_execute(rc, out, err):
if rc == 0:
cfg.load()
else:
# Need to work on error handling, need consistent
raise dbus.exceptions.DBusException(
PV_INTERFACE,
'Exit code %s, stderr = %s' % (str(rc), err))
@staticmethod
def validate_dbus_object(pv_uuid, pv_name):
dbo = cfg.om.get_object_by_uuid_lvm_id(pv_uuid, pv_name)
if not dbo:
raise dbus.exceptions.DBusException(
PV_INTERFACE,
'PV with uuid %s and name %s not present!' %
(pv_uuid, pv_name))
return dbo
@dbus.service.method(
dbus_interface=PV_INTERFACE,
in_signature='ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Remove(self, tmo, remove_options, cb, cbe):
r = RequestEntry(
tmo, Pv._remove,
(self.Uuid, self.lvm_id, remove_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@staticmethod
def _resize(pv_uuid, pv_name, new_size_bytes, resize_options):
# Make sure we have a dbus object representing it
Pv.validate_dbus_object(pv_uuid, pv_name)
rc, out, err = cmdhandler.pv_resize(pv_name, new_size_bytes,
resize_options)
Pv.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=PV_INTERFACE,
in_signature='tia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def ReSize(self, new_size_bytes, tmo, resize_options, cb, cbe):
r = RequestEntry(
tmo, Pv._resize,
(self.Uuid, self.lvm_id, round_size(new_size_bytes),
resize_options), cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _allocation_enabled(pv_uuid, pv_name, yes_no, allocation_options):
# Make sure we have a dbus object representing it
Pv.validate_dbus_object(pv_uuid, pv_name)
rc, out, err = cmdhandler.pv_allocatable(
pv_name, yes_no, allocation_options)
Pv.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=PV_INTERFACE,
in_signature='bia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def AllocationEnabled(self, yes, tmo, allocation_options, cb, cbe):
r = RequestEntry(
tmo, Pv._allocation_enabled,
(self.Uuid, self.lvm_id,
yes, allocation_options),
cb, cbe, False)
cfg.worker_q.put(r)
@property
def Tags(self):
return utils.parse_tags(self.state.Tags)
@property
def PeSegments(self):
if len(self.state.pe_segments):
return dbus.Array(self.state.pe_segments, signature='(tt)')
return dbus.Array([], '(tt)')
@property
def Exportable(self):
return dbus.Boolean(self.state.attr[1] == 'x')
@property
def Allocatable(self):
return dbus.Boolean(self.state.attr[0] == 'a')
@property
def Missing(self):
return dbus.Boolean(self.state.attr[2] == 'm')
def object_path(self):
return self._object_path
@property
def lvm_id(self):
return self.state.lvm_id
@property
def identifiers(self):
return self.state.identifiers()
@property
def Lv(self):
return dbus.Array(self.state.lv, signature="(oa(tts))")
@property
def Vg(self):
return dbus.ObjectPath(self.state.vg_path)

156
daemons/lvmdbusd/request.py Normal file
View File

@ -0,0 +1,156 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import threading
# noinspection PyUnresolvedReferences
from gi.repository import GLib
from .job import Job
from . import cfg
import traceback
from .utils import log_error, mt_async_result
class RequestEntry(object):
def __init__(self, tmo, method, arguments, cb, cb_error,
return_tuple=True, job_state=None):
self.method = method
self.arguments = arguments
self.cb = cb
self.cb_error = cb_error
self.timer_id = -1
self.lock = threading.RLock()
self.done = False
self._result = None
self._job = None
self._rc = 0
self._rc_error = None
self._return_tuple = return_tuple
self._job_state = job_state
if tmo < 0:
# Client is willing to block forever
pass
elif tmo == 0:
self._return_job()
else:
# Note: using 990 instead of 1000 for second to ms conversion to
# account for overhead. Goal is to return just before the
# timeout amount has expired. Better to be a little early than
# late.
self.timer_id = GLib.timeout_add(
tmo * 990, RequestEntry._request_timeout, self)
@staticmethod
def _request_timeout(r):
"""
Method which gets called when the timer runs out!
:param r: RequestEntry which timed out
:return: Result of timer_expired
"""
return r.timer_expired()
def _return_job(self):
# Return job is only called when we create a request object or when
# we pop a timer. In both cases we are running in the correct context
# and do not need to schedule the call back in main context.
self._job = Job(self, self._job_state)
cfg.om.register_object(self._job, True)
if self._return_tuple:
self.cb(('/', self._job.dbus_object_path()))
else:
self.cb(self._job.dbus_object_path())
def run_cmd(self):
try:
result = self.method(*self.arguments)
self.register_result(result)
except Exception as e:
# Use the request entry to return the result as the client may
# have gotten a job by the time we hit an error
# Lets get the stacktrace and set that to the error message
st = traceback.format_exc()
cfg.blackbox.dump()
log_error("Exception returned to client: \n%s" % st)
self.register_error(-1, str(e), e)
def is_done(self):
with self.lock:
rc = self.done
return rc
def get_errors(self):
with self.lock:
return (self._rc, self._rc_error)
def result(self):
with self.lock:
if self.done:
return self._result
return '/'
def _reg_ending(self, result, error_rc=0, error_msg=None,
error_exception=None):
with self.lock:
self.done = True
if self.timer_id != -1:
# Try to prevent the timer from firing
GLib.source_remove(self.timer_id)
self._result = result
self._rc = error_rc
self._rc_error = error_msg
if not self._job:
# We finished and there is no job, so return result or error
# now!
# Note: If we don't have a valid cb or cbe, this indicates a
# request that doesn't need a response as we already returned
# one before the request was processed.
if error_rc == 0:
if self.cb:
if self._return_tuple:
mt_async_result(self.cb, (result, '/'))
else:
mt_async_result(self.cb, result)
else:
if self.cb_error:
if not error_exception:
if not error_msg:
error_exception = Exception(
"An error occurred, but no reason was "
"given, see service logs!")
else:
error_exception = Exception(error_msg)
mt_async_result(self.cb_error, error_exception)
else:
# We have a job and it's complete, indicate that it's done.
self._job.Complete = True
self._job = None
def register_error(self, error_rc, error_message, error_exception):
self._reg_ending('/', error_rc, error_message, error_exception)
def register_result(self, result):
self._reg_ending(result)
def timer_expired(self):
with self.lock:
# Set the timer back to -1 as we will get a warning if we try
# to remove a timer that doesn't exist
self.timer_id = -1
if not self.done:
# Create dbus job object and return path to caller
self._return_job()
else:
# The job is done, we have nothing to do
pass
return False

27
daemons/lvmdbusd/state.py Normal file
View File

@ -0,0 +1,27 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from abc import ABCMeta, abstractmethod
class State(object, metaclass=ABCMeta):
@abstractmethod
def lvm_id(self):
pass
@abstractmethod
def identifiers(self):
pass
@abstractmethod
def create_dbus_object(self, path):
pass
def __str__(self):
return '*****\n' + str(self.__dict__) + '\n******\n'

View File

@ -0,0 +1,91 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import pyudev
import threading
from . import cfg
from .request import RequestEntry
from . import utils
observer = None
observer_lock = threading.RLock()
_udev_lock = threading.RLock()
_udev_count = 0
def udev_add():
global _udev_count
with _udev_lock:
if _udev_count == 0:
_udev_count += 1
# Place this on the queue so any other operations will sequence
# behind it
r = RequestEntry(
-1, _udev_event, (), None, None, False)
cfg.worker_q.put(r)
def udev_complete():
global _udev_count
with _udev_lock:
if _udev_count > 0:
_udev_count -= 1
def _udev_event():
utils.log_debug("Processing udev event")
udev_complete()
cfg.load()
# noinspection PyUnusedLocal
def filter_event(action, device):
# Filter for events of interest and add a request object to be processed
# when appropriate.
refresh = False
if '.ID_FS_TYPE_NEW' in device:
fs_type_new = device['.ID_FS_TYPE_NEW']
if 'LVM' in fs_type_new:
refresh = True
elif fs_type_new == '':
# Check to see if the device was one we knew about
if 'DEVNAME' in device:
found = cfg.om.get_object_by_lvm_id(device['DEVNAME'])
if found:
refresh = True
if 'DM_LV_NAME' in device:
refresh = True
if refresh:
udev_add()
def add():
with observer_lock:
global observer
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by('block')
observer = pyudev.MonitorObserver(monitor, filter_event)
observer.start()
def remove():
with observer_lock:
global observer
if observer:
observer.stop()
observer = None
return True
return False

596
daemons/lvmdbusd/utils.py Normal file
View File

@ -0,0 +1,596 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import xml.etree.ElementTree as Et
import sys
import inspect
import ctypes
import os
import string
import datetime
import dbus
from lvmdbusd import cfg
# noinspection PyUnresolvedReferences
from gi.repository import GLib
import threading
STDOUT_TTY = os.isatty(sys.stdout.fileno())
def rtype(dbus_type):
"""
Decorator making sure that the decorated function returns a value of
specified type.
:param dbus_type: The specific dbus type to return value as
"""
def decorator(fn):
def decorated(*args, **kwargs):
return dbus_type(fn(*args, **kwargs))
return decorated
return decorator
# Field is expected to be a number, handle the corner cases when parsing
@rtype(dbus.UInt64)
def n(v):
if not v:
return 0
return int(float(v))
@rtype(dbus.UInt32)
def n32(v):
if not v:
return 0
return int(float(v))
# noinspection PyProtectedMember
def init_class_from_arguments(obj_instance):
for k, v in list(sys._getframe(1).f_locals.items()):
if k != 'self':
nt = k
# If the current attribute has a value, but the incoming does
# not, don't overwrite it. Otherwise the default values on the
# property decorator don't work as expected.
cur = getattr(obj_instance, nt, v)
# print 'Init class %s = %s' % (nt, str(v))
if not (cur and len(str(cur)) and (v is None or len(str(v))) == 0):
setattr(obj_instance, nt, v)
def get_properties(f):
"""
Walks through an object instance or it's parent class(es) and determines
which attributes are properties and if they were created to be used for
dbus.
:param f: Object to inspect
:return: A dictionary of tuples with each tuple being:
0 = An array of dicts with the keys being: p_t, p_name,
p_access(type, name, access)
1 = Hash of property names and current value
"""
interfaces = dict()
for c in inspect.getmro(f.__class__):
h = vars(c)
for p, value in h.items():
if isinstance(value, property):
# We found a property, see if it has a metadata type
key = attribute_type_name(p)
if key in h:
interface = h[key][1]
if interface not in interfaces:
interfaces[interface] = ([], {})
access = ''
if getattr(f.__class__, p).fget:
access += 'read'
if getattr(f.__class__, p).fset:
access += 'write'
interfaces[interface][0].append(
dict(
p_t=getattr(f, key)[0],
p_name=p,
p_access=access))
interfaces[interface][1][p] = getattr(f, p)
return interfaces
def get_object_property_diff(o_prop, n_prop):
"""
Walk through each object properties and report what has changed and with
the new values
:param o_prop: Old keys/values
:param n_prop: New keys/values
:return: hash of properties that have changed and their new value
"""
rc = {}
for intf_k, intf_v in o_prop.items():
for k, v in list(intf_v[1].items()):
# print('Comparing %s:%s to %s:%s' %
# (k, o_prop[intf_k][1][k], k, str(n_prop[intf_k][1][k])))
if o_prop[intf_k][1][k] != n_prop[intf_k][1][k]:
new_value = n_prop[intf_k][1][k]
if intf_k not in rc:
rc[intf_k] = dict()
rc[intf_k][k] = new_value
return rc
def add_properties(xml, interface, props):
"""
Given xml that describes the interface, add property values to the XML
for the specified interface.
:param xml: XML to edit
:param interface: Interface to add the properties too
:param props: Output from get_properties
:return: updated XML string
"""
if props:
root = Et.fromstring(xml)
interface_element = None
# Check to see if interface is present
for c in root:
if c.attrib['name'] == interface:
interface_element = c
break
# Interface is not present, lets create it so we have something to
# attach the properties too
if interface_element is None:
interface_element = Et.Element("interface", name=interface)
root.append(interface_element)
# Add the properties
for p in props:
temp = '<property type="%s" name="%s" access="%s"/>\n' % \
(p['p_t'], p['p_name'], p['p_access'])
interface_element.append(Et.fromstring(temp))
return Et.tostring(root, encoding='utf8')
return xml
def attribute_type_name(name):
"""
Given the property name, return string of the attribute type
:param name:
:return:
"""
return "_%s_meta" % name
_type_map = dict(
s=dbus.String,
o=dbus.ObjectPath,
t=dbus.UInt64,
x=dbus.Int64,
u=dbus.UInt32,
i=dbus.Int32,
n=dbus.Int16,
q=dbus.UInt16,
d=dbus.Double,
y=dbus.Byte,
b=dbus.Boolean)
def _pass_through(v):
"""
If we have something which is not a simple type we return the original
value un-wrapped.
:param v:
:return:
"""
return v
def _dbus_type(t, value):
return _type_map.get(t, _pass_through)(value)
def dbus_property(interface_name, name, dbus_type, doc=None):
"""
Creates the get/set properties for the given name. It assumes that the
actual attribute is '_' + name and the attribute metadata is stuffed in
_name_type.
There is probably a better way todo this.
:param interface_name: Dbus interface this property is associated with
:param name: Name of property
:param dbus_type: dbus string type eg. s,t,i,x
:param doc: Python __doc__ for the property
:return:
"""
attribute_name = '_' + name
def getter(self):
t = getattr(self, attribute_name + '_meta')[0]
return _dbus_type(t, getattr(self.state, attribute_name[1:]))
prop = property(getter, None, None, doc)
def decorator(cls):
setattr(cls, attribute_name + '_meta', (dbus_type, interface_name))
setattr(cls, name, prop)
return cls
return decorator
def parse_tags(tags):
if len(tags):
if ',' in tags:
return tags.split(',')
return dbus.Array(sorted([tags]), signature='s')
return dbus.Array([], signature='s')
def _common_log(msg, *attributes):
cfg.stdout_lock.acquire()
tid = ctypes.CDLL('libc.so.6').syscall(186)
if STDOUT_TTY:
msg = "%s: %d:%d - %s" % \
(datetime.datetime.now().strftime("%b %d %H:%M:%S.%f"),
os.getpid(), tid, msg)
else:
msg = "%d:%d - %s" % (os.getpid(), tid, msg)
if STDOUT_TTY and attributes:
print(color(msg, *attributes))
else:
print(msg)
cfg.stdout_lock.release()
sys.stdout.flush()
# Serializes access to stdout to prevent interleaved output
# @param msg Message to output to stdout
# @return None
def log_debug(msg, *attributes):
if cfg.args and cfg.args.debug:
_common_log(msg, *attributes)
def log_error(msg, *attributes):
_common_log(msg, *attributes)
# noinspection PyUnusedLocal
def handler(signum, frame):
cfg.run.value = 0
log_debug('Signal handler called with signal %d' % signum)
if cfg.loop is not None:
cfg.loop.quit()
def pv_obj_path_generate():
return cfg.PV_OBJ_PATH + "/%d" % next(cfg.pv_id)
def vg_obj_path_generate():
return cfg.VG_OBJ_PATH + "/%d" % next(cfg.vg_id)
def lv_object_path_method(name, meta):
if name[0] == '[':
return _hidden_lv_obj_path_generate
elif meta[0][0] == 't':
return _thin_pool_obj_path_generate
elif meta[0][0] == 'C' and 'pool' in meta[1]:
return _cache_pool_obj_path_generate
return _lv_obj_path_generate
# Note: None of the individual LV path generate functions should be called
# directly, they should only be dispatched through lv_object_path_method
def _lv_obj_path_generate():
return cfg.LV_OBJ_PATH + "/%d" % next(cfg.lv_id)
def _thin_pool_obj_path_generate():
return cfg.THIN_POOL_PATH + "/%d" % next(cfg.thin_id)
def _cache_pool_obj_path_generate():
return cfg.CACHE_POOL_PATH + "/%d" % next(cfg.cache_pool_id)
def _hidden_lv_obj_path_generate():
return cfg.HIDDEN_LV_PATH + "/%d" % next(cfg.hidden_lv)
def job_obj_path_generate():
return cfg.JOB_OBJ_PATH + "/%d" % next(cfg.job_id)
def color(text, *user_styles):
styles = {
# styles
'reset': '\033[0m',
'bold': '\033[01m',
'disabled': '\033[02m',
'underline': '\033[04m',
'reverse': '\033[07m',
'strike_through': '\033[09m',
'invisible': '\033[08m',
# text colors
'fg_black': '\033[30m',
'fg_red': '\033[31m',
'fg_green': '\033[32m',
'fg_orange': '\033[33m',
'fg_blue': '\033[34m',
'fg_purple': '\033[35m',
'fg_cyan': '\033[36m',
'fg_light_grey': '\033[37m',
'fg_dark_grey': '\033[90m',
'fg_light_red': '\033[91m',
'fg_light_green': '\033[92m',
'fg_yellow': '\033[93m',
'fg_light_blue': '\033[94m',
'fg_pink': '\033[95m',
'fg_light_cyan': '\033[96m',
# background colors
'bg_black': '\033[40m',
'bg_red': '\033[41m',
'bg_green': '\033[42m',
'bg_orange': '\033[43m',
'bg_blue': '\033[44m',
'bg_purple': '\033[45m',
'bg_cyan': '\033[46m',
'bg_light_grey': '\033[47m'
}
color_text = ''
for style in user_styles:
try:
color_text += styles[style]
except KeyError:
return 'def color: parameter {} does not exist'.format(style)
color_text += text
return '\033[0m{0}\033[0m'.format(color_text)
def pv_range_append(cmd, device, start, end):
if (start, end) == (0, 0):
cmd.append(device)
else:
if start != 0 and end == 0:
cmd.append("%s:%d-" % (device, start))
else:
cmd.append(
"%s:%d-%d" %
(device, start, end))
def pv_dest_ranges(cmd, pv_dest_range_list):
if len(pv_dest_range_list):
for i in pv_dest_range_list:
pv_range_append(cmd, *i)
def round_size(size_bytes):
bs = 512
remainder = size_bytes % bs
if not remainder:
return size_bytes
return size_bytes + bs - remainder
_ALLOWABLE_CH = string.ascii_letters + string.digits + '#+-.:=@_\/%'
_ALLOWABLE_CH_SET = set(_ALLOWABLE_CH)
_ALLOWABLE_VG_LV_CH = string.ascii_letters + string.digits + '.-_+'
_ALLOWABLE_VG_LV_CH_SET = set(_ALLOWABLE_VG_LV_CH)
_LV_NAME_RESERVED = ("_cdata", "_cmeta", "_corig", "_mimage", "_mlog",
"_pmspare", "_rimage", "_rmeta", "_tdata", "_tmeta", "_vorigin")
# Tags can have the characters, based on the code
# a-zA-Z0-9._-+/=!:&#
_ALLOWABLE_TAG_CH = string.ascii_letters + string.digits + "._-+/=!:&#"
_ALLOWABLE_TAG_CH_SET = set(_ALLOWABLE_TAG_CH)
def _allowable_tag(tag_name):
# LVM should impose a length restriction
return set(tag_name) <= _ALLOWABLE_TAG_CH_SET
def _allowable_vg_name(vg_name):
if vg_name is None:
raise ValueError("VG name is None or empty")
vg_len = len(vg_name)
if vg_len == 0 or vg_len > 127:
raise ValueError("VG name (%s) length (%d) not in the domain 1..127" %
(vg_name, vg_len))
if not set(vg_name) <= _ALLOWABLE_VG_LV_CH_SET:
raise ValueError("VG name (%s) contains invalid character, "
"allowable set(%s)" % (vg_name, _ALLOWABLE_VG_LV_CH))
if vg_name == "." or vg_name == "..":
raise ValueError('VG name (%s) cannot be "." or ".."' % (vg_name))
def _allowable_lv_name(vg_name, lv_name):
if lv_name is None:
raise ValueError("LV name is None or empty")
lv_len = len(lv_name)
# This length is derived from empirical testing
if lv_len == 0 or (len(vg_name) + lv_len) > 125:
raise ValueError("LV name (%s) length (%d) + VG name length "
"not in the domain 1..125" % (lv_name, lv_len))
if not set(lv_name) <= _ALLOWABLE_VG_LV_CH_SET:
raise ValueError("LV name (%s) contains invalid character, "
"allowable (%s)" % (lv_name, _ALLOWABLE_VG_LV_CH))
if any(x in lv_name for x in _LV_NAME_RESERVED):
raise ValueError("LV name (%s) contains a reserved word, "
"reserved set(%s)" % (lv_name, str(_LV_NAME_RESERVED)))
if lv_name.startswith("snapshot") or lv_name.startswith("pvmove"):
raise ValueError("LV name (%s) starts with a reserved word, "
"reserved set(%s)" % (lv_name, str(["snapshot", "pvmove"])))
if lv_name[0] == '-':
raise ValueError("LV name (%s) cannot start with a '-' "
"character" % lv_name)
def validate_device_path(interface, device):
if not set(device) <= _ALLOWABLE_CH_SET:
raise dbus.exceptions.DBusException(
interface, 'Device path (%s) has invalid characters, '
'allowable (%s)' % (device, _ALLOWABLE_CH))
def validate_vg_name(interface, vg_name):
try:
_allowable_vg_name(vg_name)
except ValueError as ve:
raise dbus.exceptions.DBusException(
interface, str(ve))
def validate_lv_name(interface, vg_name, lv_name):
try:
_allowable_lv_name(vg_name, lv_name)
except ValueError as ve:
raise dbus.exceptions.DBusException(
interface, str(ve))
def validate_tag(interface, tag):
if not _allowable_tag(tag):
raise dbus.exceptions.DBusException(
interface, 'tag (%s) contains invalid character, allowable set(%s)'
% (tag, _ALLOWABLE_TAG_CH))
def add_no_notify(cmdline):
"""
Given a command line to execute we will see if `--config` is present, if it
is we will add the global/notify_dbus=0 to it, otherwise we will append it
to the end of the list.
:param: cmdline: The command line to inspect
:type: cmdline: list
:return: cmdline with notify_dbus config option present
:rtype: list
"""
# Only after we have seen an external event will be disable lvm from sending
# us one when we call lvm
if cfg.got_external_event:
if 'help' in cmdline:
return cmdline
if '--config' in cmdline:
for i, arg in enumerate(cmdline):
if arg == '--config':
if len(cmdline) <= i+1:
raise dbus.exceptions.DBusException("Missing value for --config option.")
cmdline[i+1] += " global/notify_dbus=0"
break
else:
cmdline.extend(['--config', 'global/notify_dbus=0'])
return cmdline
# The methods below which start with mt_* are used to execute the desired code
# on the the main thread of execution to alleviate any issues the dbus-python
# library with regards to multi-threaded access. Essentially, we are trying to
# ensure all dbus library interaction is done from the same thread!
def _async_result(call_back, results):
log_debug('Results = %s' % str(results))
call_back(results)
# Return result in main thread
def mt_async_result(call_back, results):
GLib.idle_add(_async_result, call_back, results)
# Take the supplied function and run it on the main thread and not wait for
# a result!
def mt_run_no_wait(function, param):
GLib.idle_add(function, param)
# Run the supplied function and arguments on the main thread and wait for them
# to complete while allowing the ability to get the return value too.
#
# Example:
# result = MThreadRunner(foo, arg1, arg2).done()
#
class MThreadRunner(object):
@staticmethod
def runner(obj):
# noinspection PyProtectedMember
obj._run()
with obj.cond:
obj.function_complete = True
obj.cond.notify_all()
def __init__(self, function, *args):
self.f = function
self.rc = None
self.args = args
self.function_complete = False
self.cond = threading.Condition(threading.Lock())
def done(self):
GLib.idle_add(MThreadRunner.runner, self)
with self.cond:
if not self.function_complete:
self.cond.wait()
return self.rc
def _run(self):
if len(self.args):
self.rc = self.f(*self.args)
else:
self.rc = self.f()
def _remove_objects(dbus_objects_rm):
for o in dbus_objects_rm:
cfg.om.remove_object(o, emit_signal=True)
# Remove dbus objects from main thread
def mt_remove_dbus_objects(objs):
MThreadRunner(_remove_objects, objs).done()

786
daemons/lvmdbusd/vg.py Normal file
View File

@ -0,0 +1,786 @@
# Copyright (C) 2015-2016 Red Hat, Inc. All rights reserved.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .automatedproperties import AutomatedProperties
from . import utils
from .utils import pv_obj_path_generate, vg_obj_path_generate, n
import dbus
from . import cfg
from .cfg import VG_INTERFACE
from . import cmdhandler
from .request import RequestEntry
from .loader import common
from .state import State
from . import background
from .utils import round_size, mt_remove_dbus_objects
from .job import JobState
# noinspection PyUnusedLocal
def vgs_state_retrieve(selection, cache_refresh=True):
rc = []
if cache_refresh:
cfg.db.refresh()
for v in cfg.db.fetch_vgs(selection):
rc.append(
VgState(
v['vg_uuid'], v['vg_name'], v['vg_fmt'], n(v['vg_size']),
n(v['vg_free']), v['vg_sysid'], n(v['vg_extent_size']),
n(v['vg_extent_count']), n(v['vg_free_count']),
v['vg_profile'], n(v['max_lv']), n(v['max_pv']),
n(v['pv_count']), n(v['lv_count']), n(v['snap_count']),
n(v['vg_seqno']), n(v['vg_mda_count']),
n(v['vg_mda_free']), n(v['vg_mda_size']),
n(v['vg_mda_used_count']), v['vg_attr'], v['vg_tags']))
return rc
def load_vgs(vg_specific=None, object_path=None, refresh=False,
emit_signal=False, cache_refresh=True):
return common(vgs_state_retrieve, (Vg,), vg_specific, object_path, refresh,
emit_signal, cache_refresh)
# noinspection PyPep8Naming,PyUnresolvedReferences,PyUnusedLocal
class VgState(State):
@property
def lvm_id(self):
return self.Name
def identifiers(self):
return (self.Uuid, self.Name)
def _lv_paths_build(self):
rc = []
for lv in cfg.db.lvs_in_vg(self.Uuid):
(lv_name, meta, lv_uuid) = lv
full_name = "%s/%s" % (self.Name, lv_name)
gen = utils.lv_object_path_method(lv_name, meta)
lv_path = cfg.om.get_object_path_by_uuid_lvm_id(
lv_uuid, full_name, gen)
rc.append(lv_path)
return dbus.Array(rc, signature='o')
def _pv_paths_build(self):
rc = []
for p in cfg.db.pvs_in_vg(self.Uuid):
(pv_name, pv_uuid) = p
rc.append(cfg.om.get_object_path_by_uuid_lvm_id(
pv_uuid, pv_name, pv_obj_path_generate))
return rc
def __init__(self, Uuid, Name, Fmt,
SizeBytes, FreeBytes, SysId, ExtentSizeBytes,
ExtentCount, FreeCount, Profile, MaxLv, MaxPv, PvCount,
LvCount, SnapCount, Seqno, MdaCount, MdaFree,
MdaSizeBytes, MdaUsedCount, attr, tags):
utils.init_class_from_arguments(self)
self.Pvs = self._pv_paths_build()
self.Lvs = self._lv_paths_build()
def create_dbus_object(self, path):
if not path:
path = cfg.om.get_object_path_by_uuid_lvm_id(
self.Uuid, self.Name, vg_obj_path_generate)
return Vg(path, self)
# noinspection PyMethodMayBeStatic
def creation_signature(self):
return (Vg, vg_obj_path_generate)
# noinspection PyPep8Naming
@utils.dbus_property(VG_INTERFACE, 'Uuid', 's')
@utils.dbus_property(VG_INTERFACE, 'Name', 's')
@utils.dbus_property(VG_INTERFACE, 'Fmt', 's')
@utils.dbus_property(VG_INTERFACE, 'SizeBytes', 't', 0)
@utils.dbus_property(VG_INTERFACE, 'FreeBytes', 't', 0)
@utils.dbus_property(VG_INTERFACE, 'SysId', 's')
@utils.dbus_property(VG_INTERFACE, 'ExtentSizeBytes', 't')
@utils.dbus_property(VG_INTERFACE, 'ExtentCount', 't')
@utils.dbus_property(VG_INTERFACE, 'FreeCount', 't')
@utils.dbus_property(VG_INTERFACE, 'Profile', 's')
@utils.dbus_property(VG_INTERFACE, 'MaxLv', 't')
@utils.dbus_property(VG_INTERFACE, 'MaxPv', 't')
@utils.dbus_property(VG_INTERFACE, 'PvCount', 't')
@utils.dbus_property(VG_INTERFACE, 'LvCount', 't')
@utils.dbus_property(VG_INTERFACE, 'SnapCount', 't')
@utils.dbus_property(VG_INTERFACE, 'Seqno', 't')
@utils.dbus_property(VG_INTERFACE, 'MdaCount', 't')
@utils.dbus_property(VG_INTERFACE, 'MdaFree', 't')
@utils.dbus_property(VG_INTERFACE, 'MdaSizeBytes', 't')
@utils.dbus_property(VG_INTERFACE, 'MdaUsedCount', 't')
class Vg(AutomatedProperties):
_Tags_meta = ("as", VG_INTERFACE)
_Pvs_meta = ("ao", VG_INTERFACE)
_Lvs_meta = ("ao", VG_INTERFACE)
_Writeable_meta = ("b", VG_INTERFACE)
_Readable_meta = ("b", VG_INTERFACE)
_Resizeable_meta = ("b", VG_INTERFACE)
_Exportable_meta = ('b', VG_INTERFACE)
_Partial_meta = ('b', VG_INTERFACE)
_AllocContiguous_meta = ('b', VG_INTERFACE)
_AllocCling_meta = ('b', VG_INTERFACE)
_AllocNormal_meta = ('b', VG_INTERFACE)
_AllocAnywhere_meta = ('b', VG_INTERFACE)
_Clustered_meta = ('b', VG_INTERFACE)
# noinspection PyUnusedLocal,PyPep8Naming
def __init__(self, object_path, object_state):
super(Vg, self).__init__(object_path, vgs_state_retrieve)
self.set_interface(VG_INTERFACE)
self._object_path = object_path
self.state = object_state
@staticmethod
def fetch_new_lv(vg_name, lv_name):
return cfg.om.get_object_path_by_lvm_id("%s/%s" % (vg_name, lv_name))
@staticmethod
def handle_execute(rc, out, err):
if rc == 0:
cfg.load()
else:
# Need to work on error handling, need consistent
raise dbus.exceptions.DBusException(
VG_INTERFACE,
'Exit code %s, stderr = %s' % (str(rc), err))
@staticmethod
def validate_dbus_object(vg_uuid, vg_name):
dbo = cfg.om.get_object_by_uuid_lvm_id(vg_uuid, vg_name)
if not dbo:
raise dbus.exceptions.DBusException(
VG_INTERFACE,
'VG with uuid %s and name %s not present!' %
(vg_uuid, vg_name))
return dbo
@staticmethod
def _rename(uuid, vg_name, new_name, rename_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.vg_rename(
vg_name, new_name, rename_options)
Vg.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='sia{sv}', out_signature='o',
async_callbacks=('cb', 'cbe'))
def Rename(self, name, tmo, rename_options, cb, cbe):
utils.validate_vg_name(VG_INTERFACE, name)
r = RequestEntry(tmo, Vg._rename,
(self.state.Uuid, self.state.lvm_id, name,
rename_options), cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _remove(uuid, vg_name, remove_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
# Remove the VG, if successful then remove from the model
rc, out, err = cmdhandler.vg_remove(vg_name, remove_options)
Vg.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='ia{sv}', out_signature='o',
async_callbacks=('cb', 'cbe'))
def Remove(self, tmo, remove_options, cb, cbe):
r = RequestEntry(tmo, Vg._remove,
(self.state.Uuid, self.state.lvm_id, remove_options),
cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _change(uuid, vg_name, change_options):
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.vg_change(change_options, vg_name)
Vg.handle_execute(rc, out, err)
return '/'
# TODO: This should be broken into a number of different methods
# instead of having one method that takes a hash for parameters. Some of
# the changes that vgchange does works on entire system, not just a
# specfic vg, thus that should be in the Manager interface.
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Change(self, tmo, change_options, cb, cbe):
r = RequestEntry(tmo, Vg._change,
(self.state.Uuid, self.state.lvm_id, change_options),
cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _reduce(uuid, vg_name, missing, pv_object_paths, reduce_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
pv_devices = []
# If pv_object_paths is not empty, then get the device paths
if pv_object_paths and len(pv_object_paths) > 0:
for pv_op in pv_object_paths:
pv = cfg.om.get_object_by_path(pv_op)
if pv:
pv_devices.append(pv.lvm_id)
else:
raise dbus.exceptions.DBusException(
VG_INTERFACE,
'PV Object path not found = %s!' % pv_op)
rc, out, err = cmdhandler.vg_reduce(vg_name, missing, pv_devices,
reduce_options)
Vg.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='baoia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Reduce(self, missing, pv_object_paths, tmo, reduce_options, cb, cbe):
r = RequestEntry(tmo, Vg._reduce,
(self.state.Uuid, self.state.lvm_id, missing,
pv_object_paths, reduce_options), cb, cbe, False)
cfg.worker_q.put(r)
@staticmethod
def _extend(uuid, vg_name, pv_object_paths, extend_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
extend_devices = []
for i in pv_object_paths:
pv = cfg.om.get_object_by_path(i)
if pv:
extend_devices.append(pv.lvm_id)
else:
raise dbus.exceptions.DBusException(
VG_INTERFACE, 'PV Object path not found = %s!' % i)
if len(extend_devices):
rc, out, err = cmdhandler.vg_extend(vg_name, extend_devices,
extend_options)
Vg.handle_execute(rc, out, err)
else:
raise dbus.exceptions.DBusException(
VG_INTERFACE, 'No pv_object_paths provided!')
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='aoia{sv}', out_signature='o',
async_callbacks=('cb', 'cbe'))
def Extend(self, pv_object_paths, tmo, extend_options, cb, cbe):
r = RequestEntry(tmo, Vg._extend,
(self.state.Uuid, self.state.lvm_id, pv_object_paths,
extend_options),
cb, cbe, False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='o(tt)a(ott)ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Move(self, pv_src_obj, pv_source_range, pv_dests_and_ranges,
tmo, move_options, cb, cbe):
job_state = JobState()
r = RequestEntry(
tmo, background.move,
(VG_INTERFACE, None, pv_src_obj, pv_source_range,
pv_dests_and_ranges, move_options, job_state), cb, cbe, False,
job_state)
cfg.worker_q.put(r)
@staticmethod
def _lv_create(uuid, vg_name, name, size_bytes, pv_dests_and_ranges,
create_options):
# Make sure we have a dbus object representing it
pv_dests = []
Vg.validate_dbus_object(uuid, vg_name)
if len(pv_dests_and_ranges):
for pr in pv_dests_and_ranges:
pv_dbus_obj = cfg.om.get_object_by_path(pr[0])
if not pv_dbus_obj:
raise dbus.exceptions.DBusException(
VG_INTERFACE,
'PV Destination (%s) not found' % pr[0])
pv_dests.append((pv_dbus_obj.lvm_id, pr[1], pr[2]))
rc, out, err = cmdhandler.vg_lv_create(
vg_name, create_options, name, size_bytes, pv_dests)
Vg.handle_execute(rc, out, err)
return Vg.fetch_new_lv(vg_name, name)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='sta(ott)ia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def LvCreate(self, name, size_bytes, pv_dests_and_ranges,
tmo, create_options, cb, cbe):
"""
This one it for the advanced users that want to roll their own
:param name: Name of the LV
:param size_bytes: Size of LV in bytes
:param pv_dests_and_ranges: Optional array of PV object paths and
ranges
:param tmo: -1 == Wait forever, 0 == return job immediately, > 0 ==
willing to wait that number of seconds before
getting a job
:param create_options: hash of key/value pairs
:param cb: Internal, not accessible by dbus API user
:param cbe: Internal, not accessible by dbus API user
:return: (oo) First object path is newly created object, second is
job object path if created. Each == '/' when it doesn't
apply.
"""
utils.validate_lv_name(VG_INTERFACE, self.Name, name)
r = RequestEntry(tmo, Vg._lv_create,
(self.state.Uuid, self.state.lvm_id,
name, round_size(size_bytes), pv_dests_and_ranges,
create_options), cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _lv_create_linear(uuid, vg_name, name, size_bytes,
thin_pool, create_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.vg_lv_create_linear(
vg_name, create_options, name, size_bytes, thin_pool)
Vg.handle_execute(rc, out, err)
return Vg.fetch_new_lv(vg_name, name)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='stbia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def LvCreateLinear(self, name, size_bytes,
thin_pool, tmo, create_options, cb, cbe):
utils.validate_lv_name(VG_INTERFACE, self.Name, name)
r = RequestEntry(tmo, Vg._lv_create_linear,
(self.state.Uuid, self.state.lvm_id,
name, round_size(size_bytes), thin_pool,
create_options), cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _lv_create_striped(uuid, vg_name, name, size_bytes, num_stripes,
stripe_size_kb, thin_pool, create_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.vg_lv_create_striped(
vg_name, create_options, name, size_bytes,
num_stripes, stripe_size_kb, thin_pool)
Vg.handle_execute(rc, out, err)
return Vg.fetch_new_lv(vg_name, name)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='stuubia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def LvCreateStriped(self, name, size_bytes, num_stripes,
stripe_size_kb, thin_pool, tmo, create_options,
cb, cbe):
utils.validate_lv_name(VG_INTERFACE, self.Name, name)
r = RequestEntry(
tmo, Vg._lv_create_striped,
(self.state.Uuid, self.state.lvm_id, name,
round_size(size_bytes), num_stripes, stripe_size_kb,
thin_pool, create_options),
cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _lv_create_mirror(uuid, vg_name, name, size_bytes,
num_copies, create_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.vg_lv_create_mirror(
vg_name, create_options, name, size_bytes, num_copies)
Vg.handle_execute(rc, out, err)
return Vg.fetch_new_lv(vg_name, name)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='stuia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def LvCreateMirror(self, name, size_bytes, num_copies,
tmo, create_options, cb, cbe):
utils.validate_lv_name(VG_INTERFACE, self.Name, name)
r = RequestEntry(
tmo, Vg._lv_create_mirror,
(self.state.Uuid, self.state.lvm_id, name,
round_size(size_bytes), num_copies,
create_options), cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _lv_create_raid(uuid, vg_name, name, raid_type, size_bytes,
num_stripes, stripe_size_kb, create_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.vg_lv_create_raid(
vg_name, create_options, name, raid_type, size_bytes,
num_stripes, stripe_size_kb)
Vg.handle_execute(rc, out, err)
return Vg.fetch_new_lv(vg_name, name)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='sstuuia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def LvCreateRaid(self, name, raid_type, size_bytes,
num_stripes, stripe_size_kb, tmo,
create_options, cb, cbe):
utils.validate_lv_name(VG_INTERFACE, self.Name, name)
r = RequestEntry(tmo, Vg._lv_create_raid,
(self.state.Uuid, self.state.lvm_id, name,
raid_type, round_size(size_bytes), num_stripes,
stripe_size_kb, create_options), cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _create_pool(uuid, vg_name, meta_data_lv, data_lv,
create_options, create_method):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
# Retrieve the full names for the metadata and data lv
md = cfg.om.get_object_by_path(meta_data_lv)
data = cfg.om.get_object_by_path(data_lv)
if md and data:
new_name = data.Name
rc, out, err = create_method(
md.lv_full_name(), data.lv_full_name(), create_options)
if rc == 0:
mt_remove_dbus_objects((md, data))
Vg.handle_execute(rc, out, err)
else:
msg = ""
if not md:
msg += 'Meta data LV with object path %s not present!' % \
(meta_data_lv)
if not data_lv:
msg += 'Data LV with object path %s not present!' % \
(meta_data_lv)
raise dbus.exceptions.DBusException(VG_INTERFACE, msg)
return Vg.fetch_new_lv(vg_name, new_name)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='ooia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def CreateCachePool(self, meta_data_lv, data_lv, tmo, create_options,
cb, cbe):
r = RequestEntry(
tmo, Vg._create_pool,
(self.state.Uuid, self.state.lvm_id, meta_data_lv,
data_lv, create_options, cmdhandler.vg_create_cache_pool), cb, cbe)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='ooia{sv}',
out_signature='(oo)',
async_callbacks=('cb', 'cbe'))
def CreateThinPool(self, meta_data_lv, data_lv, tmo, create_options,
cb, cbe):
r = RequestEntry(
tmo, Vg._create_pool,
(self.state.Uuid, self.state.lvm_id, meta_data_lv,
data_lv, create_options, cmdhandler.vg_create_thin_pool), cb, cbe)
cfg.worker_q.put(r)
@staticmethod
def _pv_add_rm_tags(uuid, vg_name, pv_object_paths, tags_add,
tags_del, tag_options):
pv_devices = []
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
# Check for existence of pv object paths
for p in pv_object_paths:
pv = cfg.om.get_object_by_path(p)
if pv:
pv_devices.append(pv.Name)
else:
raise dbus.exceptions.DBusException(
VG_INTERFACE, 'PV object path = %s not found' % p)
rc, out, err = cmdhandler.pv_tag(
pv_devices, tags_add, tags_del, tag_options)
Vg.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='aoasia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def PvTagsAdd(self, pvs, tags, tmo, tag_options, cb, cbe):
for t in tags:
utils.validate_tag(VG_INTERFACE, t)
r = RequestEntry(tmo, Vg._pv_add_rm_tags,
(self.state.Uuid, self.state.lvm_id,
pvs, tags, None, tag_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='aoasia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def PvTagsDel(self, pvs, tags, tmo, tag_options, cb, cbe):
for t in tags:
utils.validate_tag(VG_INTERFACE, t)
r = RequestEntry(
tmo, Vg._pv_add_rm_tags,
(self.state.Uuid, self.state.lvm_id,
pvs, None, tags, tag_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@staticmethod
def _vg_add_rm_tags(uuid, vg_name, tags_add, tags_del, tag_options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.vg_tag(
vg_name, tags_add, tags_del, tag_options)
Vg.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='asia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def TagsAdd(self, tags, tmo, tag_options, cb, cbe):
for t in tags:
utils.validate_tag(VG_INTERFACE, t)
r = RequestEntry(tmo, Vg._vg_add_rm_tags,
(self.state.Uuid, self.state.lvm_id,
tags, None, tag_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='asia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def TagsDel(self, tags, tmo, tag_options, cb, cbe):
for t in tags:
utils.validate_tag(VG_INTERFACE, t)
r = RequestEntry(tmo, Vg._vg_add_rm_tags,
(self.state.Uuid, self.state.lvm_id,
None, tags, tag_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@staticmethod
def _vg_change_set(uuid, vg_name, method, value, options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = method(vg_name, value, options)
Vg.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='sia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def AllocationPolicySet(self, policy, tmo, policy_options, cb, cbe):
r = RequestEntry(tmo, Vg._vg_change_set,
(self.state.Uuid, self.state.lvm_id,
cmdhandler.vg_allocation_policy,
policy, policy_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='tia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def MaxPvSet(self, number, tmo, max_options, cb, cbe):
r = RequestEntry(tmo, Vg._vg_change_set,
(self.state.Uuid, self.state.lvm_id,
cmdhandler.vg_max_pv, number, max_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='ia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def UuidGenerate(self, tmo, options, cb, cbe):
r = RequestEntry(tmo, Vg._vg_change_set,
(self.state.Uuid, self.state.lvm_id,
cmdhandler.vg_uuid_gen, None, options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
def _attribute(self, pos, ch):
return dbus.Boolean(self.state.attr[pos] == ch)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='tia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def MaxLvSet(self, number, tmo, max_options, cb, cbe):
r = RequestEntry(tmo, Vg._vg_change_set,
(self.state.Uuid, self.state.lvm_id,
cmdhandler.vg_max_lv, number, max_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@staticmethod
def _vg_activate_deactivate(uuid, vg_name, activate, control_flags,
options):
# Make sure we have a dbus object representing it
Vg.validate_dbus_object(uuid, vg_name)
rc, out, err = cmdhandler.activate_deactivate(
'vgchange', vg_name, activate, control_flags, options)
Vg.handle_execute(rc, out, err)
return '/'
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='tia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Activate(self, control_flags, tmo, activate_options, cb, cbe):
r = RequestEntry(tmo, Vg._vg_activate_deactivate,
(self.state.Uuid, self.state.lvm_id, True,
control_flags, activate_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@dbus.service.method(
dbus_interface=VG_INTERFACE,
in_signature='tia{sv}',
out_signature='o',
async_callbacks=('cb', 'cbe'))
def Deactivate(self, control_flags, tmo, activate_options, cb, cbe):
r = RequestEntry(tmo, Vg._vg_activate_deactivate,
(self.state.Uuid, self.state.lvm_id, False,
control_flags, activate_options),
cb, cbe, return_tuple=False)
cfg.worker_q.put(r)
@property
def Tags(self):
return utils.parse_tags(self.state.tags)
@property
def Pvs(self):
return dbus.Array(self.state.Pvs, signature='o')
@property
def Lvs(self):
return dbus.Array(self.state.Lvs, signature='o')
@property
def lvm_id(self):
return self.state.lvm_id
@property
def Writeable(self):
return self._attribute(0, 'w')
@property
def Readable(self):
return self._attribute(0, 'r')
@property
def Resizeable(self):
return self._attribute(1, 'z')
@property
def Exportable(self):
return self._attribute(2, 'x')
@property
def Partial(self):
return self._attribute(3, 'p')
@property
def AllocContiguous(self):
return self._attribute(4, 'c')
@property
def AllocCling(self):
return self._attribute(4, 'l')
@property
def AllocNormal(self):
return self._attribute(4, 'n')
@property
def AllocAnywhere(self):
return self._attribute(4, 'a')
@property
def Clustered(self):
return self._attribute(5, 'c')

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -37,11 +37,12 @@ int main(int argc, char **argv)
printf("lvmetactl dump\n");
printf("lvmetactl pv_list\n");
printf("lvmetactl vg_list\n");
printf("lvmetactl get_global_info\n");
printf("lvmetactl vg_lookup_name <name>\n");
printf("lvmetactl vg_lookup_uuid <uuid>\n");
printf("lvmetactl pv_lookup_uuid <uuid>\n");
printf("lvmetactl set_global_invalid 0|1\n");
printf("lvmetactl get_global_invalid\n");
printf("lvmetactl set_global_disable 0|1\n");
printf("lvmetactl set_vg_version <uuid> <name> <version>\n");
printf("lvmetactl vg_lock_type <uuid>\n");
return -1;
@ -54,18 +55,32 @@ int main(int argc, char **argv)
if (!strcmp(cmd, "dump")) {
reply = daemon_send_simple(h, "dump",
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);
} else if (!strcmp(cmd, "pv_list")) {
reply = daemon_send_simple(h, "pv_list",
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);
} else if (!strcmp(cmd, "vg_list")) {
reply = daemon_send_simple(h, "vg_list",
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);
} else if (!strcmp(cmd, "get_global_info")) {
reply = daemon_send_simple(h, "get_global_info",
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);
@ -77,16 +92,28 @@ int main(int argc, char **argv)
val = atoi(argv[2]);
reply = daemon_send_simple(h, "set_global_info",
"global_invalid = %d", val,
"global_invalid = " FMTd64, (int64_t) val,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
print_reply(reply);
} else if (!strcmp(cmd, "get_global_invalid")) {
reply = daemon_send_simple(h, "get_global_info",
} else if (!strcmp(cmd, "set_global_disable")) {
if (argc < 3) {
printf("set_global_disable 0|1\n");
return -1;
}
val = atoi(argv[2]);
reply = daemon_send_simple(h, "set_global_info",
"global_disable = " FMTd64, (int64_t) val,
"disable_reason = %s", LVMETAD_DISABLE_REASON_DIRECT,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);
print_reply(reply);
} else if (!strcmp(cmd, "set_vg_version")) {
if (argc < 5) {
@ -106,21 +133,27 @@ int main(int argc, char **argv)
reply = daemon_send_simple(h, "set_vg_info",
"uuid = %s", uuid,
"name = %s", name,
"version = %d", ver,
"token = %s", "skip",
NULL);
"version = " FMTd64, (int64_t) ver,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
} else if (uuid) {
reply = daemon_send_simple(h, "set_vg_info",
"uuid = %s", uuid,
"version = %d", ver,
"token = %s", "skip",
NULL);
"version = " FMTd64, (int64_t) ver,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
} else if (name) {
reply = daemon_send_simple(h, "set_vg_info",
"name = %s", name,
"version = %d", ver,
"token = %s", "skip",
NULL);
"version = " FMTd64, (int64_t) ver,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
} else {
printf("name or uuid required\n");
return -1;
@ -138,6 +171,8 @@ int main(int argc, char **argv)
reply = daemon_send_simple(h, "vg_lookup",
"name = %s", name,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);
@ -151,6 +186,8 @@ int main(int argc, char **argv)
reply = daemon_send_simple(h, "vg_lookup",
"uuid = %s", uuid,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);
@ -167,6 +204,8 @@ int main(int argc, char **argv)
reply = daemon_send_simple(h, "vg_lookup",
"uuid = %s", uuid,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
/* printf("%s\n", reply.buffer.mem); */
@ -193,6 +232,8 @@ int main(int argc, char **argv)
reply = daemon_send_simple(h, "pv_lookup",
"uuid = %s", uuid,
"token = %s", "skip",
"pid = " FMTd64, (int64_t)getpid(),
"cmd = %s", "lvmetactl",
NULL);
printf("%s\n", reply.buffer.mem);

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _LVM_LVMETAD_CLIENT_H
@ -19,6 +19,14 @@
#define LVMETAD_SOCKET DEFAULT_RUN_DIR "/lvmetad.socket"
#define LVMETAD_TOKEN_UPDATE_IN_PROGRESS "update in progress"
#define LVMETAD_DISABLE_REASON_DIRECT "DIRECT"
#define LVMETAD_DISABLE_REASON_LVM1 "LVM1"
#define LVMETAD_DISABLE_REASON_DUPLICATES "DUPLICATES"
#define LVMETAD_DISABLE_REASON_VGRESTORE "VGRESTORE"
#define LVMETAD_DISABLE_REASON_REPAIR "REPAIR"
struct volume_group;
/* Different types of replies we may get from lvmetad. */

File diff suppressed because it is too large Load Diff

View File

@ -9,7 +9,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "tool.h"
@ -75,7 +75,10 @@ int scan(daemon_handle h, char *fn) {
}
char uuid[64];
id_write_format(dev->pvid, uuid, 64);
if (!id_write_format(dev->pvid, uuid, 64)) {
fprintf(stderr, "[C] Failed to format PV UUID for %s", dev_name(dev));
return;
}
fprintf(stderr, "[C] found PV: %s\n", uuid);
struct lvmcache_info *info = (struct lvmcache_info *) label->info;
struct physical_volume pv = { 0, };

View File

@ -9,7 +9,7 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
srcdir = @srcdir@
top_srcdir = @top_srcdir@

View File

@ -18,7 +18,6 @@
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/un.h>
@ -78,7 +77,7 @@ static void save_client_info(char *line)
uint32_t client_id = 0;
char name[MAX_NAME+1] = { 0 };
sscanf(line, "info=client pid=%u fd=%d pi=%d id=%u name=%s",
(void) sscanf(line, "info=client pid=%u fd=%d pi=%d id=%u name=%s",
&pid, &fd, &pi, &client_id, name);
clients[num_clients].client_id = client_id;
@ -111,7 +110,7 @@ static void format_info_ls(char *line)
char lock_args[MAX_ARGS+1] = { 0 };
char lock_type[MAX_NAME+1] = { 0 };
sscanf(line, "info=ls ls_name=%s vg_name=%s vg_uuid=%s vg_sysid=%s vg_args=%s lm_type=%s",
(void) sscanf(line, "info=ls ls_name=%s vg_name=%s vg_uuid=%s vg_sysid=%s vg_args=%s lm_type=%s",
ls_name, vg_name, vg_uuid, vg_sysid, lock_args, lock_type);
if (!first_ls)
@ -132,7 +131,7 @@ static void format_info_ls_action(char *line)
uint32_t pid = 0;
char cl_name[MAX_NAME+1] = { 0 };
sscanf(line, "info=ls_action client_id=%u %s %s op=%s",
(void) sscanf(line, "info=ls_action client_id=%u %s %s op=%s",
&client_id, flags, version, op);
find_client_info(client_id, &pid, cl_name);
@ -148,7 +147,7 @@ static void format_info_r(char *line, char *r_name_out, char *r_type_out)
char sh_count[MAX_NAME+1] = { 0 };
uint32_t ver = 0;
sscanf(line, "info=r name=%s type=%s mode=%s %s version=%u",
(void) sscanf(line, "info=r name=%s type=%s mode=%s %s version=%u",
r_name, r_type, mode, sh_count, &ver);
strcpy(r_name_out, r_name);
@ -186,7 +185,7 @@ static void format_info_lk(char *line, char *r_name, char *r_type)
return;
}
sscanf(line, "info=lk mode=%s version=%u %s client_id=%u",
(void) sscanf(line, "info=lk mode=%s version=%u %s client_id=%u",
mode, &ver, flags, &client_id);
find_client_info(client_id, &pid, cl_name);
@ -222,7 +221,7 @@ static void format_info_r_action(char *line, char *r_name, char *r_type)
return;
}
sscanf(line, "info=r_action client_id=%u %s %s op=%s rt=%s mode=%s %s %s %s",
(void) sscanf(line, "info=r_action client_id=%u %s %s op=%s rt=%s mode=%s %s %s %s",
&client_id, flags, version, op, rt, mode, lm, result, lm_rv);
find_client_info(client_id, &pid, cl_name);
@ -456,7 +455,7 @@ static int do_able(const char *req_name)
reply = _lvmlockd_send(req_name,
"cmd = %s", "lvmlockctl",
"pid = %d", getpid(),
"pid = " FMTd64, (int64_t) getpid(),
"vg_name = %s", arg_vg_name,
NULL);
@ -487,7 +486,7 @@ static int do_stop_lockspaces(void)
reply = _lvmlockd_send("stop_all",
"cmd = %s", "lvmlockctl",
"pid = %d", getpid(),
"pid = " FMTd64, (int64_t) getpid(),
"opts = %s", opts[0] ? opts : "none",
NULL);
@ -522,7 +521,7 @@ static int do_kill(void)
reply = _lvmlockd_send("kill_vg",
"cmd = %s", "lvmlockctl",
"pid = %d", getpid(),
"pid = " FMTd64, (int64_t) getpid(),
"vg_name = %s", arg_vg_name,
NULL);
@ -568,7 +567,7 @@ static int do_drop(void)
reply = _lvmlockd_send("drop_vg",
"cmd = %s", "lvmlockctl",
"pid = %d", getpid(),
"pid = " FMTd64, (int64_t) getpid(),
"vg_name = %s", arg_vg_name,
NULL);

Some files were not shown because too many files have changed in this diff Show More