Merge lp:~vila/bzr/525571-lock-bazaar-conf-files into lp:bzr

Proposed by Vincent Ladeuil
Status: Rejected
Rejected by: Vincent Ladeuil
Proposed branch: lp:~vila/bzr/525571-lock-bazaar-conf-files
Merge into: lp:bzr
Diff against target: 893 lines (+410/-101) (has conflicts)
6 files modified
NEWS (+15/-0)
bzrlib/builtins.py (+27/-14)
bzrlib/config.py (+130/-29)
bzrlib/tests/blackbox/test_break_lock.py (+44/-20)
bzrlib/tests/test_commands.py (+1/-1)
bzrlib/tests/test_config.py (+193/-37)
Text conflict in NEWS
Text conflict in bzrlib/config.py
To merge this branch: bzr merge lp:~vila/bzr/525571-lock-bazaar-conf-files
Reviewer Review Type Date Requested Status
Robert Collins (community) Needs Fixing
Review via email: mp+28898@code.launchpad.net

This proposal supersedes a proposal from 2010-06-29.

Description of the change

The precise circumstances leading to the bug remained unclear, so
here it my best guess: somehow one process was able to read a
conf file *while* another process was writing it and failed
because the file was incomplete leading to parse errors.

ConfigObj does:

                h = open(infile, 'rb')
                infile = h.read() or []
                h.close()

to read a config file.

and
            h = open(self.filename, 'wb')
            h.write(output)
            h.close()

to write a config file.

I.e. the read or write can results in several physical IOs that
could explain partial files being read.

Addressing this is done with:

- using an atomic operation to write the config file so readers
  can't get a partial file,

- using a lock to guarantee that a single writer is allowed at any time.

The data model we use for config files is that they are used a
database where the records are the (name, value) pairs.

When a value is modified, the whole config file is written to
disk.

Config objects themselve are rarely cached (if ever) so to access
a value we generally load the whole file.

From there, it makes sense to re-read the whole file before
setting a new value so that other updates are taken into account
(*not* doing so means we will reset the values ignoring the
concurrent updates).

So the sequence to set a new value is:

- take a write lock,
- re-read the config file (to take concurrent updates into
  account),
- set the new value,
- write the config file,
- unlock

The proposed implementation means that all methods that ends up
writing a config file should be decorated with
@needs_write_lock. This is generally set_user_option() and its
variants (notably set_alias() and unset_alias() for
GlobalConfig).

Note that since we use an atomic write we neglect to protect
readers against concurrent writers. This shouldn't be a problem
in practice and I've been yelled at for suggesting it in a
paranoid attempt to cover all cases. The case at point being:

- a reader opens a file,
- starts to read it (unlikely to not complete in a single IO),
- a writer somehow manages to replace the opened file (unlikely since we
  do a rename),
- the OS presents the new content to the reader.

Since I'm not even sure this scenario is valid, I'll wait for
evidence before considering it.

Anyway, machines can crash while a lock is hold so break-lock has
to be updated to handle the config locks. After discussing the
possible implementations with lifeless, we settled on adding a
--conf option that must be specified to break a config lock. The
actual implementation succeeds when asked to break a lock in a
bzrdir where no lock exist, I did the same. We may want to
revisit the behavior for both cases (failing when no lock are
present) but I consider this out of scope for this bug fix.

I didn't enforce the config directory to be '~/.bazaar', it could
as well be '.bzrmeta' or anything.

To post a comment you must log in.
Revision history for this message
John A Meinel (jameinel) wrote : Posted in a previous version of this proposal

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Vincent Ladeuil wrote:
> Vincent Ladeuil has proposed merging lp:~vila/bzr/525571-lock-bazaar-conf-files into lp:bzr.
>
> Requested reviews:
> bzr-core (bzr-core)
> Related bugs:
> #525571 No locking when updating files in ~/.bazaar
> https://bugs.launchpad.net/bugs/525571
>
>
> This implements a write lock on LocationConfig and GlobalConfig and add support for them in break-lock
> as required for bug #525571.
>
> There is no user nor dev visible change but I'll welcome feedback from plugin authors.
>
> There is a new bzrlib.config.LockableConfig that plugins authors using config files in ~/.bazaar may want to inherit (as LocationConfig and GlobalConfig do now).
>
> I had to do some cleanup in the tests as modifying the model made quite a few of them fail
> (congrats to test authors: failing tests are good tests ! :)
>
> So I made a bit more cleanup than strictly necessary (during failure analysis),
> my apologies to the reviewers.
>

As a comment, without having really read the code thoroughly.

How does this handle stuff like 2 branches locking concurrently
locations.conf. I don't know how often we do it internally, though.

I think lots of filesystem locks on the bazaar directory could adversely
affect performance on Windows. IME locking isn't too expensive if you do
it 1 or 2 times. But if you lock and unlock on every attribute that gets
set, then it probably starts to be an issue.

On a Windows host:
  $ TIMEIT -s "b = Branch.open('.')" "b.lock_write(); b.unlock()"
  10.5msec

On an Ubuntu VM on the same machine:
  $ TIMEIT -s "b = Branch.open('.')" "b.lock_write(); b.unlock()"
  1.55msec

John
=:->
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkwqMNkACgkQJdeBCYSNAAO7WACfYZOte5LfqA4Ro4J6U/3ZA2Cf
ZhkAoLy3d0+tQjcgx047AYI0sJMiZlfY
=mMJj
-----END PGP SIGNATURE-----

Revision history for this message
Robert Collins (lifeless) wrote : Posted in a previous version of this proposal

07:04 -!- guilhembi
[~<email address hidden>] has quit
[Quit: Client exiting]
07:11 < lifeless> vila:
07:11 < lifeless> + __doc__ = """\
07:11 < lifeless> + Break a dead lock on a repository, branch,
working directory or config file.
07:11 < lifeless> I'd prefer to see that spelt as
07:11 < lifeless> __doc__ = \
07:11 < lifeless> """Break...
07:12 < lifeless> because having to actually think about what you were
escaping hurt my brain

Revision history for this message
Robert Collins (lifeless) wrote : Posted in a previous version of this proposal

Meta: This seems like a case where two threads would be nice:
a) fix the tests that are currently a bit gratuitous.
b) make the behaviour change

Revision history for this message
Robert Collins (lifeless) wrote : Posted in a previous version of this proposal

Ok, actual review stuff:
 the docstring layout is wrong, please nuke the \.

We should check for branches first, not config files, because branch locks are the common case and break-lock doesn't need to be slow.

This change is suspicous:

152 def _write_config_file(self):
153 - f = file(self._get_filename(), "wb")
154 + fname = self._get_filename()
155 + conf_dir = os.path.dirname(fname)
156 + ensure_config_dir_exists(conf_dir)
157 + f = file(fname, "wb")
158 try:
159 - osutils.copy_ownership_from_path(f.name)
160 + osutils.copy_ownership_from_path(fname)
161 self._get_parser().write(f)
162 finally:
163 f.close()
164

It appears to be adding a new stat/mkdir check, at the wrong layer.

missing VWS:

172 + """
173 + lock_name = 'lock'

Ditto here:

181 + def lock_write(self, token=None):
182 + if self.lock is None:
183 + ensure_config_dir_exists(self.dir)
184 + self._lock = lockdir.LockDir(self.transport, self.lock_name)
185 + self._lock.lock_write(token)
186 + return lock.LogicalLockResult(self.unlock)

If the dir doesn't exist, something is wrong - we really shouldn't have gotten this far without it, should we?

Docstrings!!!

I'll review the tests after the core is good.

Uh, you raise NoLockDir, but use it to mean 'A config directory that is not locked' which is very odd. Please consider something that means what you need. Also see my ordering suggestion which may help you not to need this at all.

review: Needs Fixing
Revision history for this message
Vincent Ladeuil (vila) wrote : Posted in a previous version of this proposal

> Ok, actual review stuff:
> the docstring layout is wrong, please nuke the \.
>
> We should check for branches first, not config files, because branch locks are
> the common case and break-lock doesn't need to be slow.

break_lock() for wt, branch, repo gives no indication about whether it fails or succeeds.
Trying the conf files first was the easiest.

Regarding performance, I think we don't care at all, the user is supposed to first check that
the lock is not hold by a running process (or someone else) which requires seconds in the best case
or occur long after the lock has been created.

>
> This change is suspicous:
>
> 152 def _write_config_file(self):
> 153 - f = file(self._get_filename(), "wb")
> 154 + fname = self._get_filename()
> 155 + conf_dir = os.path.dirname(fname)
> 156 + ensure_config_dir_exists(conf_dir)
> 157 + f = file(fname, "wb")
> 158 try:
> 159 - osutils.copy_ownership_from_path(f.name)
> 160 + osutils.copy_ownership_from_path(fname)
> 161 self._get_parser().write(f)
> 162 finally:
> 163 f.close()
> 164
>
> It appears to be adding a new stat/mkdir check, at the wrong layer.

No adding there, code duplication removal instead, ensure_config_dir_exists() was called anyway.

>
> missing VWS:
>
> 172 + """
> 173 + lock_name = 'lock'

Fixed.
>
>
>
> Ditto here:
>
> 181 + def lock_write(self, token=None):
> 182 + if self.lock is None:
> 183 + ensure_config_dir_exists(self.dir)
> 184 + self._lock = lockdir.LockDir(self.transport,
> self.lock_name)
> 185 + self._lock.lock_write(token)
> 186 + return lock.LogicalLockResult(self.unlock)
>
> If the dir doesn't exist, something is wrong - we really shouldn't have gotten
> this far without it, should we?

When the config file didn't exist, the config dir needs to be created.

> Docstrings!!!

A bit terse but I will add some.

> Uh, you raise NoLockDir, but use it to mean 'A config directory that is not
> locked' which is very odd.
> Please consider something that means what you need.

I need something that means: "Oh, I wanted to break a lock there but there is no lock dir there,
surely I can't break a lock in that case". I fail to see the oddness :-/

Revision history for this message
Vincent Ladeuil (vila) wrote : Posted in a previous version of this proposal

> As a comment, without having really read the code thoroughly.
>
> How does this handle stuff like 2 branches locking concurrently
> locations.conf. I don't know how often we do it internally, though.

TestLockableConfig.test_writes_are_serialized

>
> I think lots of filesystem locks on the bazaar directory could adversely
> affect performance on Windows. IME locking isn't too expensive if you do
> it 1 or 2 times. But if you lock and unlock on every attribute that gets
> set, then it probably starts to be an issue.

The actual code is not correct, it allows concurrent writers. If higher levels do too many updates of config variables it's a problem in the higher levels, we could imagine holding the updates until the last one, but
this can't addressed here.

Correctness comes before performance, there are many things we can do to address performance but it's way out of scope for this proposal IMHO.

>
> On a Windows host:
> $ TIMEIT -s "b = Branch.open('.')" "b.lock_write(); b.unlock()"
> 10.5msec
>
> On an Ubuntu VM on the same machine:
> $ TIMEIT -s "b = Branch.open('.')" "b.lock_write(); b.unlock()"
> 1.55msec

Thanks, good data point, but still, I haven't seen code doing massive updates of config variables either...

Revision history for this message
John A Meinel (jameinel) wrote :

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

...

> Note that since we use an atomic write we neglect to protect
> readers against concurrent writers. This shouldn't be a problem
> in practice and I've been yelled at for suggesting it in a
> paranoid attempt to cover all cases. The case at point being:
>
> - a reader opens a file,
> - starts to read it (unlikely to not complete in a single IO),
> - a writer somehow manages to replace the opened file (unlikely since we
> do a rename),
> - the OS presents the new content to the reader.
>
> Since I'm not even sure this scenario is valid, I'll wait for
> evidence before considering it.

POSIX systems require that the currently open file stays pointing at the
same content (same inode). While the rename replaces the directory
information, the open file handle does not point to a new file. (You
would have to have 'read' be implemented as (open(), seek(), read(),
close(), to get this behavior.)

Windows says that open() creates a lock on the *path*, which means that
you cannot rename a new file over a file which is already open. (So no
atomic rename operation.)

There is probably a CreateFile flag that might allow it (as there is one
that allows you to delete an open file IIRC). But we don't use it ourselves.

I'm about 95% sure that this scenario is invalid.

John
=:->

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkwrrRMACgkQJdeBCYSNAANG5QCeNjIy3IeDz2fFMW0KPHEUp5qv
gdYAoMG9ymYJX32g3tVRWCsIXF5vke8r
=nu81
-----END PGP SIGNATURE-----

Revision history for this message
Robert Collins (lifeless) wrote :

16:24 < lifeless> vila: --config please, not --conf
16:25 < lifeless> --conf is a strange abbreviation
16:25 < lifeless> c = config.LockableConfig(lambda : location)
16:25 < lifeless> reads really strangely
16:25 < lifeless> perhaps the LockableConfig constructor should be different
16:27 < vila> lifeless: I don't want to break the chain of constructors, I can add a def get_filename if you prefer

When a class provokes ugly code in users, the class is wrong. Perhaps the class could take two keyword constructors, and then only the new code in builtins uses a keyword, and uses the second one to supply a name.

the class can then use it.

The ironic thing here is the first thing the class does is make the filename by calling the constructor.

Please note in the (otherwise excellent) docstring that the reason callers need to lock_write, rather than the innermost writer function, is to ensure that the file is both *read* and *written* in the same lock.

Perhaps that would be best tracked - when doing a read, if the object is not locked, set self._can_write = False, and if it is, set it to True. Then check that as well as whether it is locked, in _write_config.

The file=None to infile=None change seems to just generate spurious noise, and is not done in a backward compatible way.

We are likely going to want to backport this for launchpad, so it really should be a focused patch.

Likewise the test changes that are not related to locking consistency.

Please roll those things back, and I think we'll have a much more focused patch that we can confidently get LP to cherrypick.

review: Needs Fixing
Revision history for this message
Robert Collins (lifeless) wrote :

There's also a number of opaque variable names like 'c', 'p' and 'lc_tests' - while I figured out what they were, they could be a lot clearer.

Revision history for this message
Vincent Ladeuil (vila) wrote :

> 16:24 < lifeless> vila: --config please, not --conf
> 16:25 < lifeless> --conf is a strange abbreviation
> 16:25 < lifeless> c = config.LockableConfig(lambda : location)
> 16:25 < lifeless> reads really strangely
> 16:25 < lifeless> perhaps the LockableConfig constructor should be different
> 16:27 < vila> lifeless: I don't want to break the chain of constructors, I can
> add a def get_filename if you prefer
>
>
> When a class provokes ugly code in users, the class is wrong. Perhaps the
> class could take two keyword constructors, and then only the new code in
> builtins uses a keyword, and uses the second one to supply a name.

I.e. __init__ should accept file_name and get_filename and deprecate the later ?

>
> the class can then use it.

Conflicts with making a focused patch. I'll keep that for an updated submission focused on cleanup.

>
> The ironic thing here is the first thing the class does is make the filename
> by calling the constructor.

Yup, it's needed to build the lock directory (I'm sure you got that). The other classes postpone the get_filename() evaluation until it's needed, but given the functions used to provide the names, I don't think postponing is really required (some env variables are involved though, so there may be edge cases).

>
> Please note in the (otherwise excellent) docstring that the reason callers
> need to lock_write, rather than the innermost writer function, is to ensure
> that the file is both *read* and *written* in the same lock.
>

I'll mention that. And yes, it's the real reason for requiring a larger lock scope.

> Perhaps that would be best tracked - when doing a read, if the object is not
> locked, set self._can_write = False, and if it is, set it to True. Then check
> that as well as whether it is locked, in _write_config.

_can_write == is_locked() I see the idea but it won't change the end result nor the feedback we can give.

>
>
> The file=None to infile=None change seems to just generate spurious noise, and
> is not done in a backward compatible way.

It's on a private method and used only by tests (and provide a poor way to build test configs anyway).

>
> We are likely going to want to backport this for launchpad, so it really
> should be a focused patch.

I'll restart from scratch then.

>
> Likewise the test changes that are not related to locking consistency.

Most of them were required to address the flawed assumption that a config object (with content)
can be created without an actual file existing, I had to fix the failing tests.
The duplicated ensure_config_dir_exists() came in the way to.

And I mention that to explain that many cleanups were not for the sake of pure cleaning but driven by problems making the fix harder.

I'll look into an alternative solution to minimise the patch but that would likely end up in either weird code or intrusive changes, we'll see.

Revision history for this message
Vincent Ladeuil (vila) wrote :

> 16:24 < lifeless> vila: --config please, not --conf
> 16:25 < lifeless> --conf is a strange abbreviation

:-P

Revision history for this message
Robert Collins (lifeless) wrote :

Vila, I think I need to expand on this:

>> Perhaps that would be best tracked - when doing a read, if the object is not
>> locked, set self._can_write = False, and if it is, set it to True. Then check
>> that as well as whether it is locked, in _write_config.

> _can_write == is_locked() I see the idea but it won't change the end result nor the feedback we can give.

They are quite different.

If when you *read* you are unlocked, and you permit a *write* without forcing a new read, changes from other processes are discarded.

Here:
conf.read_something()
--client 2 writes to the file
conf.set_something()
--*boom* client 2's changes are lost

What we need is two fold: detection of this case (which setting 'can write' during *read* if it is write locked at the time will permit), and easy api use (which may be less immediate depending on impact).

Alternatively lock_write could possibly trigger a read after locking before returning, which would cause properly lock_write() guarded mutators to work correctly - as they would apply the mutation within the locked context.

In short - concurrency is hard, lets drink beer.

review: Needs Fixing
Revision history for this message
John Szakmeister (jszakmeister) wrote :

On Sun, Jul 4, 2010 at 6:39 PM, Robert Collins
<email address hidden> wrote:
[snip]
> In short - concurrency is hard, lets drink beer.

I think that's the best quote I've seen in a while! :-)

-John

Revision history for this message
Vincent Ladeuil (vila) wrote :
Download full text (3.5 KiB)

>>>>> Robert Collins <email address hidden> writes:

    > Review: Needs Fixing
    > Vila, I think I need to expand on this:

    >>> Perhaps that would be best tracked - when doing a read, if the object is not
    >>> locked, set self._can_write = False, and if it is, set it to True. Then check
    >>> that as well as whether it is locked, in _write_config.

    >> _can_write == is_locked() I see the idea but it won't change the end result nor the feedback we can give.

    > They are quite different.

    > If when you *read* you are unlocked, and you permit a *write*
    > without forcing a new read,

Which this proposal guards against.

    > changes from other processes are discarded.

Yes, that's a delicate problem. This proposal isn't perfect but good
enough to cover most of our use cases.

    > Here:
    > conf.read_something()
    > --client 2 writes to the file
    > conf.set_something()
    > --*boom* client 2's changes are lost

Yup, I added a test for that and saw it fail.

    > What we need is two fold: detection of this case (which setting
    > 'can write' during *read* if it is write locked at the time will
    > permit),

Right, but what will we gain here ? The ability to *not* force the
refreshing read if someone already did it while write locked ?

Yet, it goes in the same direction as implementing a no-op read lock,
which we may want to add too, so, worth considering.

    > and easy api use (which may be less immediate depending on
    > impact).

    > Alternatively lock_write could possibly trigger a read after
    > locking before returning, which would cause properly lock_write()
    > guarded mutators to work correctly - as they would apply the
    > mutation within the locked context.

Inside the lock scope, a write should always happen *after* a refreshing
read or you'll lose changes for variables you're not changing (the
current API change one variable at a time).

Of course you always lose any change to the variable you're changing and
that in itself could be a problem if processes try to use config
variables for synchronization (a really bad idea), like an incremented
counter.

    > In short - concurrency is hard, lets drink beer.

+1

There are various lock schemes with different scopes that can be tried,
but so far, I haven't found a good way to address:

- client1 read 'var'
- client1 starts a "long" process based on 'var'
- client2 set a new value for 'var'
- client1 finished its process with a now outdated value for 'var'

Short of blocking client2 for the duration of client1 process, I can't
see how to address this.

But do we care ?

It's hard to decide without concrete examples, if 'var' is a parent
branch location and the process is pull, chances are the user really
want its pull to finish and changing 'var' to point to a new branch
should just be considered the next time we try to pull (alternate
scenarios includes: abort the pull (and rollback the already fetched
revisions (eeerk)), block the write (i.e. block the whole config file
for the duration of client1 process (omg are you crazy ?))).

Overall, I agree that we should continue thinking about which lock model
we want here, the proposed...

Read more...

Revision history for this message
Vincent Ladeuil (vila) wrote :

Marking as WIP pending a discussion during our next sprint on larger issues.
A minimal fix has landed for 2.1 using atomic writes which should be a good enough fix in the mean time.

Revision history for this message
John A Meinel (jameinel) wrote :

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

...

>
> Overall, I agree that we should continue thinking about which lock model
> we want here, the proposed one is incrementally better and at least
> address the bug better than the minimal one landed for 2.1.
>
> Orthogonal to the lock scope, sharing a config files at the
> wt/branch/repo level could at least avoid reading the config file for
> each variable which could make read locks less painful, but still, I
> don't think it would be enough.

I think defining a scope is reasonable, and just sticking with that.

IMO, configs could be treated just like the rest of the branch data. So
if you '.lock_read()' at the beginning of a process, you read the config
state at that point in time, and then never read the config file again.

When you go to write, you probably need to re-read the file, because a
given text file has more content than what you are likely to be adjusting.

We *could* implement some sort of CAS to make config updates atomic. I
don't think that is worthwhile. (I tried to overwrite parent X with
parent Y, but parent was already Z.)

I agree that you shouldn't try to abuse configs to store incremental
counters, etc.

I honestly don't know what state was getting trashed by concurrent
updates, but I have the feeling that all of the bzr core data doesn't
really care. (Yes, you might get the wrong parent pointer, or submit
pointer, but we don't really store 'live' data in conf files.)

John
=:->
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkwzP7gACgkQJdeBCYSNAANa5QCdFVLPjMHJLyKn7MvR9NdkiAhp
6r8An3u2enhCMDQVbPS/wOmeo5LUO6X3
=Kmd7
-----END PGP SIGNATURE-----

5334. By Vincent Ladeuil

Clarify lock scope.

5335. By Vincent Ladeuil

Use --config instead of --conf for break-lock.

Revision history for this message
Vincent Ladeuil (vila) wrote :

Unmerged revisions

5335. By Vincent Ladeuil

Use --config instead of --conf for break-lock.

5334. By Vincent Ladeuil

Clarify lock scope.

5333. By Vincent Ladeuil

Final cleanup.

5332. By Vincent Ladeuil

Implement the --conf option for break-lock as per lifeless suggestion.

* bzrlib/errors.py:
(NoLockDir): Useless, deleted.

* bzrlib/config.py:
(LockableConfig.unlock): NoLockDir is useless, break_lock()
silenty succeeds if the directory doesn't exist.

* bzrlib/tests/blackbox/test_break_lock.py:
Tweak the tests.

* bzrlib/builtins.py:
(cmd_break_lock): Fix docstring, add a --conf option to deal with
config files.

5331. By Vincent Ladeuil

Add a test to help LockableConfig daughter classes identify methods that needs to be decorated.

5330. By Vincent Ladeuil

Further clarify NEWS entry.

5329. By Vincent Ladeuil

Fix docstring.

5328. By Vincent Ladeuil

Fix wrong bug number and clarify NEWS entries.

5327. By Vincent Ladeuil

Revert the lock scope to a sane value.

* bzrlib/tests/test_config.py:
(TestLockableConfig.test_writes_are_serialized)
(TestLockableConfig.test_read_while_writing): Fix the fallouts.

* bzrlib/config.py:
(LockableConfig): Wrong idea, the lock needs to be taken arond the
whole value update call, reducing the lock scope to
_write_config_file exclude the config file re-read.
(GlobalConfig.set_user_option, GlobalConfig.set_alias)
(GlobalConfig.unset_alias, LocationConfig.set_user_option): These
methods needs to be decorated with needs_write_lock to enforce the
design constraints (lock, re-read config, set new value, write
config, unlock).

5326. By Vincent Ladeuil

Add some comments.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'NEWS'
--- NEWS 2010-07-13 21:25:03 +0000
+++ NEWS 2010-07-14 08:34:44 +0000
@@ -119,6 +119,15 @@
119New Features119New Features
120************120************
121121
122* ``bzr break-lock --config [location]`` can now break config files
123 locks. (Vincent Ladeuil, #525571)
124
125* ``bzrlib.config.LockableConfig`` is a base class for config files that
126 needs to be protected against multiple writers. All methods that
127 change a configuration variable value must be decorated with
128 @needs_write_lock (set_option() for example).
129 (Vincent Ladeuil, #525571)
130
122* Support ``--directory`` option for a number of additional commands:131* Support ``--directory`` option for a number of additional commands:
123 conflicts, merge-directive, missing, resolve, shelve, switch,132 conflicts, merge-directive, missing, resolve, shelve, switch,
124 unshelve, whoami. (Martin von Gagern, #527878)133 unshelve, whoami. (Martin von Gagern, #527878)
@@ -145,6 +154,7 @@
145 or pull location in locations.conf or branch.conf.154 or pull location in locations.conf or branch.conf.
146 (Gordon Tyler, #534787)155 (Gordon Tyler, #534787)
147156
157<<<<<<< TREE
148* ``bzr reconfigure --unstacked`` now works with branches accessed via a158* ``bzr reconfigure --unstacked`` now works with branches accessed via a
149 smart server. (Andrew Bennetts, #551525)159 smart server. (Andrew Bennetts, #551525)
150160
@@ -154,6 +164,11 @@
154* ``BzrDir.find_bzrdirs`` should ignore dirs that raises PermissionDenied.164* ``BzrDir.find_bzrdirs`` should ignore dirs that raises PermissionDenied.
155 (Marius Kruger, Robert Collins)165 (Marius Kruger, Robert Collins)
156166
167=======
168* Configuration files in ``${BZR_HOME}`` are now protected
169 against concurrent writers. (Vincent Ladeuil, #525571)
170
171>>>>>>> MERGE-SOURCE
157* Ensure that wrong path specifications in ``BZR_PLUGINS_AT`` display172* Ensure that wrong path specifications in ``BZR_PLUGINS_AT`` display
158 proper error messages. (Vincent Ladeuil, #591215)173 proper error messages. (Vincent Ladeuil, #591215)
159174
160175
=== modified file 'bzrlib/builtins.py'
--- bzrlib/builtins.py 2010-06-30 12:13:14 +0000
+++ bzrlib/builtins.py 2010-07-14 08:34:44 +0000
@@ -33,7 +33,7 @@
33 bzrdir,33 bzrdir,
34 directory_service,34 directory_service,
35 delta,35 delta,
36 config,36 config as _mod_config,
37 errors,37 errors,
38 globbing,38 globbing,
39 hooks,39 hooks,
@@ -3332,7 +3332,7 @@
3332 try:3332 try:
3333 c = Branch.open_containing(u'.')[0].get_config()3333 c = Branch.open_containing(u'.')[0].get_config()
3334 except errors.NotBranchError:3334 except errors.NotBranchError:
3335 c = config.GlobalConfig()3335 c = _mod_config.GlobalConfig()
3336 else:3336 else:
3337 c = Branch.open(directory).get_config()3337 c = Branch.open(directory).get_config()
3338 if email:3338 if email:
@@ -3343,7 +3343,7 @@
33433343
3344 # display a warning if an email address isn't included in the given name.3344 # display a warning if an email address isn't included in the given name.
3345 try:3345 try:
3346 config.extract_email_address(name)3346 _mod_config.extract_email_address(name)
3347 except errors.NoEmailInUsername, e:3347 except errors.NoEmailInUsername, e:
3348 warning('"%s" does not seem to contain an email address. '3348 warning('"%s" does not seem to contain an email address. '
3349 'This is allowed, but not recommended.', name)3349 'This is allowed, but not recommended.', name)
@@ -3355,7 +3355,7 @@
3355 else:3355 else:
3356 c = Branch.open(directory).get_config()3356 c = Branch.open(directory).get_config()
3357 else:3357 else:
3358 c = config.GlobalConfig()3358 c = _mod_config.GlobalConfig()
3359 c.set_user_option('email', name)3359 c.set_user_option('email', name)
33603360
33613361
@@ -3428,13 +3428,13 @@
3428 'bzr alias --remove expects an alias to remove.')3428 'bzr alias --remove expects an alias to remove.')
3429 # If alias is not found, print something like:3429 # If alias is not found, print something like:
3430 # unalias: foo: not found3430 # unalias: foo: not found
3431 c = config.GlobalConfig()3431 c = _mod_config.GlobalConfig()
3432 c.unset_alias(alias_name)3432 c.unset_alias(alias_name)
34333433
3434 @display_command3434 @display_command
3435 def print_aliases(self):3435 def print_aliases(self):
3436 """Print out the defined aliases in a similar format to bash."""3436 """Print out the defined aliases in a similar format to bash."""
3437 aliases = config.GlobalConfig().get_aliases()3437 aliases = _mod_config.GlobalConfig().get_aliases()
3438 for key, value in sorted(aliases.iteritems()):3438 for key, value in sorted(aliases.iteritems()):
3439 self.outf.write('bzr alias %s="%s"\n' % (key, value))3439 self.outf.write('bzr alias %s="%s"\n' % (key, value))
34403440
@@ -3450,7 +3450,7 @@
34503450
3451 def set_alias(self, alias_name, alias_command):3451 def set_alias(self, alias_name, alias_command):
3452 """Save the alias in the global config."""3452 """Save the alias in the global config."""
3453 c = config.GlobalConfig()3453 c = _mod_config.GlobalConfig()
3454 c.set_alias(alias_name, alias_command)3454 c.set_alias(alias_name, alias_command)
34553455
34563456
@@ -4829,7 +4829,10 @@
48294829
48304830
4831class cmd_break_lock(Command):4831class cmd_break_lock(Command):
4832 __doc__ = """Break a dead lock on a repository, branch or working directory.4832 __doc__ = """Break a dead lock.
4833
4834 This command breaks a lock on a repository, branch, working directory or
4835 config file.
48334836
4834 CAUTION: Locks should only be broken when you are sure that the process4837 CAUTION: Locks should only be broken when you are sure that the process
4835 holding the lock has been stopped.4838 holding the lock has been stopped.
@@ -4840,17 +4843,27 @@
4840 :Examples:4843 :Examples:
4841 bzr break-lock4844 bzr break-lock
4842 bzr break-lock bzr+ssh://example.com/bzr/foo4845 bzr break-lock bzr+ssh://example.com/bzr/foo
4846 bzr break-lock --conf ~/.bazaar
4843 """4847 """
4848
4844 takes_args = ['location?']4849 takes_args = ['location?']
4850 takes_options = [
4851 Option('config',
4852 help='LOCATION is the directory where the config lock is.'),
4853 ]
48454854
4846 def run(self, location=None, show=False):4855 def run(self, location=None, config=False):
4847 if location is None:4856 if location is None:
4848 location = u'.'4857 location = u'.'
4849 control, relpath = bzrdir.BzrDir.open_containing(location)4858 if config:
4850 try:4859 conf = _mod_config.LockableConfig(lambda : location)
4851 control.break_lock()4860 conf.break_lock()
4852 except NotImplementedError:4861 else:
4853 pass4862 control, relpath = bzrdir.BzrDir.open_containing(location)
4863 try:
4864 control.break_lock()
4865 except NotImplementedError:
4866 pass
48544867
48554868
4856class cmd_wait_until_signalled(Command):4869class cmd_wait_until_signalled(Command):
48574870
=== modified file 'bzrlib/config.py'
--- bzrlib/config.py 2010-07-13 16:10:20 +0000
+++ bzrlib/config.py 2010-07-14 08:34:44 +0000
@@ -62,9 +62,11 @@
62up=pull62up=pull
63"""63"""
6464
65from cStringIO import StringIO
65import os66import os
66import sys67import sys
6768
69from bzrlib.decorators import needs_write_lock
68from bzrlib.lazy_import import lazy_import70from bzrlib.lazy_import import lazy_import
69lazy_import(globals(), """71lazy_import(globals(), """
70import errno72import errno
@@ -77,11 +79,14 @@
77 atomicfile,79 atomicfile,
78 debug,80 debug,
79 errors,81 errors,
82 lock,
83 lockdir,
80 mail_client,84 mail_client,
81 osutils,85 osutils,
82 registry,86 registry,
83 symbol_versioning,87 symbol_versioning,
84 trace,88 trace,
89 transport,
85 ui,90 ui,
86 urlutils,91 urlutils,
87 win32utils,92 win32utils,
@@ -357,18 +362,35 @@
357 self._get_filename = get_filename362 self._get_filename = get_filename
358 self._parser = None363 self._parser = None
359364
360 def _get_parser(self, file=None):365 def _get_parser(self, infile=None):
361 if self._parser is not None:366 if self._parser is not None:
362 return self._parser367 return self._parser
363 if file is None:368 # Do we have a file name for the config file
364 input = self._get_filename()369 if self._get_filename is None:
365 else:370 fname = None
366 input = file371 else:
372 fname = self._get_filename()
373 # Do we have a content for the config file ?
374 if infile is None:
375 fname_or_content = fname
376 else:
377 fname_or_content = infile
378 # Build the ConfigObj
379 p = None
367 try:380 try:
368 self._parser = ConfigObj(input, encoding='utf-8')381 p = ConfigObj(fname_or_content, encoding='utf-8')
369 except configobj.ConfigObjError, e:382 except configobj.ConfigObjError, e:
370 raise errors.ParseConfigError(e.errors, e.config.filename)383 raise errors.ParseConfigError(e.errors, e.config.filename)
371 return self._parser384 if p is not None and fname is not None:
385 # Make sure p.reload() will use the right file name
386 p.filename = fname
387 self._parser = p
388 return p
389
390 def reload(self):
391 """Reload the config file from disk."""
392 if self._parser is not None:
393 self._parser.reload()
372394
373 def _get_matching_sections(self):395 def _get_matching_sections(self):
374 """Return an ordered list of (section_name, extra_path) pairs.396 """Return an ordered list of (section_name, extra_path) pairs.
@@ -479,38 +501,122 @@
479 return self.get_user_option('nickname')501 return self.get_user_option('nickname')
480502
481 def _write_config_file(self):503 def _write_config_file(self):
504<<<<<<< TREE
482 atomic_file = atomicfile.AtomicFile(self._get_filename())505 atomic_file = atomicfile.AtomicFile(self._get_filename())
483 self._get_parser().write(atomic_file)506 self._get_parser().write(atomic_file)
484 atomic_file.commit()507 atomic_file.commit()
485 atomic_file.close()508 atomic_file.close()
486509=======
487510 fname = self._get_filename()
488class GlobalConfig(IniBasedConfig):511 conf_dir = os.path.dirname(fname)
512 ensure_config_dir_exists(conf_dir)
513 f = file(fname, "wb")
514 try:
515 osutils.copy_ownership_from_path(fname)
516 self._get_parser().write(f)
517 finally:
518 f.close()
519>>>>>>> MERGE-SOURCE
520
521
522class LockableConfig(IniBasedConfig):
523 """A configuration needing explicit locking for access.
524
525 If several processes try to write the config file, the accesses need to be
526 serialized.
527
528 Daughter classes should decorate all methods that update a config with the
529 ``@needs_write_lock`` decorator (they call, directly or indirectly, the
530 ``_write_config_file()`` method. These methods (typically ``set_option()``
531 and variants must reload the config file from disk before calling
532 ``_write_config_file()``), this can be achieved by calling the
533 ``self.reload()`` method. Note that the lock scope should cover both the
534 reading and the writing of the config file which is why the decorator can't
535 be applied to ``_write_config_file()`` only.
536
537 This should be enough to implement the following logic:
538 - lock for exclusive write access,
539 - reload the config file from disk,
540 - set the new value
541 - unlock
542
543 This logic guarantees that a writer can update a value without erasing an
544 update made by another writer.
545 """
546
547 lock_name = 'lock'
548
549 def __init__(self, get_filename):
550 super(LockableConfig, self).__init__(get_filename)
551 self.dir = osutils.dirname(osutils.safe_unicode(self._get_filename()))
552 self.transport = transport.get_transport(self.dir)
553 self._lock = None
554
555 def lock_write(self, token=None):
556 """Takes a write lock in the directory containing the config file.
557
558 If the directory doesn't exist it is created.
559 """
560 if self._lock is None:
561 ensure_config_dir_exists(self.dir)
562 self._lock = lockdir.LockDir(self.transport, self.lock_name)
563 self._lock.lock_write(token)
564 return lock.LogicalLockResult(self.unlock)
565
566 def unlock(self):
567 self._lock.unlock()
568
569 def break_lock(self):
570 if self._lock is None:
571 self._lock = lockdir.LockDir(self.transport, self.lock_name)
572 self._lock.break_lock()
573
574 def _write_config_file(self):
575 if self._lock is None or not self._lock.is_held:
576 # NB: if the following exception is raised it probably means a
577 # missing @needs_write_lock decorator on one of the callers.
578 raise errors.ObjectNotLocked(self)
579 fname = self._get_filename()
580 f = StringIO()
581 p = self._get_parser()
582 p.write(f)
583 self.transport.put_bytes(os.path.basename(fname), f.getvalue())
584 # Make sure p.reload() will use the right file name
585 p.filename = fname
586 osutils.copy_ownership_from_path(fname)
587
588
589class GlobalConfig(LockableConfig):
489 """The configuration that should be used for a specific location."""590 """The configuration that should be used for a specific location."""
490591
491 def get_editor(self):
492 return self._get_user_option('editor')
493
494 def __init__(self):592 def __init__(self):
495 super(GlobalConfig, self).__init__(config_filename)593 super(GlobalConfig, self).__init__(config_filename)
496594
595 @needs_write_lock
497 def set_user_option(self, option, value):596 def set_user_option(self, option, value):
498 """Save option and its value in the configuration."""597 """Save option and its value in the configuration."""
499 self._set_option(option, value, 'DEFAULT')598 self._set_option(option, value, 'DEFAULT')
500599
600 def get_editor(self):
601 return self._get_user_option('editor')
602
501 def get_aliases(self):603 def get_aliases(self):
502 """Return the aliases section."""604 """Return the aliases section."""
503 if 'ALIASES' in self._get_parser():605 p = self._get_parser()
504 return self._get_parser()['ALIASES']606 if 'ALIASES' in p:
607 return p['ALIASES']
505 else:608 else:
506 return {}609 return {}
507610
611 @needs_write_lock
508 def set_alias(self, alias_name, alias_command):612 def set_alias(self, alias_name, alias_command):
509 """Save the alias in the configuration."""613 """Save the alias in the configuration."""
510 self._set_option(alias_name, alias_command, 'ALIASES')614 self._set_option(alias_name, alias_command, 'ALIASES')
511615
616 @needs_write_lock
512 def unset_alias(self, alias_name):617 def unset_alias(self, alias_name):
513 """Unset an existing alias."""618 """Unset an existing alias."""
619 self.reload()
514 aliases = self._get_parser().get('ALIASES')620 aliases = self._get_parser().get('ALIASES')
515 if not aliases or alias_name not in aliases:621 if not aliases or alias_name not in aliases:
516 raise errors.NoSuchAlias(alias_name)622 raise errors.NoSuchAlias(alias_name)
@@ -518,15 +624,12 @@
518 self._write_config_file()624 self._write_config_file()
519625
520 def _set_option(self, option, value, section):626 def _set_option(self, option, value, section):
521 # FIXME: RBC 20051029 This should refresh the parser and also take a627 self.reload()
522 # file lock on bazaar.conf.
523 conf_dir = os.path.dirname(self._get_filename())
524 ensure_config_dir_exists(conf_dir)
525 self._get_parser().setdefault(section, {})[option] = value628 self._get_parser().setdefault(section, {})[option] = value
526 self._write_config_file()629 self._write_config_file()
527630
528631
529class LocationConfig(IniBasedConfig):632class LocationConfig(LockableConfig):
530 """A configuration object that gives the policy for a location."""633 """A configuration object that gives the policy for a location."""
531634
532 def __init__(self, location):635 def __init__(self, location):
@@ -642,6 +745,7 @@
642 if policy_key in self._get_parser()[section]:745 if policy_key in self._get_parser()[section]:
643 del self._get_parser()[section][policy_key]746 del self._get_parser()[section][policy_key]
644747
748 @needs_write_lock
645 def set_user_option(self, option, value, store=STORE_LOCATION):749 def set_user_option(self, option, value, store=STORE_LOCATION):
646 """Save option and its value in the configuration."""750 """Save option and its value in the configuration."""
647 if store not in [STORE_LOCATION,751 if store not in [STORE_LOCATION,
@@ -649,19 +753,16 @@
649 STORE_LOCATION_APPENDPATH]:753 STORE_LOCATION_APPENDPATH]:
650 raise ValueError('bad storage policy %r for %r' %754 raise ValueError('bad storage policy %r for %r' %
651 (store, option))755 (store, option))
652 # FIXME: RBC 20051029 This should refresh the parser and also take a756 self.reload()
653 # file lock on locations.conf.757 p = self._get_parser()
654 conf_dir = os.path.dirname(self._get_filename())
655 ensure_config_dir_exists(conf_dir)
656 location = self.location758 location = self.location
657 if location.endswith('/'):759 if location.endswith('/'):
658 location = location[:-1]760 location = location[:-1]
659 if (not location in self._get_parser() and761 if not location in p and not location + '/' in p:
660 not location + '/' in self._get_parser()):762 p[location] = {}
661 self._get_parser()[location]={}763 elif location + '/' in p:
662 elif location + '/' in self._get_parser():
663 location = location + '/'764 location = location + '/'
664 self._get_parser()[location][option]=value765 p[location][option] = value
665 # the allowed values of store match the config policies766 # the allowed values of store match the config policies
666 self._set_option_policy(location, option, store)767 self._set_option_policy(location, option, store)
667 self._write_config_file()768 self._write_config_file()
668769
=== modified file 'bzrlib/tests/blackbox/test_break_lock.py'
--- bzrlib/tests/blackbox/test_break_lock.py 2010-06-11 07:32:12 +0000
+++ bzrlib/tests/blackbox/test_break_lock.py 2010-07-14 08:34:44 +0000
@@ -18,17 +18,18 @@
1818
19import os19import os
2020
21import bzrlib
22from bzrlib import (21from bzrlib import (
22 branch,
23 bzrdir,
24 config,
23 errors,25 errors,
24 lockdir,26 lockdir,
27 osutils,
28 tests,
25 )29 )
26from bzrlib.branch import Branch30
27from bzrlib.bzrdir import BzrDir31
28from bzrlib.tests import TestCaseWithTransport32class TestBreakLock(tests.TestCaseWithTransport):
29
30
31class TestBreakLock(TestCaseWithTransport):
3233
33 # General principal for break-lock: All the elements that might be locked34 # General principal for break-lock: All the elements that might be locked
34 # by a bzr operation on PATH, are candidates that break-lock may unlock.35 # by a bzr operation on PATH, are candidates that break-lock may unlock.
@@ -52,14 +53,14 @@
52 'repo/',53 'repo/',
53 'repo/branch/',54 'repo/branch/',
54 'checkout/'])55 'checkout/'])
55 bzrlib.bzrdir.BzrDir.create('master-repo').create_repository()56 bzrdir.BzrDir.create('master-repo').create_repository()
56 self.master_branch = bzrlib.bzrdir.BzrDir.create_branch_convenience(57 self.master_branch = bzrdir.BzrDir.create_branch_convenience(
57 'master-repo/master-branch')58 'master-repo/master-branch')
58 bzrlib.bzrdir.BzrDir.create('repo').create_repository()59 bzrdir.BzrDir.create('repo').create_repository()
59 local_branch = bzrlib.bzrdir.BzrDir.create_branch_convenience('repo/branch')60 local_branch = bzrdir.BzrDir.create_branch_convenience('repo/branch')
60 local_branch.bind(self.master_branch)61 local_branch.bind(self.master_branch)
61 checkoutdir = bzrlib.bzrdir.BzrDir.create('checkout')62 checkoutdir = bzrdir.BzrDir.create('checkout')
62 bzrlib.branch.BranchReferenceFormat().initialize(63 branch.BranchReferenceFormat().initialize(
63 checkoutdir, target_branch=local_branch)64 checkoutdir, target_branch=local_branch)
64 self.wt = checkoutdir.create_workingtree()65 self.wt = checkoutdir.create_workingtree()
6566
@@ -73,7 +74,7 @@
73 # however, we dont test breaking the working tree because we74 # however, we dont test breaking the working tree because we
74 # cannot accurately do so right now: the dirstate lock is held75 # cannot accurately do so right now: the dirstate lock is held
75 # by an os lock, and we need to spawn a separate process to lock it76 # by an os lock, and we need to spawn a separate process to lock it
76 # thne kill -9 it.77 # then kill -9 it.
77 # sketch of test:78 # sketch of test:
78 # lock most of the dir:79 # lock most of the dir:
79 self.wt.branch.lock_write()80 self.wt.branch.lock_write()
@@ -82,22 +83,45 @@
82 # we need 5 yes's - wt, branch, repo, bound branch, bound repo.83 # we need 5 yes's - wt, branch, repo, bound branch, bound repo.
83 self.run_bzr('break-lock checkout', stdin="y\ny\ny\ny\n")84 self.run_bzr('break-lock checkout', stdin="y\ny\ny\ny\n")
84 # a new tree instance should be lockable85 # a new tree instance should be lockable
85 branch = bzrlib.branch.Branch.open('checkout')86 b = branch.Branch.open('checkout')
86 branch.lock_write()87 b.lock_write()
87 branch.unlock()88 b.unlock()
88 # and a new instance of the master branch89 # and a new instance of the master branch
89 mb = branch.get_master_branch()90 mb = b.get_master_branch()
90 mb.lock_write()91 mb.lock_write()
91 mb.unlock()92 mb.unlock()
92 self.assertRaises(errors.LockBroken, self.wt.unlock)93 self.assertRaises(errors.LockBroken, self.wt.unlock)
93 self.assertRaises(errors.LockBroken, self.master_branch.unlock)94 self.assertRaises(errors.LockBroken, self.master_branch.unlock)
9495
9596
96class TestBreakLockOldBranch(TestCaseWithTransport):97class TestBreakLockOldBranch(tests.TestCaseWithTransport):
9798
98 def test_break_lock_format_5_bzrdir(self):99 def test_break_lock_format_5_bzrdir(self):
99 # break lock on a format 5 bzrdir should just return100 # break lock on a format 5 bzrdir should just return
100 self.make_branch_and_tree('foo', format=bzrlib.bzrdir.BzrDirFormat5())101 self.make_branch_and_tree('foo', format=bzrdir.BzrDirFormat5())
101 out, err = self.run_bzr('break-lock foo')102 out, err = self.run_bzr('break-lock foo')
102 self.assertEqual('', out)103 self.assertEqual('', out)
103 self.assertEqual('', err)104 self.assertEqual('', err)
105
106
107class TestConfigBreakLock(tests.TestCaseWithTransport):
108
109 def create_pending_lock(self):
110 def config_file_name():
111 return './my.conf'
112 self.build_tree_contents([(config_file_name(), '[DEFAULT]\none=1\n')])
113 conf = config.LockableConfig(config_file_name)
114 conf.lock_write()
115 return conf
116
117 def test_create_pending_lock(self):
118 conf = self.create_pending_lock()
119 self.addCleanup(conf.unlock)
120 self.assertTrue(conf._lock.is_held)
121
122 def test_break_lock(self):
123 conf = self.create_pending_lock()
124 self.run_bzr('break-lock --config %s'
125 % osutils.dirname(conf._get_filename()),
126 stdin="y\n")
127 self.assertRaises(errors.LockBroken, conf.unlock)
104128
=== modified file 'bzrlib/tests/test_commands.py'
--- bzrlib/tests/test_commands.py 2010-05-27 21:16:48 +0000
+++ bzrlib/tests/test_commands.py 2010-07-14 08:34:44 +0000
@@ -97,7 +97,7 @@
97 def _get_config(self, config_text):97 def _get_config(self, config_text):
98 my_config = config.GlobalConfig()98 my_config = config.GlobalConfig()
99 config_file = StringIO(config_text.encode('utf-8'))99 config_file = StringIO(config_text.encode('utf-8'))
100 my_config._parser = my_config._get_parser(file=config_file)100 my_config._parser = my_config._get_parser(infile=config_file)
101 return my_config101 return my_config
102102
103 def test_simple(self):103 def test_simple(self):
104104
=== modified file 'bzrlib/tests/test_config.py'
--- bzrlib/tests/test_config.py 2010-04-23 07:15:23 +0000
+++ bzrlib/tests/test_config.py 2010-07-14 08:34:44 +0000
@@ -19,6 +19,7 @@
19from cStringIO import StringIO19from cStringIO import StringIO
20import os20import os
21import sys21import sys
22import threading
2223
23#import bzrlib specific imports here24#import bzrlib specific imports here
24from bzrlib import (25from bzrlib import (
@@ -38,6 +39,32 @@
38from bzrlib.util.configobj import configobj39from bzrlib.util.configobj import configobj
3940
4041
42def lockable_config_scenarios():
43 return [
44 ('global',
45 {'config_file_name': config.config_filename,
46 'config_class': config.GlobalConfig,
47 'config_args': [],
48 'config_section': 'DEFAULT'}),
49 ('locations',
50 {'config_file_name': config.locations_config_filename,
51 'config_class': config.LocationConfig,
52 'config_args': ['.'],
53 'config_section': '.'}),]
54
55
56def load_tests(standard_tests, module, loader):
57 suite = loader.suiteClass()
58
59 lc_tests, remaining_tests = tests.split_suite_by_condition(
60 standard_tests, tests.condition_isinstance((
61 TestLockableConfig,
62 )))
63 tests.multiply_tests(lc_tests, lockable_config_scenarios(), suite)
64 suite.addTest(remaining_tests)
65 return suite
66
67
41sample_long_alias="log -r-15..-1 --line"68sample_long_alias="log -r-15..-1 --line"
42sample_config_text = u"""69sample_config_text = u"""
43[DEFAULT]70[DEFAULT]
@@ -129,6 +156,9 @@
129 self._calls.append(('keys',))156 self._calls.append(('keys',))
130 return []157 return []
131158
159 def reload(self):
160 self._calls.append(('reload',))
161
132 def write(self, arg):162 def write(self, arg):
133 self._calls.append(('write',))163 self._calls.append(('write',))
134164
@@ -371,7 +401,7 @@
371401
372 def make_config_parser(self, s):402 def make_config_parser(self, s):
373 conf = config.IniBasedConfig(None)403 conf = config.IniBasedConfig(None)
374 parser = conf._get_parser(file=StringIO(s.encode('utf-8')))404 parser = conf._get_parser(infile=StringIO(s.encode('utf-8')))
375 return conf, parser405 return conf, parser
376406
377407
@@ -384,16 +414,144 @@
384 config_file = StringIO(sample_config_text.encode('utf-8'))414 config_file = StringIO(sample_config_text.encode('utf-8'))
385 my_config = config.IniBasedConfig(None)415 my_config = config.IniBasedConfig(None)
386 self.failUnless(416 self.failUnless(
387 isinstance(my_config._get_parser(file=config_file),417 isinstance(my_config._get_parser(infile=config_file),
388 configobj.ConfigObj))418 configobj.ConfigObj))
389419
390 def test_cached(self):420 def test_cached(self):
391 config_file = StringIO(sample_config_text.encode('utf-8'))421 config_file = StringIO(sample_config_text.encode('utf-8'))
392 my_config = config.IniBasedConfig(None)422 my_config = config.IniBasedConfig(None)
393 parser = my_config._get_parser(file=config_file)423 parser = my_config._get_parser(infile=config_file)
394 self.failUnless(my_config._get_parser() is parser)424 self.failUnless(my_config._get_parser() is parser)
395425
396426
427class TestLockableConfig(tests.TestCaseInTempDir):
428
429 # Set by load_tests
430 config_file_name = None
431 config_class = None
432 config_args = None
433 config_section = None
434
435 def setUp(self):
436 super(TestLockableConfig, self).setUp()
437 config.ensure_config_dir_exists()
438 text = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
439 self.build_tree_contents([(self.config_file_name(), text)])
440
441 def create_config(self):
442 return self.config_class(*self.config_args)
443
444 def test_simple_read_access(self):
445 c = self.create_config()
446 self.assertEquals('1', c.get_user_option('one'))
447
448 def test_simple_write_access(self):
449 c = self.create_config()
450 c.set_user_option('one', 'one')
451 self.assertEquals('one', c.get_user_option('one'))
452
453 def test_unlocked_config(self):
454 c = self.create_config()
455 self.assertRaises(errors.ObjectNotLocked, c._write_config_file)
456
457 def test_listen_to_the_last_speaker(self):
458 c1 = self.create_config()
459 c2 = self.create_config()
460 c1.set_user_option('one', 'ONE')
461 c2.set_user_option('two', 'TWO')
462 self.assertEquals('ONE', c1.get_user_option('one'))
463 self.assertEquals('TWO', c2.get_user_option('two'))
464 # The second update respect the first one
465 self.assertEquals('ONE', c2.get_user_option('one'))
466
467 def test_last_speaker_wins(self):
468 # If the same config is not shared, the same variable modified twice
469 # can only see a single result.
470 c1 = self.create_config()
471 c2 = self.create_config()
472 c1.set_user_option('one', 'c1')
473 c2.set_user_option('one', 'c2')
474 self.assertEquals('c2', c2.get_user_option('one'))
475 # The first modification is still available until another refresh
476 # occur
477 self.assertEquals('c1', c1.get_user_option('one'))
478 c1.set_user_option('two', 'done')
479 self.assertEquals('c2', c1.get_user_option('one'))
480
481 def test_writes_are_serialized(self):
482 c1 = self.create_config()
483 c2 = self.create_config()
484
485 # We spawn a thread that will pause *during* the write
486 before_writing = threading.Event()
487 after_writing = threading.Event()
488 writing_done = threading.Event()
489 c1_orig = c1._write_config_file
490 def c1_write_config_file():
491 before_writing.set()
492 c1_orig()
493 # The lock is held we wait for the main thread to decide when to
494 # continue
495 after_writing.wait()
496 c1._write_config_file = c1_write_config_file
497 def c1_set_option():
498 c1.set_user_option('one', 'c1')
499 writing_done.set()
500 t1 = threading.Thread(target=c1_set_option)
501 # Collect the thread after the test
502 self.addCleanup(t1.join)
503 # Be ready to unblock the thread if the test goes wrong
504 self.addCleanup(after_writing.set)
505 t1.start()
506 before_writing.wait()
507 self.assertTrue(c1._lock.is_held)
508 self.assertRaises(errors.LockContention,
509 c2.set_user_option, 'one', 'c2')
510 self.assertEquals('c1', c1.get_user_option('one'))
511 # Let the lock be released
512 after_writing.set()
513 writing_done.wait()
514 c2.set_user_option('one', 'c2')
515 self.assertEquals('c2', c2.get_user_option('one'))
516
517 def test_read_while_writing(self):
518 c1 = self.create_config()
519 # We spawn a thread that will pause *during* the write
520 ready_to_write = threading.Event()
521 do_writing = threading.Event()
522 writing_done = threading.Event()
523 c1_orig = c1._write_config_file
524 def c1_write_config_file():
525 ready_to_write.set()
526 # The lock is held we wait for the main thread to decide when to
527 # continue
528 do_writing.wait()
529 c1_orig()
530 writing_done.set()
531 c1._write_config_file = c1_write_config_file
532 def c1_set_option():
533 c1.set_user_option('one', 'c1')
534 t1 = threading.Thread(target=c1_set_option)
535 # Collect the thread after the test
536 self.addCleanup(t1.join)
537 # Be ready to unblock the thread if the test goes wrong
538 self.addCleanup(do_writing.set)
539 t1.start()
540 # Ensure the thread is ready to write
541 ready_to_write.wait()
542 self.assertTrue(c1._lock.is_held)
543 self.assertEquals('c1', c1.get_user_option('one'))
544 # If we read during the write, we get the old value
545 c2 = self.create_config()
546 self.assertEquals('1', c2.get_user_option('one'))
547 # Let the writing occur and ensure it occurred
548 do_writing.set()
549 writing_done.wait()
550 # Now we get the updated value
551 c3 = self.create_config()
552 self.assertEquals('c1', c3.get_user_option('one'))
553
554
397class TestGetUserOptionAs(TestIniConfig):555class TestGetUserOptionAs(TestIniConfig):
398556
399 def test_get_user_option_as_bool(self):557 def test_get_user_option_as_bool(self):
@@ -583,26 +741,26 @@
583 def test_user_id(self):741 def test_user_id(self):
584 config_file = StringIO(sample_config_text.encode('utf-8'))742 config_file = StringIO(sample_config_text.encode('utf-8'))
585 my_config = config.GlobalConfig()743 my_config = config.GlobalConfig()
586 my_config._parser = my_config._get_parser(file=config_file)744 my_config._parser = my_config._get_parser(infile=config_file)
587 self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",745 self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
588 my_config._get_user_id())746 my_config._get_user_id())
589747
590 def test_absent_user_id(self):748 def test_absent_user_id(self):
591 config_file = StringIO("")749 config_file = StringIO("")
592 my_config = config.GlobalConfig()750 my_config = config.GlobalConfig()
593 my_config._parser = my_config._get_parser(file=config_file)751 my_config._parser = my_config._get_parser(infile=config_file)
594 self.assertEqual(None, my_config._get_user_id())752 self.assertEqual(None, my_config._get_user_id())
595753
596 def test_configured_editor(self):754 def test_configured_editor(self):
597 config_file = StringIO(sample_config_text.encode('utf-8'))755 config_file = StringIO(sample_config_text.encode('utf-8'))
598 my_config = config.GlobalConfig()756 my_config = config.GlobalConfig()
599 my_config._parser = my_config._get_parser(file=config_file)757 my_config._parser = my_config._get_parser(infile=config_file)
600 self.assertEqual("vim", my_config.get_editor())758 self.assertEqual("vim", my_config.get_editor())
601759
602 def test_signatures_always(self):760 def test_signatures_always(self):
603 config_file = StringIO(sample_always_signatures)761 config_file = StringIO(sample_always_signatures)
604 my_config = config.GlobalConfig()762 my_config = config.GlobalConfig()
605 my_config._parser = my_config._get_parser(file=config_file)763 my_config._parser = my_config._get_parser(infile=config_file)
606 self.assertEqual(config.CHECK_NEVER,764 self.assertEqual(config.CHECK_NEVER,
607 my_config.signature_checking())765 my_config.signature_checking())
608 self.assertEqual(config.SIGN_ALWAYS,766 self.assertEqual(config.SIGN_ALWAYS,
@@ -612,7 +770,7 @@
612 def test_signatures_if_possible(self):770 def test_signatures_if_possible(self):
613 config_file = StringIO(sample_maybe_signatures)771 config_file = StringIO(sample_maybe_signatures)
614 my_config = config.GlobalConfig()772 my_config = config.GlobalConfig()
615 my_config._parser = my_config._get_parser(file=config_file)773 my_config._parser = my_config._get_parser(infile=config_file)
616 self.assertEqual(config.CHECK_NEVER,774 self.assertEqual(config.CHECK_NEVER,
617 my_config.signature_checking())775 my_config.signature_checking())
618 self.assertEqual(config.SIGN_WHEN_REQUIRED,776 self.assertEqual(config.SIGN_WHEN_REQUIRED,
@@ -622,7 +780,7 @@
622 def test_signatures_ignore(self):780 def test_signatures_ignore(self):
623 config_file = StringIO(sample_ignore_signatures)781 config_file = StringIO(sample_ignore_signatures)
624 my_config = config.GlobalConfig()782 my_config = config.GlobalConfig()
625 my_config._parser = my_config._get_parser(file=config_file)783 my_config._parser = my_config._get_parser(infile=config_file)
626 self.assertEqual(config.CHECK_ALWAYS,784 self.assertEqual(config.CHECK_ALWAYS,
627 my_config.signature_checking())785 my_config.signature_checking())
628 self.assertEqual(config.SIGN_NEVER,786 self.assertEqual(config.SIGN_NEVER,
@@ -632,7 +790,7 @@
632 def _get_sample_config(self):790 def _get_sample_config(self):
633 config_file = StringIO(sample_config_text.encode('utf-8'))791 config_file = StringIO(sample_config_text.encode('utf-8'))
634 my_config = config.GlobalConfig()792 my_config = config.GlobalConfig()
635 my_config._parser = my_config._get_parser(file=config_file)793 my_config._parser = my_config._get_parser(infile=config_file)
636 return my_config794 return my_config
637795
638 def test_gpg_signing_command(self):796 def test_gpg_signing_command(self):
@@ -643,7 +801,7 @@
643 def _get_empty_config(self):801 def _get_empty_config(self):
644 config_file = StringIO("")802 config_file = StringIO("")
645 my_config = config.GlobalConfig()803 my_config = config.GlobalConfig()
646 my_config._parser = my_config._get_parser(file=config_file)804 my_config._parser = my_config._get_parser(infile=config_file)
647 return my_config805 return my_config
648806
649 def test_gpg_signing_command_unset(self):807 def test_gpg_signing_command_unset(self):
@@ -745,10 +903,11 @@
745 [('__init__', config.locations_config_filename(),903 [('__init__', config.locations_config_filename(),
746 'utf-8')])904 'utf-8')])
747 config.ensure_config_dir_exists()905 config.ensure_config_dir_exists()
748 #os.mkdir(config.config_dir())
749 f = file(config.branches_config_filename(), 'wb')906 f = file(config.branches_config_filename(), 'wb')
750 f.write('')907 try:
751 f.close()908 f.write('')
909 finally:
910 f.close()
752 oldparserclass = config.ConfigObj911 oldparserclass = config.ConfigObj
753 config.ConfigObj = InstrumentedConfigObj912 config.ConfigObj = InstrumentedConfigObj
754 try:913 try:
@@ -995,10 +1154,15 @@
995 else:1154 else:
996 global_file = StringIO(global_config.encode('utf-8'))1155 global_file = StringIO(global_config.encode('utf-8'))
997 branches_file = StringIO(sample_branches_text.encode('utf-8'))1156 branches_file = StringIO(sample_branches_text.encode('utf-8'))
1157 # Make sure the locations config can be reloaded
1158 config.ensure_config_dir_exists()
1159 f = file(config.locations_config_filename(), 'wb')
1160 try:
1161 f.write(branches_file.getvalue())
1162 finally:
1163 f.close
998 self.my_config = config.BranchConfig(FakeBranch(location))1164 self.my_config = config.BranchConfig(FakeBranch(location))
999 # Force location config to use specified file
1000 self.my_location_config = self.my_config._get_location_config()1165 self.my_location_config = self.my_config._get_location_config()
1001 self.my_location_config._get_parser(branches_file)
1002 # Force global config to use specified file1166 # Force global config to use specified file
1003 self.my_config._get_global_config()._get_parser(global_file)1167 self.my_config._get_global_config()._get_parser(global_file)
10041168
@@ -1007,25 +1171,14 @@
1007 record = InstrumentedConfigObj("foo")1171 record = InstrumentedConfigObj("foo")
1008 self.my_location_config._parser = record1172 self.my_location_config._parser = record
10091173
1010 real_mkdir = os.mkdir1174 self.callDeprecated(['The recurse option is deprecated as of '
1011 self.created = False1175 '0.14. The section "/a/c" has been '
1012 def checked_mkdir(path, mode=0777):1176 'converted to use policies.'],
1013 self.log('making directory: %s', path)1177 self.my_config.set_user_option,
1014 real_mkdir(path, mode)1178 'foo', 'bar', store=config.STORE_LOCATION)
1015 self.created = True1179
10161180 self.assertEqual([('reload',),
1017 os.mkdir = checked_mkdir1181 ('__contains__', '/a/c'),
1018 try:
1019 self.callDeprecated(['The recurse option is deprecated as of '
1020 '0.14. The section "/a/c" has been '
1021 'converted to use policies.'],
1022 self.my_config.set_user_option,
1023 'foo', 'bar', store=config.STORE_LOCATION)
1024 finally:
1025 os.mkdir = real_mkdir
1026
1027 self.failUnless(self.created, 'Failed to create ~/.bazaar')
1028 self.assertEqual([('__contains__', '/a/c'),
1029 ('__contains__', '/a/c/'),1182 ('__contains__', '/a/c/'),
1030 ('__setitem__', '/a/c', {}),1183 ('__setitem__', '/a/c', {}),
1031 ('__getitem__', '/a/c'),1184 ('__getitem__', '/a/c'),
@@ -1083,10 +1236,13 @@
1083 if global_config is not None:1236 if global_config is not None:
1084 global_file = StringIO(global_config.encode('utf-8'))1237 global_file = StringIO(global_config.encode('utf-8'))
1085 my_config._get_global_config()._get_parser(global_file)1238 my_config._get_global_config()._get_parser(global_file)
1086 self.my_location_config = my_config._get_location_config()1239 lconf = my_config._get_location_config()
1087 if location_config is not None:1240 if location_config is not None:
1088 location_file = StringIO(location_config.encode('utf-8'))1241 location_file = StringIO(location_config.encode('utf-8'))
1089 self.my_location_config._get_parser(location_file)1242 lconf._get_parser(location_file)
1243 # Make sure the config can be reloaded
1244 lconf._parser.filename = config.locations_config_filename()
1245 self.my_location_config = lconf
1090 if branch_data_config is not None:1246 if branch_data_config is not None:
1091 my_config.branch.control_files.files['branch.conf'] = \1247 my_config.branch.control_files.files['branch.conf'] = \
1092 branch_data_config1248 branch_data_config