toil 5.12.0__py3-none-any.whl → 6.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. toil/__init__.py +18 -13
  2. toil/batchSystems/abstractBatchSystem.py +21 -10
  3. toil/batchSystems/abstractGridEngineBatchSystem.py +2 -2
  4. toil/batchSystems/awsBatch.py +14 -14
  5. toil/batchSystems/contained_executor.py +3 -3
  6. toil/batchSystems/htcondor.py +0 -1
  7. toil/batchSystems/kubernetes.py +34 -31
  8. toil/batchSystems/local_support.py +3 -1
  9. toil/batchSystems/mesos/batchSystem.py +7 -7
  10. toil/batchSystems/options.py +32 -83
  11. toil/batchSystems/registry.py +104 -23
  12. toil/batchSystems/singleMachine.py +16 -13
  13. toil/batchSystems/slurm.py +3 -3
  14. toil/batchSystems/torque.py +0 -1
  15. toil/bus.py +6 -8
  16. toil/common.py +532 -743
  17. toil/cwl/__init__.py +28 -32
  18. toil/cwl/cwltoil.py +523 -520
  19. toil/cwl/utils.py +55 -10
  20. toil/fileStores/__init__.py +2 -2
  21. toil/fileStores/abstractFileStore.py +36 -11
  22. toil/fileStores/cachingFileStore.py +607 -530
  23. toil/fileStores/nonCachingFileStore.py +43 -10
  24. toil/job.py +140 -75
  25. toil/jobStores/abstractJobStore.py +147 -79
  26. toil/jobStores/aws/jobStore.py +23 -9
  27. toil/jobStores/aws/utils.py +1 -2
  28. toil/jobStores/fileJobStore.py +117 -19
  29. toil/jobStores/googleJobStore.py +16 -7
  30. toil/jobStores/utils.py +5 -6
  31. toil/leader.py +71 -43
  32. toil/lib/accelerators.py +10 -5
  33. toil/lib/aws/__init__.py +3 -14
  34. toil/lib/aws/ami.py +22 -9
  35. toil/lib/aws/iam.py +21 -13
  36. toil/lib/aws/session.py +2 -16
  37. toil/lib/aws/utils.py +4 -5
  38. toil/lib/compatibility.py +1 -1
  39. toil/lib/conversions.py +7 -3
  40. toil/lib/docker.py +22 -23
  41. toil/lib/ec2.py +10 -6
  42. toil/lib/ec2nodes.py +106 -100
  43. toil/lib/encryption/_nacl.py +2 -1
  44. toil/lib/generatedEC2Lists.py +325 -18
  45. toil/lib/io.py +21 -0
  46. toil/lib/misc.py +1 -1
  47. toil/lib/resources.py +1 -1
  48. toil/lib/threading.py +74 -26
  49. toil/options/common.py +738 -0
  50. toil/options/cwl.py +336 -0
  51. toil/options/wdl.py +32 -0
  52. toil/provisioners/abstractProvisioner.py +1 -4
  53. toil/provisioners/aws/__init__.py +3 -6
  54. toil/provisioners/aws/awsProvisioner.py +6 -0
  55. toil/provisioners/clusterScaler.py +3 -2
  56. toil/provisioners/gceProvisioner.py +2 -2
  57. toil/realtimeLogger.py +2 -1
  58. toil/resource.py +24 -18
  59. toil/server/app.py +2 -3
  60. toil/server/cli/wes_cwl_runner.py +4 -4
  61. toil/server/utils.py +1 -1
  62. toil/server/wes/abstract_backend.py +3 -2
  63. toil/server/wes/amazon_wes_utils.py +5 -4
  64. toil/server/wes/tasks.py +2 -3
  65. toil/server/wes/toil_backend.py +2 -10
  66. toil/server/wsgi_app.py +2 -0
  67. toil/serviceManager.py +12 -10
  68. toil/statsAndLogging.py +5 -1
  69. toil/test/__init__.py +29 -54
  70. toil/test/batchSystems/batchSystemTest.py +11 -111
  71. toil/test/batchSystems/test_slurm.py +3 -2
  72. toil/test/cwl/cwlTest.py +213 -90
  73. toil/test/cwl/glob_dir.cwl +15 -0
  74. toil/test/cwl/preemptible.cwl +21 -0
  75. toil/test/cwl/preemptible_expression.cwl +28 -0
  76. toil/test/cwl/revsort.cwl +1 -1
  77. toil/test/cwl/revsort2.cwl +1 -1
  78. toil/test/docs/scriptsTest.py +0 -1
  79. toil/test/jobStores/jobStoreTest.py +27 -16
  80. toil/test/lib/aws/test_iam.py +4 -14
  81. toil/test/lib/aws/test_utils.py +0 -3
  82. toil/test/lib/dockerTest.py +4 -4
  83. toil/test/lib/test_ec2.py +11 -16
  84. toil/test/mesos/helloWorld.py +4 -5
  85. toil/test/mesos/stress.py +1 -1
  86. toil/test/provisioners/aws/awsProvisionerTest.py +9 -5
  87. toil/test/provisioners/clusterScalerTest.py +6 -4
  88. toil/test/provisioners/clusterTest.py +14 -3
  89. toil/test/provisioners/gceProvisionerTest.py +0 -6
  90. toil/test/provisioners/restartScript.py +3 -2
  91. toil/test/server/serverTest.py +1 -1
  92. toil/test/sort/restart_sort.py +2 -1
  93. toil/test/sort/sort.py +2 -1
  94. toil/test/sort/sortTest.py +2 -13
  95. toil/test/src/autoDeploymentTest.py +45 -45
  96. toil/test/src/busTest.py +5 -5
  97. toil/test/src/checkpointTest.py +2 -2
  98. toil/test/src/deferredFunctionTest.py +1 -1
  99. toil/test/src/fileStoreTest.py +32 -16
  100. toil/test/src/helloWorldTest.py +1 -1
  101. toil/test/src/importExportFileTest.py +1 -1
  102. toil/test/src/jobDescriptionTest.py +2 -1
  103. toil/test/src/jobServiceTest.py +1 -1
  104. toil/test/src/jobTest.py +18 -18
  105. toil/test/src/miscTests.py +5 -3
  106. toil/test/src/promisedRequirementTest.py +3 -3
  107. toil/test/src/realtimeLoggerTest.py +1 -1
  108. toil/test/src/resourceTest.py +2 -2
  109. toil/test/src/restartDAGTest.py +1 -1
  110. toil/test/src/resumabilityTest.py +36 -2
  111. toil/test/src/retainTempDirTest.py +1 -1
  112. toil/test/src/systemTest.py +2 -2
  113. toil/test/src/toilContextManagerTest.py +2 -2
  114. toil/test/src/userDefinedJobArgTypeTest.py +1 -1
  115. toil/test/utils/toilDebugTest.py +98 -32
  116. toil/test/utils/toilKillTest.py +2 -2
  117. toil/test/utils/utilsTest.py +20 -0
  118. toil/test/wdl/wdltoil_test.py +148 -45
  119. toil/toilState.py +7 -6
  120. toil/utils/toilClean.py +1 -1
  121. toil/utils/toilConfig.py +36 -0
  122. toil/utils/toilDebugFile.py +60 -33
  123. toil/utils/toilDebugJob.py +39 -12
  124. toil/utils/toilDestroyCluster.py +1 -1
  125. toil/utils/toilKill.py +1 -1
  126. toil/utils/toilLaunchCluster.py +13 -2
  127. toil/utils/toilMain.py +3 -2
  128. toil/utils/toilRsyncCluster.py +1 -1
  129. toil/utils/toilSshCluster.py +1 -1
  130. toil/utils/toilStats.py +240 -143
  131. toil/utils/toilStatus.py +1 -4
  132. toil/version.py +11 -11
  133. toil/wdl/utils.py +2 -122
  134. toil/wdl/wdltoil.py +999 -386
  135. toil/worker.py +25 -31
  136. {toil-5.12.0.dist-info → toil-6.1.0a1.dist-info}/METADATA +60 -53
  137. toil-6.1.0a1.dist-info/RECORD +237 -0
  138. {toil-5.12.0.dist-info → toil-6.1.0a1.dist-info}/WHEEL +1 -1
  139. {toil-5.12.0.dist-info → toil-6.1.0a1.dist-info}/entry_points.txt +0 -1
  140. toil/batchSystems/parasol.py +0 -379
  141. toil/batchSystems/tes.py +0 -459
  142. toil/test/batchSystems/parasolTestSupport.py +0 -117
  143. toil/test/wdl/builtinTest.py +0 -506
  144. toil/test/wdl/conftest.py +0 -23
  145. toil/test/wdl/toilwdlTest.py +0 -522
  146. toil/wdl/toilwdl.py +0 -141
  147. toil/wdl/versions/dev.py +0 -107
  148. toil/wdl/versions/draft2.py +0 -980
  149. toil/wdl/versions/v1.py +0 -794
  150. toil/wdl/wdl_analysis.py +0 -116
  151. toil/wdl/wdl_functions.py +0 -997
  152. toil/wdl/wdl_synthesis.py +0 -1011
  153. toil/wdl/wdl_types.py +0 -243
  154. toil-5.12.0.dist-info/RECORD +0 -244
  155. /toil/{wdl/versions → options}/__init__.py +0 -0
  156. {toil-5.12.0.dist-info → toil-6.1.0a1.dist-info}/LICENSE +0 -0
  157. {toil-5.12.0.dist-info → toil-6.1.0a1.dist-info}/top_level.txt +0 -0
@@ -11,6 +11,7 @@
11
11
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
+ import copy
14
15
  import errno
15
16
  import hashlib
16
17
  import logging
@@ -19,11 +20,17 @@ import re
19
20
  import shutil
20
21
  import sqlite3
21
22
  import stat
22
- import tempfile
23
23
  import threading
24
24
  import time
25
25
  from contextlib import contextmanager
26
- from typing import Any, Callable, Generator, Optional, Tuple
26
+ from tempfile import mkstemp
27
+ from typing import (Any,
28
+ Callable,
29
+ Generator,
30
+ Iterator,
31
+ Optional,
32
+ Sequence,
33
+ Tuple)
27
34
 
28
35
  from toil.common import cacheDirName, getDirSizeRecursively, getFileSystemSize
29
36
  from toil.fileStores import FileID
@@ -35,6 +42,7 @@ from toil.lib.conversions import bytes2human
35
42
  from toil.lib.io import (atomic_copy,
36
43
  atomic_copyobj,
37
44
  make_public_dir,
45
+ mkdtemp,
38
46
  robust_rmtree)
39
47
  from toil.lib.retry import ErrorCondition, retry
40
48
  from toil.lib.threading import get_process_name, process_name_exists
@@ -224,9 +232,11 @@ class CachingFileStore(AbstractFileStore):
224
232
  # be able to tell that from showing up on a machine where a cache has
225
233
  # already been created.
226
234
  self.dbPath = os.path.join(self.coordination_dir, f'cache-{self.workflowAttemptNumber}.db')
227
- # We need to hold onto both a connection (to commit) and a cursor (to actually use the database)
228
- self.con = sqlite3.connect(self.dbPath, timeout=SQLITE_TIMEOUT_SECS)
229
- self.cur = self.con.cursor()
235
+
236
+ # Database connections are provided by magic properties self.con and
237
+ # self.cur that always have the right object for the current thread to
238
+ # use. They store stuff in this thread-local storage.
239
+ self._thread_local = threading.local()
230
240
 
231
241
  # Note that sqlite3 automatically starts a transaction when we go to
232
242
  # modify the database.
@@ -234,6 +244,12 @@ class CachingFileStore(AbstractFileStore):
234
244
  # write themselves), we need to COMMIT after every coherent set of
235
245
  # writes.
236
246
 
247
+ # Because we support multi-threaded access to files, but we talk to the
248
+ # database as one process with one identity for owning file references,
249
+ # we need to make sure only one thread of our process is trying to e.g.
250
+ # free up space in the cache for a file at a time.
251
+ self.process_identity_lock = threading.RLock()
252
+
237
253
  # Set up the tables
238
254
  self._ensureTables(self.con)
239
255
 
@@ -253,6 +269,37 @@ class CachingFileStore(AbstractFileStore):
253
269
  # time.
254
270
  self.commitThread = None
255
271
 
272
+ @contextmanager
273
+ def as_process(self) -> Generator[str, None, None]:
274
+ """
275
+ Assume the process's identity to act on the caching database.
276
+
277
+ Yields the process's name in the caching database, and holds onto a
278
+ lock while your thread has it.
279
+ """
280
+ with self.process_identity_lock:
281
+ yield get_process_name(self.coordination_dir)
282
+
283
+ @property
284
+ def con(self) -> sqlite3.Connection:
285
+ """
286
+ Get the database connection to be used for the current thread.
287
+ """
288
+ if not hasattr(self._thread_local, 'con'):
289
+ # Connect to the database for this thread.
290
+ # TODO: We assume the connection closes when the thread goes away and can no longer use it.
291
+ self._thread_local.con = sqlite3.connect(self.dbPath, timeout=SQLITE_TIMEOUT_SECS)
292
+ return self._thread_local.con
293
+
294
+ @property
295
+ def cur(self) -> sqlite3.Cursor:
296
+ """
297
+ Get the main cursor to be used for the current thread.
298
+ """
299
+ if not hasattr(self._thread_local, 'cur'):
300
+ # If we don't already have a main cursor for the thread, make one.
301
+ self._thread_local.cur = self.con.cursor()
302
+ return self._thread_local.cur
256
303
 
257
304
  @staticmethod
258
305
  @retry(infinite_retries=True,
@@ -261,7 +308,7 @@ class CachingFileStore(AbstractFileStore):
261
308
  error=sqlite3.OperationalError,
262
309
  error_message_must_include='is locked')
263
310
  ])
264
- def _staticWrite(con, cur, operations):
311
+ def _static_write(con, cur, operations):
265
312
  """
266
313
  Write to the caching database, using the given connection.
267
314
 
@@ -313,6 +360,35 @@ class CachingFileStore(AbstractFileStore):
313
360
 
314
361
  return cur.rowcount
315
362
 
363
+ @staticmethod
364
+ @retry(infinite_retries=True,
365
+ errors=[
366
+ ErrorCondition(
367
+ error=sqlite3.OperationalError,
368
+ error_message_must_include='is locked')
369
+ ])
370
+ def _static_read(cur: sqlite3.Cursor, query: str, args: Optional[Sequence[Any]] = ()) -> Iterator[Any]:
371
+ """
372
+ Read from the database.
373
+
374
+ Run the given select query with the given arguments. Yield each result.
375
+ If the query cannot be run because someone else has a write lock on the
376
+ database, retry.
377
+ """
378
+ # All the real work is the decorators
379
+ return cur.execute(query, args)
380
+
381
+ def _read(self, query: str, args: Optional[Sequence[Any]] = ()) -> Iterator[Any]:
382
+ """
383
+ Read from the database using the instance's connection.
384
+
385
+ Run the given select query with the given arguments. Yield each result.
386
+ If the query cannot be run because someone else has a write lock on the
387
+ database, retry.
388
+ """
389
+
390
+ return self._static_read(self.cur, query, args)
391
+
316
392
  def _write(self, operations):
317
393
  """
318
394
  Write to the caching database, using the instance's connection
@@ -331,7 +407,7 @@ class CachingFileStore(AbstractFileStore):
331
407
  :rtype: int
332
408
  """
333
409
 
334
- return self._staticWrite(self.con, self.cur, operations)
410
+ return self._static_write(self.con, self.cur, operations)
335
411
 
336
412
  @classmethod
337
413
  def _ensureTables(cls, con):
@@ -344,7 +420,7 @@ class CachingFileStore(AbstractFileStore):
344
420
  # Get a cursor
345
421
  cur = con.cursor()
346
422
 
347
- cls._staticWrite(con, cur, ["""
423
+ cls._static_write(con, cur, ["""
348
424
  CREATE TABLE IF NOT EXISTS files (
349
425
  id TEXT NOT NULL PRIMARY KEY,
350
426
  path TEXT UNIQUE NOT NULL,
@@ -399,7 +475,7 @@ class CachingFileStore(AbstractFileStore):
399
475
  if self.cachingIsFree():
400
476
  return 0
401
477
 
402
- for row in self.cur.execute('SELECT TOTAL(size) FROM files'):
478
+ for row in self._read('SELECT TOTAL(size) FROM files'):
403
479
  return row[0]
404
480
 
405
481
  raise RuntimeError('Unable to retrieve cache usage')
@@ -417,7 +493,7 @@ class CachingFileStore(AbstractFileStore):
417
493
  """
418
494
 
419
495
  # Total up the sizes of all the reads of files and subtract it from the total disk reservation of all jobs
420
- for row in self.cur.execute("""
496
+ for row in self._read("""
421
497
  SELECT (
422
498
  (SELECT TOTAL(disk) FROM jobs) -
423
499
  (SELECT TOTAL(files.size) FROM refs INNER JOIN files ON refs.file_id = files.id WHERE refs.state == 'immutable')
@@ -443,24 +519,24 @@ class CachingFileStore(AbstractFileStore):
443
519
  # content.
444
520
 
445
521
  # Do a little report first
446
- for row in self.cur.execute("SELECT value FROM properties WHERE name = 'maxSpace'"):
522
+ for row in self._read("SELECT value FROM properties WHERE name = 'maxSpace'"):
447
523
  logger.debug('Max space: %d', row[0])
448
- for row in self.cur.execute("SELECT TOTAL(size) FROM files"):
524
+ for row in self._read("SELECT TOTAL(size) FROM files"):
449
525
  logger.debug('Total file size: %d', row[0])
450
- for row in self.cur.execute("SELECT TOTAL(disk) FROM jobs"):
526
+ for row in self._read("SELECT TOTAL(disk) FROM jobs"):
451
527
  logger.debug('Total job disk requirement size: %d', row[0])
452
- for row in self.cur.execute("SELECT TOTAL(files.size) FROM refs INNER JOIN files ON refs.file_id = files.id WHERE refs.state = 'immutable'"):
528
+ for row in self._read("SELECT TOTAL(files.size) FROM refs INNER JOIN files ON refs.file_id = files.id WHERE refs.state = 'immutable'"):
453
529
  logger.debug('Total immutable reference size: %d', row[0])
454
530
 
455
531
  if self.cachingIsFree():
456
532
  # If caching is free, we just say that all the space is always available.
457
- for row in self.cur.execute("SELECT value FROM properties WHERE name = 'maxSpace'"):
533
+ for row in self._read("SELECT value FROM properties WHERE name = 'maxSpace'"):
458
534
  return row[0]
459
535
 
460
536
  raise RuntimeError('Unable to retrieve available cache space')
461
537
 
462
538
 
463
- for row in self.cur.execute("""
539
+ for row in self._read("""
464
540
  SELECT (
465
541
  (SELECT value FROM properties WHERE name = 'maxSpace') -
466
542
  (SELECT TOTAL(size) FROM files) -
@@ -480,7 +556,7 @@ class CachingFileStore(AbstractFileStore):
480
556
  If not retrievable, raises an error.
481
557
  """
482
558
 
483
- for row in self.cur.execute("""
559
+ for row in self._read("""
484
560
  SELECT (
485
561
  (SELECT value FROM properties WHERE name = 'maxSpace') -
486
562
  (SELECT TOTAL(disk) FROM jobs)
@@ -502,14 +578,14 @@ class CachingFileStore(AbstractFileStore):
502
578
 
503
579
  logger.debug('Get unused space for job %s', self.jobID)
504
580
 
505
- for row in self.cur.execute('SELECT * FROM files'):
581
+ for row in self._read('SELECT * FROM files'):
506
582
  logger.debug('File record: %s', str(row))
507
583
 
508
- for row in self.cur.execute('SELECT * FROM refs'):
584
+ for row in self._read('SELECT * FROM refs'):
509
585
  logger.debug('Ref record: %s', str(row))
510
586
 
511
587
 
512
- for row in self.cur.execute('SELECT TOTAL(files.size) FROM refs INNER JOIN files ON refs.file_id = files.id WHERE refs.job_id = ? AND refs.state != ?',
588
+ for row in self._read('SELECT TOTAL(files.size) FROM refs INNER JOIN files ON refs.file_id = files.id WHERE refs.job_id = ? AND refs.state != ?',
513
589
  (self.jobID, 'mutable')):
514
590
  # Sum up all the sizes of our referenced files, then subtract that from how much we came in with
515
591
  return self.jobDiskBytes - row[0]
@@ -532,7 +608,7 @@ class CachingFileStore(AbstractFileStore):
532
608
  file you need to do it in a transaction.
533
609
  """
534
610
 
535
- for row in self.cur.execute('SELECT COUNT(*) FROM files WHERE id = ? AND (state = ? OR state = ? OR state = ?)',
611
+ for row in self._read('SELECT COUNT(*) FROM files WHERE id = ? AND (state = ? OR state = ? OR state = ?)',
536
612
  (fileID, 'cached', 'uploadable', 'uploading')):
537
613
 
538
614
  return row[0] > 0
@@ -545,7 +621,7 @@ class CachingFileStore(AbstractFileStore):
545
621
  Counts mutable references too.
546
622
  """
547
623
 
548
- for row in self.cur.execute('SELECT COUNT(*) FROM refs WHERE file_id = ?', (fileID,)):
624
+ for row in self._read('SELECT COUNT(*) FROM refs WHERE file_id = ?', (fileID,)):
549
625
  return row[0]
550
626
  return 0
551
627
 
@@ -558,7 +634,7 @@ class CachingFileStore(AbstractFileStore):
558
634
  configurations, most notably the FileJobStore.
559
635
  """
560
636
 
561
- for row in self.cur.execute('SELECT value FROM properties WHERE name = ?', ('freeCaching',)):
637
+ for row in self._read('SELECT value FROM properties WHERE name = ?', ('freeCaching',)):
562
638
  return row[0] == 1
563
639
 
564
640
  # Otherwise we need to set it
@@ -570,7 +646,7 @@ class CachingFileStore(AbstractFileStore):
570
646
  emptyID = self.jobStore.getEmptyFileStoreID()
571
647
 
572
648
  # Read it out to a generated name.
573
- destDir = tempfile.mkdtemp(dir=self.localCacheDir)
649
+ destDir = mkdtemp(dir=self.localCacheDir)
574
650
  cachedFile = os.path.join(destDir, 'sniffLinkCount')
575
651
  self.jobStore.read_file(emptyID, cachedFile, symlink=False)
576
652
 
@@ -614,7 +690,7 @@ class CachingFileStore(AbstractFileStore):
614
690
  # sure we can never collide even though we are going to remove the
615
691
  # file.
616
692
  # TODO: use a de-slashed version of the ID instead?
617
- handle, path = tempfile.mkstemp(dir=self.localCacheDir, suffix=hasher.hexdigest())
693
+ handle, path = mkstemp(dir=self.localCacheDir, suffix=hasher.hexdigest())
618
694
  os.close(handle)
619
695
  os.unlink(path)
620
696
 
@@ -627,153 +703,137 @@ class CachingFileStore(AbstractFileStore):
627
703
  We don't actually process them here. We take action based on the states of files we own later.
628
704
  """
629
705
 
630
- me = get_process_name(self.coordination_dir)
706
+ with self.as_process() as me:
631
707
 
632
- # Get a list of all file owner processes on this node.
633
- # Exclude NULL because it comes out as 0 and we can't look for PID 0.
634
- owners = []
635
- for row in self.cur.execute('SELECT DISTINCT owner FROM files WHERE owner IS NOT NULL'):
636
- owners.append(row[0])
708
+ # Get a list of all file owner processes on this node.
709
+ # Exclude NULL because it comes out as 0 and we can't look for PID 0.
710
+ owners = []
711
+ for row in self._read('SELECT DISTINCT owner FROM files WHERE owner IS NOT NULL'):
712
+ owners.append(row[0])
637
713
 
638
- # Work out which of them have died.
639
- deadOwners = []
640
- for owner in owners:
641
- if not process_name_exists(self.coordination_dir, owner):
642
- logger.debug('Owner %s is dead', owner)
643
- deadOwners.append(owner)
644
- else:
645
- logger.debug('Owner %s is alive', owner)
646
-
647
- for owner in deadOwners:
648
- # Try and adopt all the files that any dead owner had
649
-
650
- # If they were deleting, we delete.
651
- # If they were downloading, we delete. Any outstanding references
652
- # can't be in use since they are from the dead downloader.
653
- # If they were uploading or uploadable, we mark as cached even
654
- # though it never made it to the job store (and leave it unowned).
655
- #
656
- # Once the dead job that it was being uploaded from is cleaned up,
657
- # and there are no longer any immutable references, it will be
658
- # evicted as normal. Since the dead job can't have been marked
659
- # successfully completed (since the file is still not uploaded),
660
- # nobody is allowed to actually try and use the file.
661
- #
662
- # TODO: if we ever let other PIDs be responsible for writing our
663
- # files asynchronously, this will need to change.
664
- self._write([('UPDATE files SET owner = ?, state = ? WHERE owner = ? AND state = ?',
665
- (me, 'deleting', owner, 'deleting')),
666
- ('UPDATE files SET owner = ?, state = ? WHERE owner = ? AND state = ?',
667
- (me, 'deleting', owner, 'downloading')),
668
- ('UPDATE files SET owner = NULL, state = ? WHERE owner = ? AND (state = ? OR state = ?)',
669
- ('cached', owner, 'uploadable', 'uploading'))])
670
-
671
- logger.debug('Tried to adopt file operations from dead worker %s to ourselves as %s', owner, me)
672
-
673
- @classmethod
674
- def _executePendingDeletions(cls, coordination_dir, con, cur):
714
+ # Work out which of them have died.
715
+ deadOwners = []
716
+ for owner in owners:
717
+ if not process_name_exists(self.coordination_dir, owner):
718
+ logger.debug('Owner %s is dead', owner)
719
+ deadOwners.append(owner)
720
+ else:
721
+ logger.debug('Owner %s is alive', owner)
722
+
723
+ for owner in deadOwners:
724
+ # Try and adopt all the files that any dead owner had
725
+
726
+ # If they were deleting, we delete.
727
+ # If they were downloading, we delete. Any outstanding references
728
+ # can't be in use since they are from the dead downloader.
729
+ # If they were uploading or uploadable, we mark as cached even
730
+ # though it never made it to the job store (and leave it unowned).
731
+ #
732
+ # Once the dead job that it was being uploaded from is cleaned up,
733
+ # and there are no longer any immutable references, it will be
734
+ # evicted as normal. Since the dead job can't have been marked
735
+ # successfully completed (since the file is still not uploaded),
736
+ # nobody is allowed to actually try and use the file.
737
+ #
738
+ # TODO: if we ever let other PIDs be responsible for writing our
739
+ # files asynchronously, this will need to change.
740
+ self._write([('UPDATE files SET owner = ?, state = ? WHERE owner = ? AND state = ?',
741
+ (me, 'deleting', owner, 'deleting')),
742
+ ('UPDATE files SET owner = ?, state = ? WHERE owner = ? AND state = ?',
743
+ (me, 'deleting', owner, 'downloading')),
744
+ ('UPDATE files SET owner = NULL, state = ? WHERE owner = ? AND (state = ? OR state = ?)',
745
+ ('cached', owner, 'uploadable', 'uploading'))])
746
+
747
+ logger.debug('Tried to adopt file operations from dead worker %s to ourselves as %s', owner, me)
748
+
749
+ def _executePendingDeletions(self):
675
750
  """
676
751
  Delete all the files that are registered in the database as in the
677
752
  process of being deleted from the cache by us.
678
753
 
679
754
  Returns the number of files that were deleted.
680
-
681
- Implemented as a class method so it can use the database connection
682
- appropriate to its thread without any chance of getting at the main
683
- thread's connection and cursor in self.
684
-
685
- :param str coordination_dir: The coordination directory.
686
- :param sqlite3.Connection con: Connection to the cache database.
687
- :param sqlite3.Cursor cur: Cursor in the cache database.
688
755
  """
689
756
 
690
- me = get_process_name(coordination_dir)
757
+ with self.as_process() as me:
691
758
 
692
- # Remember the file IDs we are deleting
693
- deletedFiles = []
694
- for row in cur.execute('SELECT id, path FROM files WHERE owner = ? AND state = ?', (me, 'deleting')):
695
- # Grab everything we are supposed to delete and delete it
696
- fileID = row[0]
697
- filePath = row[1]
698
- try:
699
- os.unlink(filePath)
700
- logger.debug('Successfully deleted: %s', filePath)
701
- except OSError:
702
- # Probably already deleted
703
- logger.debug('File already gone: %s', filePath)
704
- # Still need to mark it as deleted
759
+ # Remember the file IDs we are deleting
760
+ deletedFiles = []
761
+ for row in self._read('SELECT id, path FROM files WHERE owner = ? AND state = ?', (me, 'deleting')):
762
+ # Grab everything we are supposed to delete and delete it
763
+ fileID = row[0]
764
+ filePath = row[1]
765
+ try:
766
+ os.unlink(filePath)
767
+ logger.debug('Successfully deleted: %s', filePath)
768
+ except OSError:
769
+ # Probably already deleted
770
+ logger.debug('File already gone: %s', filePath)
771
+ # Still need to mark it as deleted
705
772
 
706
- # Whether we deleted the file or just found out that it is gone, we
707
- # need to take credit for deleting it so that we remove it from the
708
- # database.
709
- deletedFiles.append(fileID)
773
+ # Whether we deleted the file or just found out that it is gone, we
774
+ # need to take credit for deleting it so that we remove it from the
775
+ # database.
776
+ deletedFiles.append(fileID)
710
777
 
711
- for fileID in deletedFiles:
712
- # Drop all the files. They should have stayed in deleting state. We move them from there to not present at all.
713
- # Also drop their references, if they had any from dead downloaders.
714
- cls._staticWrite(con, cur, [('DELETE FROM files WHERE id = ? AND state = ?', (fileID, 'deleting')),
715
- ('DELETE FROM refs WHERE file_id = ?', (fileID,))])
778
+ for fileID in deletedFiles:
779
+ # Drop all the files. They should have stayed in deleting state. We move them from there to not present at all.
780
+ # Also drop their references, if they had any from dead downloaders.
781
+ self._write([('DELETE FROM files WHERE id = ? AND state = ?', (fileID, 'deleting')),
782
+ ('DELETE FROM refs WHERE file_id = ?', (fileID,))])
716
783
 
717
- return len(deletedFiles)
784
+ return len(deletedFiles)
718
785
 
719
- def _executePendingUploads(self, con, cur):
786
+ def _executePendingUploads(self):
720
787
  """
721
788
  Uploads all files in uploadable state that we own.
722
789
 
723
790
  Returns the number of files that were uploaded.
724
-
725
- Needs access to self to get at the job store for uploading files, but
726
- still needs to take con and cur so it can run in a thread with the
727
- thread's database connection.
728
-
729
- :param sqlite3.Connection con: Connection to the cache database.
730
- :param sqlite3.Cursor cur: Cursor in the cache database.
731
791
  """
732
792
 
733
793
  # Work out who we are
734
- me = get_process_name(self.coordination_dir)
735
-
736
- # Record how many files we upload
737
- uploadedCount = 0
738
- while True:
739
- # Try and find a file we might want to upload
740
- fileID = None
741
- filePath = None
742
- for row in cur.execute('SELECT id, path FROM files WHERE state = ? AND owner = ? LIMIT 1', ('uploadable', me)):
743
- fileID = row[0]
744
- filePath = row[1]
745
-
746
- if fileID is None:
747
- # Nothing else exists to upload
748
- break
749
-
750
- # We need to set it to uploading in a way that we can detect that *we* won the update race instead of anyone else.
751
- rowCount = self._staticWrite(con, cur, [('UPDATE files SET state = ? WHERE id = ? AND state = ?', ('uploading', fileID, 'uploadable'))])
752
- if rowCount != 1:
753
- # We didn't manage to update it. Someone else (a running job if
754
- # we are a committing thread, or visa versa) must have grabbed
755
- # it.
756
- logger.debug('Lost race to upload %s', fileID)
757
- # Try again to see if there is something else to grab.
758
- continue
794
+ with self.as_process() as me:
795
+
796
+ # Record how many files we upload
797
+ uploadedCount = 0
798
+ while True:
799
+ # Try and find a file we might want to upload
800
+ fileID = None
801
+ filePath = None
802
+ for row in self._static_read(self.cur, 'SELECT id, path FROM files WHERE state = ? AND owner = ? LIMIT 1', ('uploadable', me)):
803
+ fileID = row[0]
804
+ filePath = row[1]
805
+
806
+ if fileID is None:
807
+ # Nothing else exists to upload
808
+ break
759
809
 
760
- # Upload the file
761
- logger.debug('Actually executing upload for file %s', fileID)
762
- try:
763
- self.jobStore.update_file(fileID, filePath)
764
- except:
765
- # We need to set the state back to 'uploadable' in case of any failures to ensure
766
- # we can retry properly.
767
- self._staticWrite(con, cur, [('UPDATE files SET state = ? WHERE id = ? AND state = ?', ('uploadable', fileID, 'uploading'))])
768
- raise
810
+ # We need to set it to uploading in a way that we can detect that *we* won the update race instead of anyone else.
811
+ rowCount = self._static_write(self.con, self.cur, [('UPDATE files SET state = ? WHERE id = ? AND state = ?', ('uploading', fileID, 'uploadable'))])
812
+ if rowCount != 1:
813
+ # We didn't manage to update it. Someone else (a running job if
814
+ # we are a committing thread, or visa versa) must have grabbed
815
+ # it.
816
+ logger.debug('Lost race to upload %s', fileID)
817
+ # Try again to see if there is something else to grab.
818
+ continue
819
+
820
+ # Upload the file
821
+ logger.debug('Actually executing upload for file %s', fileID)
822
+ try:
823
+ self.jobStore.update_file(fileID, filePath)
824
+ except:
825
+ # We need to set the state back to 'uploadable' in case of any failures to ensure
826
+ # we can retry properly.
827
+ self._static_write(self.con, self.cur, [('UPDATE files SET state = ? WHERE id = ? AND state = ?', ('uploadable', fileID, 'uploading'))])
828
+ raise
769
829
 
770
- # Count it for the total uploaded files value we need to return
771
- uploadedCount += 1
830
+ # Count it for the total uploaded files value we need to return
831
+ uploadedCount += 1
772
832
 
773
- # Remember that we uploaded it in the database
774
- self._staticWrite(con, cur, [('UPDATE files SET state = ?, owner = NULL WHERE id = ?', ('cached', fileID))])
833
+ # Remember that we uploaded it in the database
834
+ self._static_write(self.con, self.cur, [('UPDATE files SET state = ?, owner = NULL WHERE id = ?', ('cached', fileID))])
775
835
 
776
- return uploadedCount
836
+ return uploadedCount
777
837
 
778
838
  def _allocateSpaceForJob(self, newJobReqs):
779
839
  """
@@ -794,23 +854,23 @@ class CachingFileStore(AbstractFileStore):
794
854
  # This will take up space for us and potentially make the cache over-full.
795
855
  # But we won't actually let the job run and use any of this space until
796
856
  # the cache has been successfully cleared out.
797
- me = get_process_name(self.coordination_dir)
798
- self._write([('INSERT INTO jobs VALUES (?, ?, ?, ?)', (self.jobID, self.localTempDir, newJobReqs, me))])
857
+ with self.as_process() as me:
858
+ self._write([('INSERT INTO jobs VALUES (?, ?, ?, ?)', (self.jobID, self.localTempDir, newJobReqs, me))])
799
859
 
800
- # Now we need to make sure that we can fit all currently cached files,
801
- # and the parts of the total job requirements not currently spent on
802
- # cached files, in under the total disk space limit.
860
+ # Now we need to make sure that we can fit all currently cached files,
861
+ # and the parts of the total job requirements not currently spent on
862
+ # cached files, in under the total disk space limit.
803
863
 
804
- available = self.getCacheAvailable()
864
+ available = self.getCacheAvailable()
805
865
 
806
- logger.debug('Available space with job: %d bytes', available)
866
+ logger.debug('Available space with job: %d bytes', available)
807
867
 
808
- if available >= 0:
809
- # We're fine on disk space
810
- return
868
+ if available >= 0:
869
+ # We're fine on disk space
870
+ return
811
871
 
812
- # Otherwise we need to clear stuff.
813
- self._freeUpSpace()
872
+ # Otherwise we need to clear stuff.
873
+ self._freeUpSpace()
814
874
 
815
875
  @classmethod
816
876
  def _removeJob(cls, con, cur, jobID):
@@ -827,10 +887,10 @@ class CachingFileStore(AbstractFileStore):
827
887
  """
828
888
 
829
889
  # Get the job's temp dir
830
- for row in cur.execute('SELECT tempdir FROM jobs WHERE id = ?', (jobID,)):
890
+ for row in cls._static_read(cur, 'SELECT tempdir FROM jobs WHERE id = ?', (jobID,)):
831
891
  jobTemp = row[0]
832
892
 
833
- for row in cur.execute('SELECT path FROM refs WHERE job_id = ?', (jobID,)):
893
+ for row in cls._static_read(cur, 'SELECT path FROM refs WHERE job_id = ?', (jobID,)):
834
894
  try:
835
895
  # Delete all the reference files.
836
896
  os.unlink(row[0])
@@ -838,7 +898,7 @@ class CachingFileStore(AbstractFileStore):
838
898
  # May not exist
839
899
  pass
840
900
  # And their database entries
841
- cls._staticWrite(con, cur, [('DELETE FROM refs WHERE job_id = ?', (jobID,))])
901
+ cls._static_write(con, cur, [('DELETE FROM refs WHERE job_id = ?', (jobID,))])
842
902
 
843
903
  try:
844
904
  # Delete the job's temp directory to the extent that we can.
@@ -847,7 +907,7 @@ class CachingFileStore(AbstractFileStore):
847
907
  pass
848
908
 
849
909
  # Strike the job from the database
850
- cls._staticWrite(con, cur, [('DELETE FROM jobs WHERE id = ?', (jobID,))])
910
+ cls._static_write(con, cur, [('DELETE FROM jobs WHERE id = ?', (jobID,))])
851
911
 
852
912
  def _deallocateSpaceForJob(self):
853
913
  """
@@ -866,66 +926,65 @@ class CachingFileStore(AbstractFileStore):
866
926
  Return whether we manage to get any space freed or not.
867
927
  """
868
928
 
869
- # First we want to make sure that dead jobs aren't holding
870
- # references to files and keeping them from looking unused.
871
- self._removeDeadJobs(self.coordination_dir, self.con)
872
-
873
- # Adopt work from any dead workers
874
- self._stealWorkFromTheDead()
929
+ with self.as_process() as me:
875
930
 
876
- if self._executePendingDeletions(self.coordination_dir, self.con, self.cur) > 0:
877
- # We actually had something to delete, which we deleted.
878
- # Maybe there is space now
879
- logger.debug('Successfully executed pending deletions to free space')
880
- return True
931
+ # First we want to make sure that dead jobs aren't holding
932
+ # references to files and keeping them from looking unused.
933
+ self._removeDeadJobs(self.coordination_dir, self.con)
881
934
 
882
- if self._executePendingUploads(self.con, self.cur) > 0:
883
- # We had something to upload. Maybe it can be evicted now.
884
- logger.debug('Successfully executed pending uploads to free space')
885
- return True
935
+ # Adopt work from any dead workers
936
+ self._stealWorkFromTheDead()
886
937
 
887
- # Otherwise, not enough files could be found in deleting state to solve our problem.
888
- # We need to put something into the deleting state.
889
- # TODO: give other people time to finish their in-progress
890
- # evictions before starting more, or we might evict everything as
891
- # soon as we hit the cache limit.
892
-
893
- # Find something that has no non-mutable references and is not already being deleted.
894
- self.cur.execute("""
895
- SELECT files.id FROM files WHERE files.state = 'cached' AND NOT EXISTS (
896
- SELECT NULL FROM refs WHERE refs.file_id = files.id AND refs.state != 'mutable'
897
- ) LIMIT 1
898
- """)
899
- row = self.cur.fetchone()
900
- if row is None:
901
- # Nothing can be evicted by us.
902
- # Someone else might be in the process of evicting something that will free up space for us too.
903
- # Or someone mught be uploading something and we have to wait for them to finish before it can be deleted.
904
- logger.debug('Could not find anything to evict! Cannot free up space!')
905
- return False
906
-
907
- # Otherwise we found an eviction candidate.
908
- fileID = row[0]
938
+ if self._executePendingDeletions() > 0:
939
+ # We actually had something to delete, which we deleted.
940
+ # Maybe there is space now
941
+ logger.debug('Successfully executed pending deletions to free space')
942
+ return True
943
+
944
+ if self._executePendingUploads() > 0:
945
+ # We had something to upload. Maybe it can be evicted now.
946
+ logger.debug('Successfully executed pending uploads to free space')
947
+ return True
948
+
949
+ # Otherwise, not enough files could be found in deleting state to solve our problem.
950
+ # We need to put something into the deleting state.
951
+ # TODO: give other people time to finish their in-progress
952
+ # evictions before starting more, or we might evict everything as
953
+ # soon as we hit the cache limit.
954
+
955
+ # Find something that has no non-mutable references and is not already being deleted.
956
+ self._read("""
957
+ SELECT files.id FROM files WHERE files.state = 'cached' AND NOT EXISTS (
958
+ SELECT NULL FROM refs WHERE refs.file_id = files.id AND refs.state != 'mutable'
959
+ ) LIMIT 1
960
+ """)
961
+ row = self.cur.fetchone()
962
+ if row is None:
963
+ # Nothing can be evicted by us.
964
+ # Someone else might be in the process of evicting something that will free up space for us too.
965
+ # Or someone mught be uploading something and we have to wait for them to finish before it can be deleted.
966
+ logger.debug('Could not find anything to evict! Cannot free up space!')
967
+ return False
909
968
 
910
- # Work out who we are
911
- me = get_process_name(self.coordination_dir)
969
+ # Otherwise we found an eviction candidate.
970
+ fileID = row[0]
912
971
 
913
- # Try and grab it for deletion, subject to the condition that nothing has started reading it
914
- self._write([("""
915
- UPDATE files SET owner = ?, state = ? WHERE id = ? AND state = ?
916
- AND owner IS NULL AND NOT EXISTS (
917
- SELECT NULL FROM refs WHERE refs.file_id = files.id AND refs.state != 'mutable'
918
- )
919
- """,
920
- (me, 'deleting', fileID, 'cached'))])
972
+ # Try and grab it for deletion, subject to the condition that nothing has started reading it
973
+ self._write([("""
974
+ UPDATE files SET owner = ?, state = ? WHERE id = ? AND state = ?
975
+ AND owner IS NULL AND NOT EXISTS (
976
+ SELECT NULL FROM refs WHERE refs.file_id = files.id AND refs.state != 'mutable'
977
+ )
978
+ """,
979
+ (me, 'deleting', fileID, 'cached'))])
921
980
 
922
- logger.debug('Evicting file %s', fileID)
981
+ logger.debug('Evicting file %s', fileID)
923
982
 
924
- # Whether we actually got it or not, try deleting everything we have to delete
925
- if self._executePendingDeletions(self.coordination_dir, self.con, self.cur) > 0:
926
- # We deleted something
927
- logger.debug('Successfully executed pending deletions to free space')
928
- return True
983
+ # Whether we actually got it or not, try deleting everything we have to delete
984
+ if self._executePendingDeletions() > 0:
985
+ # We deleted something
986
+ logger.debug('Successfully executed pending deletions to free space')
987
+ return True
929
988
 
930
989
  def _freeUpSpace(self):
931
990
  """
@@ -1006,11 +1065,11 @@ class CachingFileStore(AbstractFileStore):
1006
1065
  disk_usage: str = (f"Job {self.jobName} used {percent:.2f}% disk ({bytes2human(disk)}B [{disk}B] used, "
1007
1066
  f"{bytes2human(self.jobDiskBytes)}B [{self.jobDiskBytes}B] requested).")
1008
1067
  if disk > self.jobDiskBytes:
1009
- self.logToMaster("Job used more disk than requested. For CWL, consider increasing the outdirMin "
1068
+ self.log_to_leader("Job used more disk than requested. For CWL, consider increasing the outdirMin "
1010
1069
  f"requirement, otherwise, consider increasing the disk requirement. {disk_usage}",
1011
1070
  level=logging.WARNING)
1012
1071
  else:
1013
- self.logToMaster(disk_usage, level=logging.DEBUG)
1072
+ self.log_to_leader(disk_usage, level=logging.DEBUG)
1014
1073
 
1015
1074
  # Go back up to the per-worker local temp directory.
1016
1075
  os.chdir(startingDir)
@@ -1038,60 +1097,60 @@ class CachingFileStore(AbstractFileStore):
1038
1097
  # TODO: this empty file could leak if we die now...
1039
1098
  fileID = self.jobStore.getEmptyFileStoreID(creatorID, cleanup, os.path.basename(localFileName))
1040
1099
  # Work out who we are
1041
- me = get_process_name(self.coordination_dir)
1100
+ with self.as_process() as me:
1042
1101
 
1043
- # Work out where the file ought to go in the cache
1044
- cachePath = self._getNewCachingPath(fileID)
1102
+ # Work out where the file ought to go in the cache
1103
+ cachePath = self._getNewCachingPath(fileID)
1045
1104
 
1046
- # Create a file in uploadable state and a reference, in the same transaction.
1047
- # Say the reference is an immutable reference
1048
- self._write([('INSERT INTO files VALUES (?, ?, ?, ?, ?)', (fileID, cachePath, fileSize, 'uploadable', me)),
1049
- ('INSERT INTO refs VALUES (?, ?, ?, ?)', (absLocalFileName, fileID, creatorID, 'immutable'))])
1105
+ # Create a file in uploadable state and a reference, in the same transaction.
1106
+ # Say the reference is an immutable reference
1107
+ self._write([('INSERT INTO files VALUES (?, ?, ?, ?, ?)', (fileID, cachePath, fileSize, 'uploadable', me)),
1108
+ ('INSERT INTO refs VALUES (?, ?, ?, ?)', (absLocalFileName, fileID, creatorID, 'immutable'))])
1050
1109
 
1051
- if absLocalFileName.startswith(self.localTempDir) and not os.path.islink(absLocalFileName):
1052
- # We should link into the cache, because the upload is coming from our local temp dir (and not via a symlink in there)
1053
- try:
1054
- # Try and hardlink the file into the cache.
1055
- # This can only fail if the system doesn't have hardlinks, or the
1056
- # file we're trying to link to has too many hardlinks to it
1057
- # already, or something.
1058
- os.link(absLocalFileName, cachePath)
1110
+ if absLocalFileName.startswith(self.localTempDir) and not os.path.islink(absLocalFileName):
1111
+ # We should link into the cache, because the upload is coming from our local temp dir (and not via a symlink in there)
1112
+ try:
1113
+ # Try and hardlink the file into the cache.
1114
+ # This can only fail if the system doesn't have hardlinks, or the
1115
+ # file we're trying to link to has too many hardlinks to it
1116
+ # already, or something.
1117
+ os.link(absLocalFileName, cachePath)
1059
1118
 
1060
- linkedToCache = True
1119
+ linkedToCache = True
1061
1120
 
1062
- logger.debug('Hardlinked file %s into cache at %s; deferring write to job store', localFileName, cachePath)
1063
- assert not os.path.islink(cachePath), "Symlink %s has invaded cache!" % cachePath
1121
+ logger.debug('Hardlinked file %s into cache at %s; deferring write to job store', localFileName, cachePath)
1122
+ assert not os.path.islink(cachePath), "Symlink %s has invaded cache!" % cachePath
1064
1123
 
1065
- # Don't do the upload now. Let it be deferred until later (when the job is committing).
1066
- except OSError:
1067
- # We couldn't make the link for some reason
1124
+ # Don't do the upload now. Let it be deferred until later (when the job is committing).
1125
+ except OSError:
1126
+ # We couldn't make the link for some reason
1127
+ linkedToCache = False
1128
+ else:
1129
+ # If you are uploading a file that physically exists outside the
1130
+ # local temp dir, it should not be linked into the cache. On
1131
+ # systems that support it, we could end up with a
1132
+ # hardlink-to-symlink in the cache if we break this rule, allowing
1133
+ # files to vanish from our cache.
1068
1134
  linkedToCache = False
1069
- else:
1070
- # If you are uploading a file that physically exists outside the
1071
- # local temp dir, it should not be linked into the cache. On
1072
- # systems that support it, we could end up with a
1073
- # hardlink-to-symlink in the cache if we break this rule, allowing
1074
- # files to vanish from our cache.
1075
- linkedToCache = False
1076
1135
 
1077
1136
 
1078
- if not linkedToCache:
1079
- # If we can't do the link into the cache and upload from there, we
1080
- # have to just upload right away. We can't guarantee sufficient
1081
- # space to make a full copy in the cache, if we aren't allowed to
1082
- # take this copy away from the writer.
1137
+ if not linkedToCache:
1138
+ # If we can't do the link into the cache and upload from there, we
1139
+ # have to just upload right away. We can't guarantee sufficient
1140
+ # space to make a full copy in the cache, if we aren't allowed to
1141
+ # take this copy away from the writer.
1083
1142
 
1084
- # Change the reference to 'mutable', which it will be.
1085
- # And drop the file altogether.
1086
- self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('mutable', absLocalFileName, fileID)),
1087
- ('DELETE FROM files WHERE id = ?', (fileID,))])
1143
+ # Change the reference to 'mutable', which it will be.
1144
+ # And drop the file altogether.
1145
+ self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('mutable', absLocalFileName, fileID)),
1146
+ ('DELETE FROM files WHERE id = ?', (fileID,))])
1088
1147
 
1089
- # Save the file to the job store right now
1090
- logger.debug('Actually executing upload immediately for file %s', fileID)
1091
- self.jobStore.update_file(fileID, absLocalFileName)
1148
+ # Save the file to the job store right now
1149
+ logger.debug('Actually executing upload immediately for file %s', fileID)
1150
+ self.jobStore.update_file(fileID, absLocalFileName)
1092
1151
 
1093
- # Ship out the completed FileID object with its real size.
1094
- return FileID.forPath(fileID, absLocalFileName)
1152
+ # Ship out the completed FileID object with its real size.
1153
+ return FileID.forPath(fileID, absLocalFileName)
1095
1154
 
1096
1155
  def readGlobalFile(self, fileStoreID, userPath=None, cache=True, mutable=False, symlink=False):
1097
1156
 
@@ -1162,7 +1221,7 @@ class CachingFileStore(AbstractFileStore):
1162
1221
 
1163
1222
  # Find where the file is cached
1164
1223
  cachedPath = None
1165
- for row in self.cur.execute('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1224
+ for row in self._read('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1166
1225
  cachedPath = row[0]
1167
1226
 
1168
1227
  if cachedPath is None:
@@ -1239,130 +1298,130 @@ class CachingFileStore(AbstractFileStore):
1239
1298
  """
1240
1299
 
1241
1300
  # Work out who we are
1242
- me = get_process_name(self.coordination_dir)
1243
-
1244
- # Work out where to cache the file if it isn't cached already
1245
- cachedPath = self._getNewCachingPath(fileStoreID)
1301
+ with self.as_process() as me:
1246
1302
 
1247
- # Start a loop until we can do one of these
1248
- while True:
1249
- # Try and create a downloading entry if no entry exists
1250
- logger.debug('Trying to make file record for id %s', fileStoreID)
1251
- self._write([('INSERT OR IGNORE INTO files VALUES (?, ?, ?, ?, ?)',
1252
- (fileStoreID, cachedPath, self.getGlobalFileSize(fileStoreID), 'downloading', me))])
1303
+ # Work out where to cache the file if it isn't cached already
1304
+ cachedPath = self._getNewCachingPath(fileStoreID)
1253
1305
 
1254
- # See if we won the race
1255
- self.cur.execute('SELECT COUNT(*) FROM files WHERE id = ? AND state = ? AND owner = ?', (fileStoreID, 'downloading', me))
1256
- if self.cur.fetchone()[0] > 0:
1257
- # We are responsible for downloading the file
1258
- logger.debug('We are now responsible for downloading file %s', fileStoreID)
1306
+ # Start a loop until we can do one of these
1307
+ while True:
1308
+ # Try and create a downloading entry if no entry exists
1309
+ logger.debug('Trying to make file record for id %s', fileStoreID)
1310
+ self._write([('INSERT OR IGNORE INTO files VALUES (?, ?, ?, ?, ?)',
1311
+ (fileStoreID, cachedPath, self.getGlobalFileSize(fileStoreID), 'downloading', me))])
1259
1312
 
1260
- # Make sure we have space for this download.
1261
- self._freeUpSpace()
1262
-
1263
- # Do the download into the cache.
1264
- self._downloadToCache(fileStoreID, cachedPath)
1265
-
1266
- # Now, we may have to immediately give away this file, because
1267
- # we don't have space for two copies.
1268
- # If so, we can't let it go to cached state, because someone
1269
- # else might make a reference to it, and we may get stuck with
1270
- # two readers, one cached copy, and space for two copies total.
1271
-
1272
- # Make the copying reference
1273
- self._write([('INSERT INTO refs VALUES (?, ?, ?, ?)',
1274
- (localFilePath, fileStoreID, readerID, 'copying'))])
1275
-
1276
- # Fulfill it with a full copy or by giving away the cached copy
1277
- self._fulfillCopyingReference(fileStoreID, cachedPath, localFilePath)
1278
-
1279
- # Now we're done
1280
- return localFilePath
1281
-
1282
- else:
1283
- logger.debug('Someone else is already responsible for file %s', fileStoreID)
1284
-
1285
- # A record already existed for this file.
1286
- # Try and create an immutable or copying reference to an entry that
1287
- # is in 'cached' or 'uploadable' or 'uploading' state.
1288
- # It might be uploading because *we* are supposed to be uploading it.
1289
- logger.debug('Trying to make reference to file %s', fileStoreID)
1290
- self._write([('INSERT INTO refs SELECT ?, id, ?, ? FROM files WHERE id = ? AND (state = ? OR state = ? OR state = ?)',
1291
- (localFilePath, readerID, 'copying', fileStoreID, 'cached', 'uploadable', 'uploading'))])
1292
-
1293
- # See if we got it
1294
- self.cur.execute('SELECT COUNT(*) FROM refs WHERE path = ? and file_id = ?', (localFilePath, fileStoreID))
1313
+ # See if we won the race
1314
+ self._read('SELECT COUNT(*) FROM files WHERE id = ? AND state = ? AND owner = ?', (fileStoreID, 'downloading', me))
1295
1315
  if self.cur.fetchone()[0] > 0:
1296
- # The file is cached and we can copy or link it
1297
- logger.debug('Obtained reference to file %s', fileStoreID)
1298
-
1299
- # Get the path it is actually at in the cache, instead of where we wanted to put it
1300
- for row in self.cur.execute('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1301
- cachedPath = row[0]
1302
-
1303
-
1304
- while self.getCacheAvailable() < 0:
1305
- # Since we now have a copying reference, see if we have used too much space.
1306
- # If so, try to free up some space by deleting or uploading, but
1307
- # don't loop forever if we can't get enough.
1308
- self._tryToFreeUpSpace()
1309
-
1310
- if self.getCacheAvailable() >= 0:
1311
- # We made room
1312
- break
1313
-
1314
- # See if we have no other references and we can give away the file.
1315
- # Change it to downloading owned by us if we can grab it.
1316
- self._write([("""
1317
- UPDATE files SET files.owner = ?, files.state = ? WHERE files.id = ? AND files.state = ?
1318
- AND files.owner IS NULL AND NOT EXISTS (
1319
- SELECT NULL FROM refs WHERE refs.file_id = files.id AND refs.state != 'mutable'
1320
- )
1321
- """,
1322
- (me, 'downloading', fileStoreID, 'cached'))])
1323
-
1324
- if self._giveAwayDownloadingFile(fileStoreID, cachedPath, localFilePath):
1325
- # We got ownership of the file and managed to give it away.
1326
- return localFilePath
1316
+ # We are responsible for downloading the file
1317
+ logger.debug('We are now responsible for downloading file %s', fileStoreID)
1327
1318
 
1328
- # If we don't have space, and we couldn't make space, and we
1329
- # couldn't get exclusive control of the file to give it away, we
1330
- # need to wait for one of those people with references to the file
1331
- # to finish and give it up.
1332
- # TODO: work out if that will never happen somehow.
1333
- time.sleep(self.contentionBackoff)
1319
+ # Make sure we have space for this download.
1320
+ self._freeUpSpace()
1334
1321
 
1335
- # OK, now we have space to make a copy.
1322
+ # Do the download into the cache.
1323
+ self._downloadToCache(fileStoreID, cachedPath)
1336
1324
 
1337
- if self.forceDownloadDelay is not None:
1338
- # Wait around to simulate a big file for testing
1339
- time.sleep(self.forceDownloadDelay)
1325
+ # Now, we may have to immediately give away this file, because
1326
+ # we don't have space for two copies.
1327
+ # If so, we can't let it go to cached state, because someone
1328
+ # else might make a reference to it, and we may get stuck with
1329
+ # two readers, one cached copy, and space for two copies total.
1340
1330
 
1341
- # Make the copy
1342
- atomic_copy(cachedPath, localFilePath)
1331
+ # Make the copying reference
1332
+ self._write([('INSERT INTO refs VALUES (?, ?, ?, ?)',
1333
+ (localFilePath, fileStoreID, readerID, 'copying'))])
1343
1334
 
1344
- # Change the reference to mutable
1345
- self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('mutable', localFilePath, fileStoreID))])
1335
+ # Fulfill it with a full copy or by giving away the cached copy
1336
+ self._fulfillCopyingReference(fileStoreID, cachedPath, localFilePath)
1346
1337
 
1347
1338
  # Now we're done
1348
1339
  return localFilePath
1349
1340
 
1350
1341
  else:
1351
- # We didn't get a reference. Maybe it is still downloading.
1352
- logger.debug('Could not obtain reference to file %s', fileStoreID)
1342
+ logger.debug('Someone else is already responsible for file %s', fileStoreID)
1343
+
1344
+ # A record already existed for this file.
1345
+ # Try and create an immutable or copying reference to an entry that
1346
+ # is in 'cached' or 'uploadable' or 'uploading' state.
1347
+ # It might be uploading because *we* are supposed to be uploading it.
1348
+ logger.debug('Trying to make reference to file %s', fileStoreID)
1349
+ self._write([('INSERT INTO refs SELECT ?, id, ?, ? FROM files WHERE id = ? AND (state = ? OR state = ? OR state = ?)',
1350
+ (localFilePath, readerID, 'copying', fileStoreID, 'cached', 'uploadable', 'uploading'))])
1351
+
1352
+ # See if we got it
1353
+ self._read('SELECT COUNT(*) FROM refs WHERE path = ? and file_id = ?', (localFilePath, fileStoreID))
1354
+ if self.cur.fetchone()[0] > 0:
1355
+ # The file is cached and we can copy or link it
1356
+ logger.debug('Obtained reference to file %s', fileStoreID)
1357
+
1358
+ # Get the path it is actually at in the cache, instead of where we wanted to put it
1359
+ for row in self._read('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1360
+ cachedPath = row[0]
1361
+
1362
+
1363
+ while self.getCacheAvailable() < 0:
1364
+ # Since we now have a copying reference, see if we have used too much space.
1365
+ # If so, try to free up some space by deleting or uploading, but
1366
+ # don't loop forever if we can't get enough.
1367
+ self._tryToFreeUpSpace()
1368
+
1369
+ if self.getCacheAvailable() >= 0:
1370
+ # We made room
1371
+ break
1372
+
1373
+ # See if we have no other references and we can give away the file.
1374
+ # Change it to downloading owned by us if we can grab it.
1375
+ self._write([("""
1376
+ UPDATE files SET files.owner = ?, files.state = ? WHERE files.id = ? AND files.state = ?
1377
+ AND files.owner IS NULL AND NOT EXISTS (
1378
+ SELECT NULL FROM refs WHERE refs.file_id = files.id AND refs.state != 'mutable'
1379
+ )
1380
+ """,
1381
+ (me, 'downloading', fileStoreID, 'cached'))])
1382
+
1383
+ if self._giveAwayDownloadingFile(fileStoreID, cachedPath, localFilePath):
1384
+ # We got ownership of the file and managed to give it away.
1385
+ return localFilePath
1386
+
1387
+ # If we don't have space, and we couldn't make space, and we
1388
+ # couldn't get exclusive control of the file to give it away, we
1389
+ # need to wait for one of those people with references to the file
1390
+ # to finish and give it up.
1391
+ # TODO: work out if that will never happen somehow.
1392
+ time.sleep(self.contentionBackoff)
1393
+
1394
+ # OK, now we have space to make a copy.
1395
+
1396
+ if self.forceDownloadDelay is not None:
1397
+ # Wait around to simulate a big file for testing
1398
+ time.sleep(self.forceDownloadDelay)
1399
+
1400
+ # Make the copy
1401
+ atomic_copy(cachedPath, localFilePath)
1402
+
1403
+ # Change the reference to mutable
1404
+ self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('mutable', localFilePath, fileStoreID))])
1405
+
1406
+ # Now we're done
1407
+ return localFilePath
1353
1408
 
1354
- # Loop around again and see if either we can download it or we can get a reference to it.
1409
+ else:
1410
+ # We didn't get a reference. Maybe it is still downloading.
1411
+ logger.debug('Could not obtain reference to file %s', fileStoreID)
1355
1412
 
1356
- # If we didn't get a download or a reference, adopt and do work
1357
- # from dead workers and loop again.
1358
- # We may have to wait for someone else's download or delete to
1359
- # finish. If they die, we will notice.
1360
- self._removeDeadJobs(self.coordination_dir, self.con)
1361
- self._stealWorkFromTheDead()
1362
- self._executePendingDeletions(self.coordination_dir, self.con, self.cur)
1413
+ # Loop around again and see if either we can download it or we can get a reference to it.
1363
1414
 
1364
- # Wait for other people's downloads to progress before re-polling.
1365
- time.sleep(self.contentionBackoff)
1415
+ # If we didn't get a download or a reference, adopt and do work
1416
+ # from dead workers and loop again.
1417
+ # We may have to wait for someone else's download or delete to
1418
+ # finish. If they die, we will notice.
1419
+ self._removeDeadJobs(self.coordination_dir, self.con)
1420
+ self._stealWorkFromTheDead()
1421
+ self._executePendingDeletions()
1422
+
1423
+ # Wait for other people's downloads to progress before re-polling.
1424
+ time.sleep(self.contentionBackoff)
1366
1425
 
1367
1426
  def _fulfillCopyingReference(self, fileStoreID, cachedPath, localFilePath):
1368
1427
  """
@@ -1422,27 +1481,27 @@ class CachingFileStore(AbstractFileStore):
1422
1481
  """
1423
1482
 
1424
1483
  # Work out who we are
1425
- me = get_process_name(self.coordination_dir)
1484
+ with self.as_process() as me:
1426
1485
 
1427
- # See if we actually own this file and can giove it away
1428
- self.cur.execute('SELECT COUNT(*) FROM files WHERE id = ? AND state = ? AND owner = ?',
1429
- (fileStoreID, 'downloading', me))
1430
- if self.cur.fetchone()[0] > 0:
1431
- # Now we have exclusive control of the cached copy of the file, so we can give it away.
1486
+ # See if we actually own this file and can giove it away
1487
+ self._read('SELECT COUNT(*) FROM files WHERE id = ? AND state = ? AND owner = ?',
1488
+ (fileStoreID, 'downloading', me))
1489
+ if self.cur.fetchone()[0] > 0:
1490
+ # Now we have exclusive control of the cached copy of the file, so we can give it away.
1432
1491
 
1433
- # Don't fake a delay here; this should be a rename always.
1492
+ # Don't fake a delay here; this should be a rename always.
1434
1493
 
1435
- # We are giving it away
1436
- shutil.move(cachedPath, localFilePath)
1437
- # Record that.
1438
- self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('mutable', localFilePath, fileStoreID)),
1439
- ('DELETE FROM files WHERE id = ?', (fileStoreID,))])
1494
+ # We are giving it away
1495
+ shutil.move(cachedPath, localFilePath)
1496
+ # Record that.
1497
+ self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('mutable', localFilePath, fileStoreID)),
1498
+ ('DELETE FROM files WHERE id = ?', (fileStoreID,))])
1440
1499
 
1441
- # Now we're done
1442
- return True
1443
- else:
1444
- # We don't own this file in 'downloading' state
1445
- return False
1500
+ # Now we're done
1501
+ return True
1502
+ else:
1503
+ # We don't own this file in 'downloading' state
1504
+ return False
1446
1505
 
1447
1506
  def _createLinkFromCache(self, cachedPath, localFilePath, symlink=True):
1448
1507
  """
@@ -1493,108 +1552,108 @@ class CachingFileStore(AbstractFileStore):
1493
1552
  # Now we know to use the cache, and that we don't require a mutable copy.
1494
1553
 
1495
1554
  # Work out who we are
1496
- me = get_process_name(self.coordination_dir)
1497
-
1498
- # Work out where to cache the file if it isn't cached already
1499
- cachedPath = self._getNewCachingPath(fileStoreID)
1500
-
1501
- # Start a loop until we can do one of these
1502
- while True:
1503
- # Try and create a downloading entry if no entry exists.
1504
- # Make sure to create a reference at the same time if it succeeds, to bill it against our job's space.
1505
- # Don't create the mutable reference yet because we might not necessarily be able to clear that space.
1506
- logger.debug('Trying to make file downloading file record and reference for id %s', fileStoreID)
1507
- self._write([('INSERT OR IGNORE INTO files VALUES (?, ?, ?, ?, ?)',
1508
- (fileStoreID, cachedPath, self.getGlobalFileSize(fileStoreID), 'downloading', me)),
1509
- ('INSERT INTO refs SELECT ?, id, ?, ? FROM files WHERE id = ? AND state = ? AND owner = ?',
1510
- (localFilePath, readerID, 'immutable', fileStoreID, 'downloading', me))])
1511
-
1512
- # See if we won the race
1513
- self.cur.execute('SELECT COUNT(*) FROM files WHERE id = ? AND state = ? AND owner = ?', (fileStoreID, 'downloading', me))
1514
- if self.cur.fetchone()[0] > 0:
1515
- # We are responsible for downloading the file (and we have the reference)
1516
- logger.debug('We are now responsible for downloading file %s', fileStoreID)
1517
-
1518
- # Make sure we have space for this download.
1519
- self._freeUpSpace()
1520
-
1521
- # Do the download into the cache.
1522
- self._downloadToCache(fileStoreID, cachedPath)
1523
-
1524
- # Try and make the link before we let the file go to cached state.
1525
- # If we fail we may end up having to give away the file we just downloaded.
1526
- if self._createLinkFromCache(cachedPath, localFilePath, symlink):
1527
- # We made the link!
1528
-
1529
- # Change file state from downloading to cached so other people can use it
1530
- self._write([('UPDATE files SET state = ?, owner = NULL WHERE id = ?',
1531
- ('cached', fileStoreID))])
1532
-
1533
- # Now we're done!
1534
- return localFilePath
1535
- else:
1536
- # We could not make a link. We need to make a copy.
1537
-
1538
- # Change the reference to copying.
1539
- self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('copying', localFilePath, fileStoreID))])
1555
+ with self.as_process() as me:
1556
+
1557
+ # Work out where to cache the file if it isn't cached already
1558
+ cachedPath = self._getNewCachingPath(fileStoreID)
1559
+
1560
+ # Start a loop until we can do one of these
1561
+ while True:
1562
+ # Try and create a downloading entry if no entry exists.
1563
+ # Make sure to create a reference at the same time if it succeeds, to bill it against our job's space.
1564
+ # Don't create the mutable reference yet because we might not necessarily be able to clear that space.
1565
+ logger.debug('Trying to make file downloading file record and reference for id %s', fileStoreID)
1566
+ self._write([('INSERT OR IGNORE INTO files VALUES (?, ?, ?, ?, ?)',
1567
+ (fileStoreID, cachedPath, self.getGlobalFileSize(fileStoreID), 'downloading', me)),
1568
+ ('INSERT INTO refs SELECT ?, id, ?, ? FROM files WHERE id = ? AND state = ? AND owner = ?',
1569
+ (localFilePath, readerID, 'immutable', fileStoreID, 'downloading', me))])
1570
+
1571
+ # See if we won the race
1572
+ self._read('SELECT COUNT(*) FROM files WHERE id = ? AND state = ? AND owner = ?', (fileStoreID, 'downloading', me))
1573
+ if self.cur.fetchone()[0] > 0:
1574
+ # We are responsible for downloading the file (and we have the reference)
1575
+ logger.debug('We are now responsible for downloading file %s', fileStoreID)
1540
1576
 
1541
- # Fulfill it with a full copy or by giving away the cached copy
1542
- self._fulfillCopyingReference(fileStoreID, cachedPath, localFilePath)
1577
+ # Make sure we have space for this download.
1578
+ self._freeUpSpace()
1543
1579
 
1544
- # Now we're done
1545
- return localFilePath
1580
+ # Do the download into the cache.
1581
+ self._downloadToCache(fileStoreID, cachedPath)
1546
1582
 
1547
- else:
1548
- logger.debug('We already have an entry in the cache database for file %s', fileStoreID)
1549
-
1550
- # A record already existed for this file.
1551
- # Try and create an immutable reference to an entry that
1552
- # is in 'cached' or 'uploadable' or 'uploading' state.
1553
- # It might be uploading because *we* are supposed to be uploading it.
1554
- logger.debug('Trying to make reference to file %s', fileStoreID)
1555
- self._write([('INSERT INTO refs SELECT ?, id, ?, ? FROM files WHERE id = ? AND (state = ? OR state = ? OR state = ?)',
1556
- (localFilePath, readerID, 'immutable', fileStoreID, 'cached', 'uploadable', 'uploading'))])
1557
-
1558
- # See if we got it
1559
- self.cur.execute('SELECT COUNT(*) FROM refs WHERE path = ? and file_id = ?', (localFilePath, fileStoreID))
1560
- if self.cur.fetchone()[0] > 0:
1561
- # The file is cached and we can copy or link it
1562
- logger.debug('Obtained reference to file %s', fileStoreID)
1583
+ # Try and make the link before we let the file go to cached state.
1584
+ # If we fail we may end up having to give away the file we just downloaded.
1585
+ if self._createLinkFromCache(cachedPath, localFilePath, symlink):
1586
+ # We made the link!
1563
1587
 
1564
- # Get the path it is actually at in the cache, instead of where we wanted to put it
1565
- for row in self.cur.execute('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1566
- cachedPath = row[0]
1588
+ # Change file state from downloading to cached so other people can use it
1589
+ self._write([('UPDATE files SET state = ?, owner = NULL WHERE id = ?',
1590
+ ('cached', fileStoreID))])
1567
1591
 
1568
- if self._createLinkFromCache(cachedPath, localFilePath, symlink):
1569
- # We managed to make the link
1592
+ # Now we're done!
1570
1593
  return localFilePath
1571
1594
  else:
1572
- # We can't make the link. We need a copy instead.
1595
+ # We could not make a link. We need to make a copy.
1573
1596
 
1574
- # We could change the reference to copying, see if
1575
- # there's space, make the copy, try and get ahold of
1576
- # the file if there isn't space, and give it away, but
1577
- # we already have code for that for mutable downloads,
1578
- # so just clear the reference and download mutably.
1597
+ # Change the reference to copying.
1598
+ self._write([('UPDATE refs SET state = ? WHERE path = ? AND file_id = ?', ('copying', localFilePath, fileStoreID))])
1579
1599
 
1580
- self._write([('DELETE FROM refs WHERE path = ? AND file_id = ?', (localFilePath, fileStoreID))])
1600
+ # Fulfill it with a full copy or by giving away the cached copy
1601
+ self._fulfillCopyingReference(fileStoreID, cachedPath, localFilePath)
1602
+
1603
+ # Now we're done
1604
+ return localFilePath
1581
1605
 
1582
- return self._readGlobalFileMutablyWithCache(fileStoreID, localFilePath, readerID)
1583
1606
  else:
1584
- logger.debug('Could not obtain reference to file %s', fileStoreID)
1607
+ logger.debug('We already have an entry in the cache database for file %s', fileStoreID)
1608
+
1609
+ # A record already existed for this file.
1610
+ # Try and create an immutable reference to an entry that
1611
+ # is in 'cached' or 'uploadable' or 'uploading' state.
1612
+ # It might be uploading because *we* are supposed to be uploading it.
1613
+ logger.debug('Trying to make reference to file %s', fileStoreID)
1614
+ self._write([('INSERT INTO refs SELECT ?, id, ?, ? FROM files WHERE id = ? AND (state = ? OR state = ? OR state = ?)',
1615
+ (localFilePath, readerID, 'immutable', fileStoreID, 'cached', 'uploadable', 'uploading'))])
1616
+
1617
+ # See if we got it
1618
+ self._read('SELECT COUNT(*) FROM refs WHERE path = ? and file_id = ?', (localFilePath, fileStoreID))
1619
+ if self.cur.fetchone()[0] > 0:
1620
+ # The file is cached and we can copy or link it
1621
+ logger.debug('Obtained reference to file %s', fileStoreID)
1622
+
1623
+ # Get the path it is actually at in the cache, instead of where we wanted to put it
1624
+ for row in self._read('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1625
+ cachedPath = row[0]
1626
+
1627
+ if self._createLinkFromCache(cachedPath, localFilePath, symlink):
1628
+ # We managed to make the link
1629
+ return localFilePath
1630
+ else:
1631
+ # We can't make the link. We need a copy instead.
1585
1632
 
1586
- # If we didn't get a download or a reference, adopt and do work from dead workers and loop again.
1587
- # We may have to wait for someone else's download or delete to
1588
- # finish. If they die, we will notice.
1589
- self._removeDeadJobs(self.coordination_dir, self.con)
1590
- self._stealWorkFromTheDead()
1591
- # We may have acquired ownership of partially-downloaded
1592
- # files, now in deleting state, that we need to delete
1593
- # before we can download them.
1594
- self._executePendingDeletions(self.coordination_dir, self.con, self.cur)
1633
+ # We could change the reference to copying, see if
1634
+ # there's space, make the copy, try and get ahold of
1635
+ # the file if there isn't space, and give it away, but
1636
+ # we already have code for that for mutable downloads,
1637
+ # so just clear the reference and download mutably.
1595
1638
 
1596
- # Wait for other people's downloads to progress.
1597
- time.sleep(self.contentionBackoff)
1639
+ self._write([('DELETE FROM refs WHERE path = ? AND file_id = ?', (localFilePath, fileStoreID))])
1640
+
1641
+ return self._readGlobalFileMutablyWithCache(fileStoreID, localFilePath, readerID)
1642
+ else:
1643
+ logger.debug('Could not obtain reference to file %s', fileStoreID)
1644
+
1645
+ # If we didn't get a download or a reference, adopt and do work from dead workers and loop again.
1646
+ # We may have to wait for someone else's download or delete to
1647
+ # finish. If they die, we will notice.
1648
+ self._removeDeadJobs(self.coordination_dir, self.con)
1649
+ self._stealWorkFromTheDead()
1650
+ # We may have acquired ownership of partially-downloaded
1651
+ # files, now in deleting state, that we need to delete
1652
+ # before we can download them.
1653
+ self._executePendingDeletions()
1654
+
1655
+ # Wait for other people's downloads to progress.
1656
+ time.sleep(self.contentionBackoff)
1598
1657
 
1599
1658
  @contextmanager
1600
1659
  def _with_copying_reference_to_upload(self, file_store_id: FileID, reader_id: str, local_file_path: Optional[str] = None) -> Generator:
@@ -1624,7 +1683,7 @@ class CachingFileStore(AbstractFileStore):
1624
1683
 
1625
1684
  # See if we got it
1626
1685
  have_reference = False
1627
- for row in self.cur.execute('SELECT COUNT(*) FROM refs WHERE path = ? and file_id = ?', (local_file_path, file_store_id)):
1686
+ for row in self._read('SELECT COUNT(*) FROM refs WHERE path = ? and file_id = ?', (local_file_path, file_store_id)):
1628
1687
  have_reference = row[0] > 0
1629
1688
 
1630
1689
  if have_reference:
@@ -1651,12 +1710,12 @@ class CachingFileStore(AbstractFileStore):
1651
1710
  # Try and grab a reference to the file if it is being uploaded.
1652
1711
  if ref_path is not None:
1653
1712
  # We have an update in the cache that isn't written back yet.
1654
- # So we must stream from the ceche for consistency.
1713
+ # So we must stream from the cache for consistency.
1655
1714
 
1656
1715
  # The ref file is not actually copied to; find the actual file
1657
1716
  # in the cache
1658
1717
  cached_path = None
1659
- for row in self.cur.execute('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1718
+ for row in self._read('SELECT path FROM files WHERE id = ?', (fileStoreID,)):
1660
1719
  cached_path = row[0]
1661
1720
 
1662
1721
  if cached_path is None:
@@ -1666,7 +1725,7 @@ class CachingFileStore(AbstractFileStore):
1666
1725
  # Pass along the results of the open context manager on the
1667
1726
  # file in the cache.
1668
1727
  yield result
1669
- # When we exit the with the copying reference will go away and
1728
+ # When we exit the with, the copying reference will go away and
1670
1729
  # the file will be allowed to leave the cache again.
1671
1730
  else:
1672
1731
  # No local update, so we can stream from the job store
@@ -1684,7 +1743,7 @@ class CachingFileStore(AbstractFileStore):
1684
1743
  # missing ref file, we will raise an error about it and stop deleting
1685
1744
  # things.
1686
1745
  missingFile = None
1687
- for row in self.cur.execute('SELECT path FROM refs WHERE file_id = ? AND job_id = ?', (fileStoreID, jobID)):
1746
+ for row in self._read('SELECT path FROM refs WHERE file_id = ? AND job_id = ?', (fileStoreID, jobID)):
1688
1747
  # Delete all the files that are references to this cached file (even mutable copies)
1689
1748
  path = row[0]
1690
1749
 
@@ -1735,25 +1794,25 @@ class CachingFileStore(AbstractFileStore):
1735
1794
  raise
1736
1795
 
1737
1796
  # Work out who we are
1738
- me = get_process_name(self.coordination_dir)
1797
+ with self.as_process() as me:
1739
1798
 
1740
- # Make sure nobody else has references to it
1741
- for row in self.cur.execute('SELECT job_id FROM refs WHERE file_id = ? AND state != ?', (fileStoreID, 'mutable')):
1742
- raise RuntimeError(f'Deleted file ID {fileStoreID} which is still in use by job {row[0]}')
1743
- # TODO: should we just let other jobs and the cache keep the file until
1744
- # it gets evicted, and only delete at the back end?
1799
+ # Make sure nobody else has references to it
1800
+ for row in self._read('SELECT job_id FROM refs WHERE file_id = ? AND state != ?', (fileStoreID, 'mutable')):
1801
+ raise RuntimeError(f'Deleted file ID {fileStoreID} which is still in use by job {row[0]}')
1802
+ # TODO: should we just let other jobs and the cache keep the file until
1803
+ # it gets evicted, and only delete at the back end?
1745
1804
 
1746
- # Pop the file into deleting state owned by us if it exists
1747
- self._write([('UPDATE files SET state = ?, owner = ? WHERE id = ?', ('deleting', me, fileStoreID))])
1805
+ # Pop the file into deleting state owned by us if it exists
1806
+ self._write([('UPDATE files SET state = ?, owner = ? WHERE id = ?', ('deleting', me, fileStoreID))])
1748
1807
 
1749
- # Finish the delete if the file is present
1750
- self._executePendingDeletions(self.coordination_dir, self.con, self.cur)
1808
+ # Finish the delete if the file is present
1809
+ self._executePendingDeletions()
1751
1810
 
1752
- # Add the file to the list of files to be deleted from the job store
1753
- # once the run method completes.
1754
- self.filesToDelete.add(str(fileStoreID))
1755
- self.logToMaster('Added file with ID \'%s\' to the list of files to be' % fileStoreID +
1756
- ' globally deleted.', level=logging.DEBUG)
1811
+ # Add the file to the list of files to be deleted from the job store
1812
+ # once the run method completes.
1813
+ self.filesToDelete.add(str(fileStoreID))
1814
+ self.log_to_leader('Added file with ID \'%s\' to the list of files to be' % fileStoreID +
1815
+ ' globally deleted.', level=logging.DEBUG)
1757
1816
 
1758
1817
  @deprecated(new_function_name='export_file')
1759
1818
  def exportFile(self, jobStoreFileID: FileID, dstUrl: str) -> None:
@@ -1768,7 +1827,7 @@ class CachingFileStore(AbstractFileStore):
1768
1827
  # until they are done.
1769
1828
 
1770
1829
  # For safety and simplicity, we just execute all pending uploads now.
1771
- self._executePendingUploads(self.con, self.cur)
1830
+ self._executePendingUploads()
1772
1831
 
1773
1832
  # Then we let the job store export. TODO: let the export come from the
1774
1833
  # cache? How would we write the URL?
@@ -1796,11 +1855,37 @@ class CachingFileStore(AbstractFileStore):
1796
1855
  # value?) wait on it, so we can't forget to join it later.
1797
1856
  self.waitForCommit()
1798
1857
 
1858
+ if len(self.jobDesc.filesToDelete) > 0:
1859
+ raise RuntimeError("Job is already in the process of being committed!")
1860
+
1861
+ state_to_commit: Optional[JobDescription] = None
1862
+
1863
+ if jobState:
1864
+ # Clone the current job description, so that further updates to it
1865
+ # (such as new successors being added when it runs) occur after the
1866
+ # commit process, and aren't committed early or partially.
1867
+ state_to_commit = copy.deepcopy(self.jobDesc)
1868
+ # Also snapshot the files that should be seen as deleted once the
1869
+ # update of the job description is visible.
1870
+ state_to_commit.filesToDelete = list(self.filesToDelete)
1871
+ # TODO: We never clear this out on the file store itself. This
1872
+ # might be necessary for later jobs to see earlier jobs' deleted
1873
+ # before they are committed?
1874
+
1875
+ logger.debug('Starting commit of %s forked from %s', state_to_commit, self.jobDesc)
1876
+ # Make sure the deep copy isn't summoning ghosts of old job
1877
+ # versions. It must be as new or newer at this point.
1878
+ self.jobDesc.check_new_version(state_to_commit)
1879
+
1880
+ # Bump the original's version since saving will do that too and we
1881
+ # don't want duplicate versions.
1882
+ self.jobDesc.reserve_versions(1 if len(state_to_commit.filesToDelete) == 0 else 2)
1883
+
1799
1884
  # Start the commit thread
1800
- self.commitThread = threading.Thread(target=self.startCommitThread, args=(jobState,))
1885
+ self.commitThread = threading.Thread(target=self.startCommitThread, args=(state_to_commit,))
1801
1886
  self.commitThread.start()
1802
1887
 
1803
- def startCommitThread(self, jobState):
1888
+ def startCommitThread(self, state_to_commit: Optional[JobDescription]):
1804
1889
  """
1805
1890
  Run in a thread to actually commit the current job.
1806
1891
  """
@@ -1810,38 +1895,28 @@ class CachingFileStore(AbstractFileStore):
1810
1895
  self.waitForPreviousCommit()
1811
1896
 
1812
1897
  try:
1813
- # Reconnect to the database from this thread. The main thread can
1814
- # keep using self.con and self.cur. We need to do this because
1815
- # SQLite objects are tied to a thread.
1816
- con = sqlite3.connect(self.dbPath, timeout=SQLITE_TIMEOUT_SECS)
1817
- cur = con.cursor()
1818
-
1819
1898
  logger.debug('Committing file uploads asynchronously')
1820
1899
 
1821
1900
  # Finish all uploads
1822
- self._executePendingUploads(con, cur)
1901
+ self._executePendingUploads()
1823
1902
  # Finish all deletions out of the cache (not from the job store)
1824
- self._executePendingDeletions(self.coordination_dir, con, cur)
1903
+ self._executePendingDeletions()
1825
1904
 
1826
- if jobState:
1905
+ if state_to_commit is not None:
1827
1906
  # Do all the things that make this job not redoable
1828
1907
 
1829
- logger.debug('Committing file deletes and job state changes asynchronously')
1908
+ logger.debug('Committing file deletes and job state changes asynchronously from %s', state_to_commit)
1830
1909
 
1831
- # Indicate any files that should be deleted once the update of
1832
- # the job wrapper is completed.
1833
- self.jobDesc.filesToDelete = list(self.filesToDelete)
1834
1910
  # Complete the job
1835
- self.jobStore.update_job(self.jobDesc)
1836
- # Delete any remnant jobs
1837
- list(map(self.jobStore.delete_job, self.jobsToDelete))
1838
- # Delete any remnant files
1839
- list(map(self.jobStore.delete_file, self.filesToDelete))
1911
+ self.jobStore.update_job(state_to_commit)
1912
+ # Delete the files
1913
+ list(map(self.jobStore.delete_file, state_to_commit.filesToDelete))
1840
1914
  # Remove the files to delete list, having successfully removed the files
1841
- if len(self.filesToDelete) > 0:
1842
- self.jobDesc.filesToDelete = []
1915
+ if len(state_to_commit.filesToDelete) > 0:
1916
+ state_to_commit.filesToDelete = []
1843
1917
  # Update, removing emptying files to delete
1844
- self.jobStore.update_job(self.jobDesc)
1918
+ self.jobStore.update_job(state_to_commit)
1919
+
1845
1920
  except:
1846
1921
  self._terminateEvent.set()
1847
1922
  raise
@@ -1852,14 +1927,14 @@ class CachingFileStore(AbstractFileStore):
1852
1927
  def shutdown(cls, shutdown_info: Tuple[str, str]) -> None:
1853
1928
  """
1854
1929
  :param shutdown_info: Tuple of the coordination directory (where the
1855
- cache database is) and the cache directory (where the cached data is).
1856
-
1930
+ cache database is) and the cache directory (where the cached data is).
1931
+
1857
1932
  Job local temp directories will be removed due to their appearance in
1858
1933
  the database.
1859
1934
  """
1860
-
1935
+
1861
1936
  coordination_dir, cache_dir = shutdown_info
1862
-
1937
+
1863
1938
  if os.path.isdir(cache_dir):
1864
1939
  # There is a directory to clean up
1865
1940
 
@@ -1877,7 +1952,7 @@ class CachingFileStore(AbstractFileStore):
1877
1952
  # and use that.
1878
1953
  dbFilename = None
1879
1954
  dbAttempt = float('-inf')
1880
-
1955
+
1881
1956
  # We also need to remember all the plausible database files and
1882
1957
  # journals
1883
1958
  all_db_files = []
@@ -1929,7 +2004,7 @@ class CachingFileStore(AbstractFileStore):
1929
2004
  for filename in all_db_files:
1930
2005
  # And delete everything related to the caching database
1931
2006
  robust_rmtree(filename)
1932
-
2007
+
1933
2008
  def __del__(self):
1934
2009
  """
1935
2010
  Cleanup function that is run when destroying the class instance that ensures that all the
@@ -1951,12 +2026,14 @@ class CachingFileStore(AbstractFileStore):
1951
2026
  # Get a cursor
1952
2027
  cur = con.cursor()
1953
2028
 
1954
- # Work out our process name for taking ownership of jobs
2029
+ # We're allowed to assign jobs to us without acquiring the process
2030
+ # identity lock; we know it won't interfere with any of the other logic
2031
+ # happening under our process's identity in the database.
1955
2032
  me = get_process_name(coordination_dir)
1956
2033
 
1957
2034
  # Get all the dead worker PIDs
1958
2035
  workers = []
1959
- for row in cur.execute('SELECT DISTINCT worker FROM jobs WHERE worker IS NOT NULL'):
2036
+ for row in cls._static_read(cur, 'SELECT DISTINCT worker FROM jobs WHERE worker IS NOT NULL'):
1960
2037
  workers.append(row[0])
1961
2038
 
1962
2039
  # Work out which of them are not currently running.
@@ -1969,14 +2046,14 @@ class CachingFileStore(AbstractFileStore):
1969
2046
  # Now we know which workers are dead.
1970
2047
  # Clear them off of the jobs they had.
1971
2048
  for deadWorker in deadWorkers:
1972
- cls._staticWrite(con, cur, [('UPDATE jobs SET worker = NULL WHERE worker = ?', (deadWorker,))])
2049
+ cls._static_write(con, cur, [('UPDATE jobs SET worker = NULL WHERE worker = ?', (deadWorker,))])
1973
2050
  if len(deadWorkers) > 0:
1974
2051
  logger.debug('Reaped %d dead workers', len(deadWorkers))
1975
2052
 
1976
2053
  while True:
1977
2054
  # Find an unowned job.
1978
2055
  # Don't take all of them; other people could come along and want to help us with the other jobs.
1979
- cur.execute('SELECT id FROM jobs WHERE worker IS NULL LIMIT 1')
2056
+ cls._static_read(cur, 'SELECT id FROM jobs WHERE worker IS NULL LIMIT 1')
1980
2057
  row = cur.fetchone()
1981
2058
  if row is None:
1982
2059
  # We cleaned up all the jobs
@@ -1985,10 +2062,10 @@ class CachingFileStore(AbstractFileStore):
1985
2062
  jobID = row[0]
1986
2063
 
1987
2064
  # Try to own this job
1988
- cls._staticWrite(con, cur, [('UPDATE jobs SET worker = ? WHERE id = ? AND worker IS NULL', (me, jobID))])
2065
+ cls._static_write(con, cur, [('UPDATE jobs SET worker = ? WHERE id = ? AND worker IS NULL', (me, jobID))])
1989
2066
 
1990
2067
  # See if we won the race
1991
- cur.execute('SELECT id, tempdir FROM jobs WHERE id = ? AND worker = ?', (jobID, me))
2068
+ cls._static_read(cur, 'SELECT id, tempdir FROM jobs WHERE id = ? AND worker = ?', (jobID, me))
1992
2069
  row = cur.fetchone()
1993
2070
  if row is None:
1994
2071
  # We didn't win the race. Try another one.