-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsync.py
executable file
·199 lines (163 loc) · 5.67 KB
/
rsync.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#!/usr/bin/env python3
import os
import signal
import subprocess
import threading
from colored import fg, attr
from pathlib import Path
class Logger:
COLORS = [
fg(1), # red
fg(2), # green
fg(3), # yellow
fg(4), # blue
fg(5), # magenta
fg(6), # cyan
]
COLORS_SIZE = len(COLORS)
NAME_LENGTH = 5
RESET = attr(0)
__index = 0
__lock = threading.Semaphore()
@staticmethod
def get(name):
color = Logger.COLORS[Logger.__index % Logger.COLORS_SIZE]
Logger.__index += 1
return Logger(name, color)
def __init__(self, name, color):
name = name.rjust(Logger.NAME_LENGTH, " ")
self.__prefix = "[%s%s%s] " % (color, name, Logger.RESET)
def log(self, line, end="\n"):
if isinstance(line, bytes):
line = line.decode()
with Logger.__lock:
print(self.__prefix + line, end=end)
def stdout(self, line, end="\n"):
self.log(line, end=end)
def stderr(self, line, end="\n"):
if isinstance(line, bytes):
line = line.decode()
line = "%s%s%s" % (fg(1), line, Logger.RESET)
self.log(line, end=end)
class Cmd:
@staticmethod
def process(io, logger):
for line in io:
logger(line, end="")
def __init__(self, logger, *args, **kwargs):
self.__logger = logger
self.__args = args
self.__kwargs = kwargs
self.__process = None
def run(self):
env = self.__kwargs.pop("env", None)
if env:
env = os.environ.update(env)
cwd = self.__kwargs.pop("cwd", None)
# self.__logger.log(" ".join(self.__args))
self.__process = subprocess.Popen(self.__args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=env,
cwd=cwd)
threads = [
threading.Thread(target=Cmd.process, args=[self.__process.stdout,
self.__logger.stdout]),
threading.Thread(target=Cmd.process,
args=[self.__process.stderr, self.__logger.stderr])
]
stdin = self.__kwargs.get("stdin")
if stdin:
self.__process.stdin.write(stdin)
[thread.start() for thread in threads]
retcode = self.__process.wait()
for thread in threads:
thread.join()
self.__process = None
# self.__logger.log(" ".join(self.__args) + ": " + str(retcode))
if retcode:
raise subprocess.CalledProcessError(retcode, self.__args)
def signal(self, signal=signal.SIGTERM):
if self.__process:
try:
self.__process.send_signal(signal)
except:
pass
@staticmethod
def rsync(logger, *args):
cmd = ["rsync", "-r", "--info=name", "--partial", "--inplace", "--delete",
"--chown=stream:www-data", "--chmod=ug=rwX,o=rX",
"-e", "ssh -o ControlMaster=no -o ControlPath=none"] \
+ list(args)
return Cmd(logger, *cmd)
class Loop(threading.Thread):
def __init__(self, logger, cmd):
super().__init__()
self.__logger = logger
# if not isinstance(cmd, Cmd):
# cmd = Cmd(self.__logger, cmd)
self.__cmd = cmd
self.__current = None
self.__event = threading.Event()
self.__running = False
def run(self):
self.__running = True
while self.__running:
try:
# self.__logger.stdout("Run")
for cmd in self.__cmd:
self.__current = cmd.run()
self.__current = None
# self.__logger.stdout("Sleep")
self.__event.clear()
self.__event.wait(1)
# self.__logger.stdout("End sleep")
except:
pass
# finally:
# self.__logger.stdout("Runned")
# self.__logger.stdout("Exit")
def stop(self):
if self.__running:
# self.__logger.stdout("Stopping")
self.__running = False
if self.__current:
self.__current.signal()
self.__event.set()
# self.__logger.stdout("Stopping ok")
self.join()
# self.__logger.stdout("Stopped")
class Stream(Loop):
def __init__(self, name, target):
logger = Logger.get(name)
folder = os.path.join("stream", name) + "/"
target_stream = os.path.join(target, name) + "/"
cmd1 = Cmd.rsync(logger, folder, target_stream)
index = os.path.join("stream", name + ".m3u8")
cmd2 = Cmd.rsync(logger, index, target)
super().__init__(logger, [cmd1, cmd2])
class Streams:
NAMES = ["360p", "480p", "720p", "1080p", "audio"]
# NAMES = ["1080p"]
def __init__(self, target):
self.__streams = []
for name in Streams.NAMES:
folder = os.path.join("stream", name)
if Path(folder).is_dir():
stream = Stream(name, target)
self.__streams.append(stream)
def start(self):
for stream in self.__streams:
stream.start()
def stop(self):
for stream in self.__streams:
stream.stop()
if __name__ == "__main__":
lock = threading.Event()
streams = Streams("rabbit:/var/www/stream/stream2")
def signal_handler(_1, _2):
streams.stop()
lock.set()
signal.signal(signal.SIGINT, signal_handler)
streams.start()
lock.wait()