File size: 5,289 Bytes
0936134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
from rngcache import RandomFileCache
cache = RandomFileCache(rootdir, cache_size=200) # 200MB cache
cache.start()
# ...
with cache.get_random_file() as file_path:
    # load file ... cPickle.load(open(file_path,"rb")) ...
# ...
cache.terminate()
"""

import signal
import ctypes
import shutil
import random
import os
from time import time, sleep
import multiprocessing as mp
from glob import glob


class RandomFileCache(object):
    def __init__(self,
                 root_dir,
                 cache_size, #in MB
                 cache_dir="/dev/shm/",
                 max_files=10000
                 ):
        if not root_dir.endswith("/"): root_dir += "/"
        self.cache_dir = cache_dir
        self.root_dir = root_dir
        self.max_MB = cache_size
        self.max_files = max_files
        self.init = False

    def start(self):
        self.is_terminated = mp.Value(ctypes.c_bool, False)
        self.cache_ready = mp.Event()

        self.files = glob(self.root_dir+"*")
        manager = mp.Manager()
        self.cache = manager.list()

        self.cache_dir += "rngcache"+str(time())+"/"
        os.mkdir(self.cache_dir)

        # locks can't be made on the fly (not pickable), so allocate a bunch of them
        self.locks = [mp.Lock() for _ in range(self.max_files)]
        self.lock_idxs = range(self.max_files) # lock references

        self.job = mp.Process(target=self._cache_process)
        self.job.daemon = True
        self.job.start()

        signal.signal(signal.SIGINT, self.terminate)
        signal.signal(signal.SIGTERM, self.terminate)

        self.init = True

    def get_random_file(self):
        self.cache_ready.wait()
        tries = 0
        while tries < 100:
            try: entry = random.choice(self.cache)
            except:
                if self.is_terminated.value: return None
                tries += 1
                sleep(0.01)
                continue
            lock = self.locks[entry["lock"]]
            if not lock.acquire(False): continue # is locked, go to next
            cached_file = CachedFile(self.cache_dir + entry["key"])
            cached_file.set_lock(lock)
            return cached_file # extension of string
        raise Exception("Failed to get random file")

    def _cache_process(self):
        try: self.cache_process()
        except Exception as e: print e
        finally: self.terminate()

    def cache_process(self):
        self.size = 0
        while not self.is_terminated.value:
            file = random.choice(self.files)
            file_size = os.path.getsize(file) >> 20

            # if not enough space, remove a random entry
            if self.size + file_size > self.max_MB:
                self.cache_ready.set()
                self.remove_entry()
                continue

            key = os.path.basename(file)

            # don't allow duplicates
            if self.contains(key): continue

            shutil.copyfile(file, self.cache_dir+key)
            self.size += file_size
            self.cache.append( {"key":key, "lock":self.lock_idxs.pop(0)} )

    def remove_entry(self):
        if len(self.cache) == 0: return
        while True:
            for i, entry in enumerate(self.cache):

                # lock entry
                lock_idx = entry["lock"]
                lock = self.locks[lock_idx]
                if not lock.acquire(False): continue

                file = self.cache_dir+entry["key"]
                self.size -= os.path.getsize(file) >> 20

                # remove file
                os.remove(file)
                del self.cache[i]
                self.lock_idxs.append(lock_idx)
                lock.release()
                return
            sleep(0.01)

    def contains(self, key):
        for entry in self.cache:
            if entry["key"] == key: return True
        return False

    def terminate(self, sig=None, frame=None):
        try:
            if not self.init or self.is_terminated.value: return
            self.is_terminated.value = True
            for lock in self.locks:
                try: lock.release()
                except ValueError: pass
            self.job.join(timeout=5)
            try:self.job.terminate()
            except: pass
        finally:
            if os.path.exists(self.cache_dir):
                shutil.rmtree(self.cache_dir)


class CachedFile(str):
    def set_lock(self, lock): self.lock = lock
    def __enter__(self): return self
    def __exit__(self, type, value, traceback):
        try: self.lock.release()
        except ValueError: pass


if __name__ == '__main__':
    import yaml
    from moviepy.editor import VideoFileClip
    os.chdir("..")
    with open("paths.yaml", "r") as f: PATH = yaml.load(f)
    cache = RandomFileCache(PATH["preproc"] + "25fps_crf28", cache_size=200)
    cache.start()
    print len(cache.files)

    for i in range(10):
        with cache.get_random_file() as file:
            print file
            print cache.cache
            clip = VideoFileClip(file)
            clip.preview()

            # for l in cache.locks:
            #     if not l.acquire(False):
            #         count += 1
            #         continue
            #     l.release()
            # print count, "locked"
    cache.terminate()