]> git.treefish.org Git - photosort.git/blob - src/bunch.py
fixing bunch creation
[photosort.git] / src / bunch.py
1 import logging
2 import os
3 import time
4 import threading
5
6 from dirtrigger import DirTrigger
7 from migrator import Migrator
8
9 class Bunch:
10     class TriggeredSource:
11         def __init__(self, idx, trigger, migrator, cleanup):
12             self.idx = idx
13             self.trigger = trigger
14             self.migrator = migrator
15             self.cleanup = cleanup
16
17     def __init__(self, idx, cache_dir, cfg):
18         self._idx = idx
19         source_idx = 1
20         self._sources = []
21         for src_dir_cfg in cfg['src_dirs']:
22             reg_db = os.path.join(cache_dir, "reg_%d_%d.db" % (idx, source_idx))
23             self._sources.append(
24                 Bunch.TriggeredSource(
25                     source_idx,
26                     DirTrigger(src_dir_cfg['path'], src_dir_cfg['cool_time'],
27                                src_dir_cfg['max_time']),
28                     Migrator(src_dir_cfg['path'], cfg['dst_dir']['path'], reg_db),
29                     src_dir_cfg['cleanup']
30                 )
31             )
32             source_idx += 1
33         logging.info("Created bunch #%d with %d sources.", self._idx, len(self._sources))
34
35     def start(self):
36         logging.info("Starting bunch #%d...", self._idx)
37         self._stop = False
38         self._worker_thread = threading.Thread(target=self._worker)
39         self._worker_thread.start()
40
41     def stop(self):
42         logging.info("Stopping bunch #%d...", self._idx)
43         self._stop = True
44         self._worker_thread.join()
45         logging.info("Stopped bunch #%d.", self._idx)
46
47     def is_running(self):
48         return self._worker_thread.is_alive()
49
50     def _worker(self):
51         for src in self._sources:
52             src.trigger.start()
53
54         while not self._stop:
55             for src in self._sources:
56                 try:
57                     if src.trigger.is_triggering():
58                         logging.info("Got trigger for source #%d.%d.", self._idx, src.idx)
59                         before = time.time()
60                         src.trigger.reset()
61                         src.migrator.migrate(src.cleanup)
62                         if src.cleanup:
63                             src.migrator.cleanup()
64                         logging.info("Migration took %.1fs for source #%d.%d.",
65                                      time.time() - before, self._idx, src.idx)
66                 except Exception as e:
67                     logging.error("Error migrating source #%d.%d: %s",
68                                   self._idx, src.idx, str(e))
69             time.sleep(10.0)
70
71         for src in self._sources:
72             src.trigger.stop()