Ubuntu Pastebin

Paste from cjwatson at Tue, 23 Feb 2016 17:26:24 +0000

Download as text
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
=== modified file '.bzrignore'
--- .bzrignore	2013-02-21 00:39:32 +0000
+++ .bzrignore	2016-02-23 17:16:12 +0000
@@ -13,7 +13,7 @@
 ./ubuntu-archive-tools
 ./www
 __pycache__
+etc/.build-image-set-pids
 etc/.lock*
 etc/.next-build-suffix*
-etc/.sem-build-image-set
 etc/task-mail

=== added file 'bin/multipidfile'
--- bin/multipidfile	1970-01-01 00:00:00 +0000
+++ bin/multipidfile	2016-02-23 17:18:51 +0000
@@ -0,0 +1,68 @@
+#! /usr/bin/python
+
+# Copyright (C) 2013, 2016 Canonical Ltd.
+# Author: Colin Watson <cjwatson@ubuntu.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
+# the Free Software Foundation; version 3 of the License.
+#
+# 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/>.
+
+"""PID files containing multiple PIDs.
+
+This implements two operations, namely test-add (test non-empty, add PID,
+return state of test) and remove-test (remove PID, test non-empty, return
+state of test), which are sufficient for use as a shared lock which only
+opens when all users have unlocked.  Dead processes are automatically
+ignored and removed.  It is an error to call test-add with a PID that is
+already in the file, or remove-test with a PID that is not already in the
+file.
+
+The state is returned on stdout; a non-zero exit status indicates an error.
+"""
+
+from __future__ import print_function
+
+from optparse import OptionParser
+import os
+import sys
+
+sys.path.insert(0, os.path.join(sys.path[0], os.pardir, "lib"))
+
+
+def main():
+    from cdimage.multipidfile import MultiPIDFile, MultiPIDFileError
+
+    parser = OptionParser("%prog FILE test-add|remove-test PID")
+    _, args = parser.parse_args()
+    if len(args) < 1:
+        parser.error("need file name")
+    if len(args) < 2:
+        parser.error("need operation")
+    if len(args) < 3:
+        parser.error("need PID")
+    path, mode, pid = args[:3]
+    multipidfile = MultiPIDFile(path)
+    try:
+        if mode == "test-add":
+            for pid in sorted(multipidfile.test_add(int(pid))):
+                print(pid)
+        elif mode == "remove-test":
+            for pid in sorted(multipidfile.remove_test(int(pid))):
+                print(pid)
+        else:
+            parser.error("unknown multipidfile operation '%s'" % mode)
+    except MultiPIDFileError as e:
+        print(e, file=sys.stderr)
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    main()

=== removed file 'bin/semaphore'
--- bin/semaphore	2015-10-26 11:06:11 +0000
+++ bin/semaphore	1970-01-01 00:00:00 +0000
@@ -1,63 +0,0 @@
-#! /usr/bin/python
-
-# Copyright (C) 2013 Canonical Ltd.
-# Author: Colin Watson <cjwatson@ubuntu.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
-# the Free Software Foundation; version 3 of the License.
-#
-# 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/>.
-
-"""Atomic counting semaphore files.
-
-This implements two operations, namely test-increment (test non-zero,
-increment, return state of test) and decrement-test (decrement, test
-non-zero, return state of test), which are sufficient for use as a shared
-lock which only opens when all users have unlocked.  It is an error to call
-decrement-test on a semaphore that is already zero.
-
-The semaphore state is returned on stdout to allow the exit status to be
-used to report errors.
-"""
-
-from __future__ import print_function
-
-from optparse import OptionParser
-import os
-import sys
-
-sys.path.insert(0, os.path.join(sys.path[0], os.pardir, "lib"))
-
-
-def main():
-    from cdimage.semaphore import Semaphore, SemaphoreError
-
-    parser = OptionParser("%prog test-increment|decrement-test SEMAPHORE")
-    _, args = parser.parse_args()
-    if len(args) < 1:
-        parser.error("need operation")
-    if len(args) < 2:
-        parser.error("need semaphore file name")
-    mode, path = args[:2]
-    semaphore = Semaphore(path)
-    try:
-        if mode == "test-increment":
-            print(semaphore.test_increment())
-        elif mode == "decrement-test":
-            print(semaphore.decrement_test())
-        else:
-            parser.error("unknown semaphore operation '%s'" % mode)
-    except SemaphoreError as e:
-        print(e, file=sys.stderr)
-        sys.exit(1)
-
-
-if __name__ == "__main__":
-    main()

=== modified file 'lib/cdimage/build.py'
--- lib/cdimage/build.py	2015-12-09 12:31:46 +0000
+++ lib/cdimage/build.py	2016-02-23 17:10:32 +0000
@@ -42,7 +42,7 @@ from cdimage.livefs import (
 from cdimage.log import logger, reset_logging
 from cdimage.mail import get_notify_addresses, send_mail
 from cdimage.mirror import find_mirror, trigger_mirrors
-from cdimage.semaphore import Semaphore
+from cdimage.multipidfile import MultiPIDFile
 from cdimage.tracker import tracker_set_rebuild_status
 from cdimage.tree import Publisher, Tree
 from cdimage.config import Touch
@@ -239,13 +239,13 @@ def anonftpsync(config):
         osextras.unlink_force(lock)
 
 
-def sync_local_mirror(config, semaphore_state):
+def sync_local_mirror(config, multipidfile_state):
     if config["CDIMAGE_NOSYNC"]:
         return
 
     capproject = config.capproject
     sync_lock = os.path.join(config.root, "etc", ".lock-archive-sync")
-    if semaphore_state == 0:
+    if not multipidfile_state:
         log_marker("Syncing %s mirror" % capproject)
         # Acquire lock to allow parallel builds to ensure a consistent
         # archive.
@@ -671,7 +671,7 @@ def is_live_fs_only(config):
     return live_fs_only
 
 
-def build_image_set_locked(config, options, semaphore_state):
+def build_image_set_locked(config, options, multipidfile_state):
     image_type = config.image_type
     config["CDIMAGE_DATE"] = date = next_build_id(config, image_type)
     log_path = None
@@ -688,7 +688,7 @@ def build_image_set_locked(config, optio
             tracker_set_rebuild_status(config, [0, 1], 2)
 
         if not is_live_fs_only(config):
-            sync_local_mirror(config, semaphore_state)
+            sync_local_mirror(config, multipidfile_state)
 
             if config["LOCAL"]:
                 log_marker("Updating archive of local packages")
@@ -792,7 +792,9 @@ def handle_signals():
 def build_image_set(config, options):
     """Master entry point for building images."""
     with handle_signals():
-        semaphore = Semaphore(
-            os.path.join(config.root, "etc", ".sem-build-image-set"))
-        with lock_build_image_set(config), semaphore.held() as semaphore_state:
-            return build_image_set_locked(config, options, semaphore_state)
+        multipidfile = MultiPIDFile(
+            os.path.join(config.root, "etc", ".build-image-set-pids"))
+        with lock_build_image_set(config):
+            with multipidfile.held(os.getpid()) as multipidfile_state:
+                return build_image_set_locked(
+                    config, options, multipidfile_state)

=== added file 'lib/cdimage/multipidfile.py'
--- lib/cdimage/multipidfile.py	1970-01-01 00:00:00 +0000
+++ lib/cdimage/multipidfile.py	2016-02-23 16:45:18 +0000
@@ -0,0 +1,119 @@
+# Copyright (C) 2013, 2016 Canonical Ltd.
+# Author: Colin Watson <cjwatson@ubuntu.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
+# the Free Software Foundation; version 3 of the License.
+#
+# 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/>.
+
+"""PID files containing multiple PIDs."""
+
+from __future__ import print_function
+
+import contextlib
+import errno
+import os
+import subprocess
+
+from cdimage import osextras
+
+__metaclass__ = type
+
+
+class MultiPIDFileError(Exception):
+    pass
+
+
+class MultiPIDFile:
+    """A file tracking multiple PIDs."""
+
+    def __init__(self, path):
+        self.path = path
+        self.lock_path = "%s.lock" % path
+
+    def __str__(self):
+        return "multipidfile %s" % self.path
+
+    def __enter__(self):
+        command = ["lockfile", "-r", "4", self.lock_path]
+        if subprocess.call(command) != 0:
+            raise MultiPIDFileError("Cannot acquire lock on %s!" % self)
+
+    def __exit__(self, unused_exc_type, unused_exc_value, unused_exc_tb):
+        osextras.unlink_force(self.lock_path)
+
+    def _read(self):
+        # Must be called within context manager lock.
+        assert os.path.exists(self.lock_path), (
+            "Called _read on %s without locking!" % self)
+        try:
+            with open(self.path) as fd:
+                pids = set(int(line) for line in fd)
+                return set(pid for pid in pids if osextras.pid_exists(pid))
+        except IOError as e:
+            if e.errno == errno.ENOENT:
+                return set()
+            raise
+
+    def _write(self, pids):
+        # Must be called within context manager lock.
+        assert os.path.exists(self.lock_path), (
+            "Called _write on %s without locking!" % self)
+        if pids:
+            with open(self.path, "w") as fd:
+                for pid in sorted(pids):
+                    print(pid, file=fd)
+        else:
+            osextras.unlink_force(self.path)
+
+    @property
+    def state(self):
+        """Return current set of tracked PIDs."""
+        with self:
+            return self._read()
+
+    def test_add(self, pid):
+        """Test, add PID, return state of test.
+
+        It is an error to add a PID that is already present.
+        """
+        with self:
+            pids = self._read()
+            if pid in pids:
+                raise MultiPIDFileError(
+                    "Attempted to add PID %d to %s which was already "
+                    "present!" % (pid, self))
+            state = set(pids)
+            pids.add(pid)
+            self._write(pids)
+            return state
+
+    def remove_test(self, pid):
+        """Remove PID, test, return state of test.
+
+        It is an error to remove a PID that is not already present.
+        """
+        with self:
+            pids = self._read()
+            try:
+                pids.remove(pid)
+            except KeyError:
+                raise MultiPIDFileError(
+                    "Attempted to remove PID %d from %s which was not "
+                    "present!" % (pid, self))
+            self._write(pids)
+            return pids
+
+    @contextlib.contextmanager
+    def held(self, pid):
+        try:
+            yield self.test_add(pid)
+        finally:
+            self.remove_test(pid)

=== modified file 'lib/cdimage/osextras.py'
--- lib/cdimage/osextras.py	2014-05-28 09:18:44 +0000
+++ lib/cdimage/osextras.py	2016-02-23 16:09:21 +0000
@@ -200,3 +200,13 @@ def read_shell_config(config_path=None,
     env = _read_nullsep_output(["sh", "-c", "; ".join(commands)])
     for key, value in env.items():
         yield key, value
+
+
+def pid_exists(pid):
+    try:
+        os.kill(pid, 0)
+        return True
+    except OSError as e:
+        if e.errno == errno.ESRCH:
+            return False
+        raise

=== removed file 'lib/cdimage/semaphore.py'
--- lib/cdimage/semaphore.py	2015-10-26 11:06:11 +0000
+++ lib/cdimage/semaphore.py	1970-01-01 00:00:00 +0000
@@ -1,108 +0,0 @@
-# Copyright (C) 2013 Canonical Ltd.
-# Author: Colin Watson <cjwatson@ubuntu.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
-# the Free Software Foundation; version 3 of the License.
-#
-# 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/>.
-
-"""Atomic counting semaphore files."""
-
-from __future__ import print_function
-
-import contextlib
-import errno
-import os
-import subprocess
-
-from cdimage import osextras
-
-__metaclass__ = type
-
-
-class SemaphoreError(Exception):
-    pass
-
-
-class Semaphore:
-    """A shared lock which only opens when all users have unlocked."""
-
-    def __init__(self, path):
-        self.path = path
-        self.lock_path = "%s.lock" % path
-
-    def __str__(self):
-        return "semaphore %s" % self.path
-
-    def __enter__(self):
-        command = ["lockfile", "-r", "4", self.lock_path]
-        if subprocess.call(command) != 0:
-            raise SemaphoreError("Cannot acquire lock on %s!" % self)
-
-    def __exit__(self, unused_exc_type, unused_exc_value, unused_exc_tb):
-        osextras.unlink_force(self.lock_path)
-
-    def _read(self):
-        # Must be called within context manager lock.
-        assert os.path.exists(self.lock_path), (
-            "Called _read on %s without locking!" % self)
-        try:
-            with open(self.path) as fd:
-                return int(fd.read())
-        except IOError as e:
-            if e.errno == errno.ENOENT:
-                return 0
-            raise
-
-    def _add(self, offset):
-        # Must be called within context manager lock.
-        assert os.path.exists(self.lock_path), (
-            "Called _add on %s without locking!" % self)
-        cur = self._read()
-        with open(self.path, "w") as fd:
-            print(cur + offset, file=fd)
-        return cur + offset
-
-    @property
-    def state(self):
-        """Return current state of semaphore."""
-        with self:
-            return self._read()
-
-    def test_increment(self):
-        """Test, increment, return state of test."""
-        with self:
-            state = self._read()
-            self._add(1)
-            return state
-
-    def decrement_test(self):
-        """Decrement, test, return state of test.
-
-        It is an error to call decrement-test on a semaphore that is already
-        zero.
-        """
-        with self:
-            state = self._read()
-            if state == 0:
-                osextras.unlink_force(self.path)
-                raise SemaphoreError(
-                    "Attempted to decrement %s when already zero!" % self)
-            state = self._add(-1)
-            if state == 0:
-                osextras.unlink_force(self.path)
-            return state
-
-    @contextlib.contextmanager
-    def held(self):
-        try:
-            yield self.test_increment()
-        finally:
-            self.decrement_test()

=== modified file 'lib/cdimage/tests/test_build.py'
--- lib/cdimage/tests/test_build.py	2015-12-09 12:31:46 +0000
+++ lib/cdimage/tests/test_build.py	2016-02-23 17:09:39 +0000
@@ -1204,13 +1204,13 @@ class TestBuildImageSet(TestCase):
         self.config["IMAGE_TYPE"] = "daily"
         lock_path = os.path.join(
             self.temp_dir, "etc", ".lock-build-image-set-ubuntu-raring-daily")
-        semaphore_path = os.path.join(
-            self.temp_dir, "etc", ".sem-build-image-set")
+        multipidfile_path = os.path.join(
+            self.temp_dir, "etc", ".build-image-set-pids")
         os.makedirs(os.path.dirname(lock_path))
         self.assertRaises(
             KeyboardInterrupt, build_image_set, self.config, None)
         self.assertFalse(os.path.exists(lock_path))
-        self.assertFalse(os.path.exists(semaphore_path))
+        self.assertFalse(os.path.exists(multipidfile_path))
 
     @mock.patch("cdimage.build.build_image_set_locked")
     def test_build_image_set_terminated(self, mock_build_image_set_locked):
@@ -1219,11 +1219,11 @@ class TestBuildImageSet(TestCase):
         self.config["IMAGE_TYPE"] = "daily"
         lock_path = os.path.join(
             self.temp_dir, "etc", ".lock-build-image-set-ubuntu-raring-daily")
-        semaphore_path = os.path.join(
-            self.temp_dir, "etc", ".sem-build-image-set")
+        multipidfile_path = os.path.join(
+            self.temp_dir, "etc", ".build-image-set-pids")
         os.makedirs(os.path.dirname(lock_path))
 
-        def side_effect(config, options, semaphore_state):
+        def side_effect(config, options, multipidfile_state):
             os.kill(os.getpid(), signal.SIGTERM)
 
         mock_build_image_set_locked.side_effect = side_effect
@@ -1233,7 +1233,7 @@ class TestBuildImageSet(TestCase):
             os._exit(1)
         else:  # parent
             self.wait_for_pid(pid, signal.SIGTERM)
-            self.assertFalse(os.path.exists(semaphore_path))
+            self.assertFalse(os.path.exists(multipidfile_path))
 
     @mock.patch("cdimage.build.build_image_set_locked")
     def test_build_image_set(self, mock_build_image_set_locked):
@@ -1242,16 +1242,16 @@ class TestBuildImageSet(TestCase):
         self.config["IMAGE_TYPE"] = "daily"
         lock_path = os.path.join(
             self.temp_dir, "etc", ".lock-build-image-set-ubuntu-raring-daily")
-        semaphore_path = os.path.join(
-            self.temp_dir, "etc", ".sem-build-image-set")
+        multipidfile_path = os.path.join(
+            self.temp_dir, "etc", ".build-image-set-pids")
         os.makedirs(os.path.dirname(lock_path))
 
-        def side_effect(config, options, semaphore_state):
+        def side_effect(config, options, multipidfile_state):
             self.assertTrue(os.path.exists(lock_path))
             self.assertIsNone(options)
-            self.assertEqual(0, semaphore_state)
-            with open(semaphore_path) as semaphore:
-                self.assertEqual("1\n", semaphore.read())
+            self.assertEqual(set(), multipidfile_state)
+            with open(multipidfile_path) as multipidfile:
+                self.assertEqual("%d\n" % os.getpid(), multipidfile.read())
 
         mock_build_image_set_locked.side_effect = side_effect
         build_image_set(self.config, None)

=== added file 'lib/cdimage/tests/test_multipidfile.py'
--- lib/cdimage/tests/test_multipidfile.py	1970-01-01 00:00:00 +0000
+++ lib/cdimage/tests/test_multipidfile.py	2016-02-23 16:51:40 +0000
@@ -0,0 +1,160 @@
+#! /usr/bin/python
+
+# Copyright (C) 2013, 2016 Canonical Ltd.
+# Author: Colin Watson <cjwatson@ubuntu.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
+# the Free Software Foundation; version 3 of the License.
+#
+# 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/>.
+
+"""Unit tests for cdimage.multipidfile."""
+
+from __future__ import print_function
+
+import os
+
+try:
+    from unittest import mock
+except ImportError:
+    import mock
+
+from cdimage.multipidfile import MultiPIDFile, MultiPIDFileError
+from cdimage.tests.helpers import TestCase, mkfile
+
+__metaclass__ = type
+
+
+class TestMultiPIDFile(TestCase):
+    def setUp(self):
+        super(TestMultiPIDFile, self).setUp()
+        self.use_temp_dir()
+        self.multipidfile = MultiPIDFile(os.path.join(self.temp_dir, "pids"))
+
+    def test_str(self):
+        """A MultiPIDFile stringifies to 'multipidfile PATH'."""
+        self.assertEqual(
+            "multipidfile %s" % self.multipidfile.path, str(self.multipidfile))
+
+    def test_context_manager(self):
+        """A MultiPIDFile operates as a context manager, with locking."""
+        self.assertFalse(os.path.exists(self.multipidfile.lock_path))
+        with self.multipidfile:
+            self.assertTrue(os.path.exists(self.multipidfile.lock_path))
+        self.assertFalse(os.path.exists(self.multipidfile.lock_path))
+
+    @mock.patch("subprocess.call", return_value=1)
+    def test_lock_failure(self, mock_call):
+        """__enter__ raises MultiPIDFileError if the lock is already held."""
+        self.assertRaises(MultiPIDFileError, self.multipidfile.__enter__)
+
+    def test_read_requires_lock(self):
+        """_read must be called within the lock."""
+        self.assertRaises(AssertionError, self.multipidfile._read)
+
+    def test_read_missing(self):
+        """A missing MultiPIDFile reads as empty."""
+        with self.multipidfile:
+            self.assertEqual(set(), self.multipidfile._read())
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_read_existing(self, mock_pid_exists):
+        """An existing MultiPIDFile reads as the set of PIDs it contains."""
+        with mkfile(self.multipidfile.path) as fd:
+            print(1, file=fd)
+            print(2, file=fd)
+        with self.multipidfile:
+            self.assertEqual(set([1, 2]), self.multipidfile._read())
+
+    @mock.patch("cdimage.osextras.pid_exists")
+    def test_read_skips_dead_pids(self, mock_pid_exists):
+        """Only live PIDs are returned."""
+        with mkfile(self.multipidfile.path) as fd:
+            print(1, file=fd)
+            print(2, file=fd)
+        mock_pid_exists.side_effect = lambda pid: pid == 2
+        with self.multipidfile:
+            self.assertEqual(set([2]), self.multipidfile._read())
+
+    def test_write_requires_lock(self):
+        """_write must be called within the lock."""
+        self.assertRaises(AssertionError, self.multipidfile._write, 1)
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_write_missing(self, mock_pid_exists):
+        """Writing to a missing MultiPIDFile works."""
+        with self.multipidfile:
+            self.multipidfile._write(set([1, 2]))
+            self.assertEqual(set([1, 2]), self.multipidfile._read())
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_write_existing(self, mock_pid_exists):
+        """Writing to an existing MultiPIDFile adjusts its contents."""
+        with mkfile(self.multipidfile.path) as fd:
+            print(1, file=fd)
+        with self.multipidfile:
+            self.multipidfile._write(set([1, 2]))
+            self.assertEqual(set([1, 2]), self.multipidfile._read())
+
+    def test_state(self):
+        """The state can be fetched without explicit locking."""
+        self.assertEqual(set(), self.multipidfile.state)
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_test_add(self, mock_pid_exists):
+        self.assertFalse(self.multipidfile.test_add(1))
+        self.assertEqual(set([1]), self.multipidfile.state)
+        self.assertTrue(self.multipidfile.test_add(2))
+        self.assertEqual(set([1, 2]), self.multipidfile.state)
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_test_add_error_on_existing_pid(self, mock_pid_exists):
+        with mkfile(self.multipidfile.path) as fd:
+            print(1, file=fd)
+        self.assertRaises(MultiPIDFileError, self.multipidfile.test_add, 1)
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_remove_test(self, mock_pid_exists):
+        with mkfile(self.multipidfile.path) as fd:
+            print(1, file=fd)
+            print(2, file=fd)
+        self.assertTrue(self.multipidfile.remove_test(2))
+        self.assertEqual(set([1]), self.multipidfile.state)
+        self.assertFalse(self.multipidfile.remove_test(1))
+        self.assertEqual(set(), self.multipidfile.state)
+
+    def test_remove_test_error_on_empty(self):
+        """remove_test raises MultiPIDFileError if already empty."""
+        self.assertRaises(MultiPIDFileError, self.multipidfile.remove_test, 1)
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_remove_test_error_on_missing_pid(self, mock_pid_exists):
+        with mkfile(self.multipidfile.path) as fd:
+            print(1, file=fd)
+        self.assertRaises(MultiPIDFileError, self.multipidfile.remove_test, 2)
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_round_trip(self, mock_pid_exists):
+        """After a +/- round-trip, the MultiPIDFile path is missing."""
+        self.assertFalse(self.multipidfile.test_add(1))
+        self.assertFalse(self.multipidfile.remove_test(1))
+        self.assertFalse(os.path.exists(self.multipidfile.path))
+
+    @mock.patch("cdimage.osextras.pid_exists", return_value=True)
+    def test_held(self, mock_pid_exists):
+        self.assertEqual(set(), self.multipidfile.state)
+        with self.multipidfile.held(1) as state_zero:
+            self.assertFalse(state_zero)
+            self.assertEqual(set([1]), self.multipidfile.state)
+            with self.multipidfile.held(2) as state_one:
+                self.assertTrue(state_one)
+                self.assertEqual(set([1, 2]), self.multipidfile.state)
+            self.assertEqual(set([1]), self.multipidfile.state)
+        self.assertEqual(set(), self.multipidfile.state)

=== modified file 'lib/cdimage/tests/test_osextras.py'
--- lib/cdimage/tests/test_osextras.py	2013-09-04 11:42:47 +0000
+++ lib/cdimage/tests/test_osextras.py	2016-02-23 17:04:07 +0000
@@ -225,3 +225,12 @@ class TestOSExtras(TestCase):
         self.assertEqual("one two three", config_dict["ONE"])
         self.assertEqual("two", config_dict["TWO"])
         self.assertNotIn("three", config_dict)
+
+    def test_pid_exists(self):
+        self.assertTrue(osextras.pid_exists(os.getpid()))
+        esrch = OSError(errno.ESRCH, "No such process")
+        with mock.patch("os.kill", side_effect=esrch):
+            self.assertFalse(osextras.pid_exists(os.getpid()))
+        enoent = OSError(errno.ENOENT, "No such file or directory")
+        with mock.patch("os.kill", side_effect=enoent):
+            self.assertRaises(OSError, osextras.pid_exists, os.getpid())

=== removed file 'lib/cdimage/tests/test_semaphore.py'
--- lib/cdimage/tests/test_semaphore.py	2015-10-26 11:06:11 +0000
+++ lib/cdimage/tests/test_semaphore.py	1970-01-01 00:00:00 +0000
@@ -1,129 +0,0 @@
-#! /usr/bin/python
-
-# Copyright (C) 2013 Canonical Ltd.
-# Author: Colin Watson <cjwatson@ubuntu.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
-# the Free Software Foundation; version 3 of the License.
-#
-# 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/>.
-
-"""Unit tests for cdimage.semaphore."""
-
-from __future__ import print_function
-
-import os
-
-try:
-    from unittest import mock
-except ImportError:
-    import mock
-
-from cdimage.semaphore import Semaphore, SemaphoreError
-from cdimage.tests.helpers import TestCase, mkfile
-
-__metaclass__ = type
-
-
-class TestSemaphore(TestCase):
-    def setUp(self):
-        super(TestSemaphore, self).setUp()
-        self.use_temp_dir()
-        self.semaphore = Semaphore(os.path.join(self.temp_dir, "sem"))
-
-    def test_str(self):
-        """A Semaphore stringifies to 'semaphore PATH'."""
-        self.assertEqual(
-            "semaphore %s" % self.semaphore.path, str(self.semaphore))
-
-    def test_context_manager(self):
-        """A Semaphore operates as a context manager, with locking."""
-        self.assertFalse(os.path.exists(self.semaphore.lock_path))
-        with self.semaphore:
-            self.assertTrue(os.path.exists(self.semaphore.lock_path))
-        self.assertFalse(os.path.exists(self.semaphore.lock_path))
-
-    @mock.patch("subprocess.call", return_value=1)
-    def test_lock_failure(self, mock_call):
-        """__enter__ raises SemaphoreError if the lock is already held."""
-        self.assertRaises(SemaphoreError, self.semaphore.__enter__)
-
-    def test_read_requires_lock(self):
-        """_read must be called within the lock."""
-        self.assertRaises(AssertionError, self.semaphore._read)
-
-    def test_read_missing(self):
-        """A missing semaphore file reads as zero."""
-        with self.semaphore:
-            self.assertEqual(0, self.semaphore._read())
-
-    def test_read_existing(self):
-        """An existing semaphore file reads as its integer value."""
-        with mkfile(self.semaphore.path) as fd:
-            print(10, file=fd)
-        with self.semaphore:
-            self.assertEqual(10, self.semaphore._read())
-
-    def test_add_requires_lock(self):
-        """_add must be called within the lock."""
-        self.assertRaises(AssertionError, self.semaphore._add, 1)
-
-    def test_add_missing(self):
-        """Adding to a missing semaphore file treats it as initially zero."""
-        with self.semaphore:
-            self.assertEqual(1, self.semaphore._add(1))
-            self.assertEqual(1, self.semaphore._read())
-
-    def test_add_existing(self):
-        """Adding to an existing semaphore file adjusts its contents."""
-        with mkfile(self.semaphore.path) as fd:
-            print(10, file=fd)
-        with self.semaphore:
-            self.assertEqual(9, self.semaphore._add(-1))
-            self.assertEqual(9, self.semaphore._read())
-
-    def test_state(self):
-        """The state can be fetched without explicit locking."""
-        self.assertEqual(0, self.semaphore.state)
-
-    def test_test_increment(self):
-        self.assertEqual(0, self.semaphore.test_increment())
-        self.assertEqual(1, self.semaphore.state)
-        self.assertEqual(1, self.semaphore.test_increment())
-        self.assertEqual(2, self.semaphore.state)
-
-    def test_decrement_test(self):
-        with mkfile(self.semaphore.path) as fd:
-            print(2, file=fd)
-        self.assertEqual(1, self.semaphore.decrement_test())
-        self.assertEqual(1, self.semaphore.state)
-        self.assertEqual(0, self.semaphore.decrement_test())
-        self.assertEqual(0, self.semaphore.state)
-
-    def test_decrement_test_error_on_zero(self):
-        """decrement_test raises SemaphoreError if already zero."""
-        self.assertRaises(SemaphoreError, self.semaphore.decrement_test)
-
-    def test_round_trip(self):
-        """After a +/- round-trip, the semaphore path is missing."""
-        self.assertEqual(0, self.semaphore.test_increment())
-        self.assertEqual(0, self.semaphore.decrement_test())
-        self.assertFalse(os.path.exists(self.semaphore.path))
-
-    def test_held(self):
-        self.assertEqual(0, self.semaphore.state)
-        with self.semaphore.held() as state_zero:
-            self.assertEqual(0, state_zero)
-            self.assertEqual(1, self.semaphore.state)
-            with self.semaphore.held() as state_one:
-                self.assertEqual(1, state_one)
-                self.assertEqual(2, self.semaphore.state)
-            self.assertEqual(1, self.semaphore.state)
-        self.assertEqual(0, self.semaphore.state)
Download as text