summaryrefslogtreecommitdiffhomepage
path: root/bazarr.py
blob: afb9b52c9cd90bf5fd63e8b54c9014a8361cd030 (plain)
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
# coding=utf-8

from __future__ import absolute_import
from __future__ import print_function

import bazarr.libs
from six import PY3
import subprocess as sp
import time
import os
import sys
import platform
import re
import signal

from bazarr.get_args import args


def check_python_version():
    python_version = platform.python_version_tuple()
    minimum_python_version_tuple = (2, 7, 13)
    minimum_python3_version_tuple = (3, 6, 0)
    minimum_python_version = ".".join(str(i) for i in minimum_python_version_tuple)
    minimum_python3_version = ".".join(str(i) for i in minimum_python3_version_tuple)

    if int(python_version[0]) == minimum_python3_version_tuple[0]:
        if int(python_version[1]) >= minimum_python3_version_tuple[1]:
            pass
        else:
            print("Python " + minimum_python3_version + " or greater required. Current version is " + platform.python_version() + ". Please upgrade Python.")
            os._exit(0)

    elif int(python_version[1]) < minimum_python_version_tuple[1] or int(re.search(r'\d+', python_version[2]).group()) < minimum_python_version_tuple[2]:
        print("Python " + minimum_python_version + " or greater required. Current version is " + platform.python_version() + ". Please upgrade Python.")
        os._exit(0)


check_python_version()

dir_name = os.path.dirname(__file__)


class ProcessRegistry:

    def register(self, process):
        pass

    def unregister(self, process):
        pass


class DaemonStatus(ProcessRegistry):

    def __init__(self):
        self.__should_stop = False
        self.__processes = set()

    def register(self, process):
        self.__processes.add(process)

    def unregister(self, process):
        self.__processes.remove(process)

    '''
    Waits all the provided processes for the specified amount of time in seconds.
    '''
    @staticmethod
    def __wait_for_processes(processes, timeout):
        reference_ts = time.time()
        elapsed = 0
        remaining_processes = list(processes)
        while elapsed < timeout and len(remaining_processes) > 0:
            remaining_time = timeout - elapsed
            for ep in list(remaining_processes):
                if ep.poll() is not None:
                    remaining_processes.remove(ep)
                else:
                    if remaining_time > 0:
                        if PY3:
                            try:
                                ep.wait(remaining_time)
                                remaining_processes.remove(ep)
                            except sp.TimeoutExpired:
                                pass
                        else:
                            '''
                            In python 2 there is no such thing as some mechanism to wait with a timeout.
                            '''
                            time.sleep(1)
                        elapsed = time.time() - reference_ts
                        remaining_time = timeout - elapsed
        return remaining_processes

    '''
    Sends to every single of the specified processes the given signal and (if live_processes is not None) append to it processes which are still alive.
    '''
    @staticmethod
    def __send_signal(processes, signal_no, live_processes=None):
        for ep in processes:
            if ep.poll() is None:
                if live_processes is not None:
                    live_processes.append(ep)
                try:
                    ep.send_signal(signal_no)
                except Exception as e:
                    print('Failed sending signal %s to process %s because of an unexpected error: %s' % (signal_no, ep.pid, e))
        return live_processes

    '''
    Flags this instance as should stop and terminates as smoothly as possible children processes.
    '''
    def stop(self):
        self.__should_stop = True
        live_processes = DaemonStatus.__send_signal(self.__processes, signal.SIGINT, list())
        live_processes = DaemonStatus.__wait_for_processes(live_processes, 120)
        DaemonStatus.__send_signal(live_processes, signal.SIGTERM)

    def should_stop(self):
        return self.__should_stop
    
    
def start_bazarr(process_registry=ProcessRegistry()):
    script = [sys.executable, "-u", os.path.normcase(os.path.join(dir_name, 'bazarr', 'main.py'))] + sys.argv[1:]
    
    ep = sp.Popen(script, stdout=sp.PIPE, stderr=sp.STDOUT, stdin=sp.PIPE)
    process_registry.register(ep)
    print("Bazarr starting...")
    try:
        while True:
            line = ep.stdout.readline()
            if line == '' or not line:
                # Process ended so let's unregister it
                process_registry.unregister(ep)
                break
            if PY3:
                sys.stdout.buffer.write(line)
            else:
                sys.stdout.write(line)
            sys.stdout.flush()
    except KeyboardInterrupt:
        pass


if __name__ == '__main__':
    restartfile = os.path.normcase(os.path.join(args.config_dir, 'bazarr.restart'))
    stopfile = os.path.normcase(os.path.join(args.config_dir, 'bazarr.stop'))
    
    try:
        os.remove(restartfile)
    except:
        pass
    
    try:
        os.remove(stopfile)
    except:
        pass
    
    
    def daemon(daemonStatus):
        if os.path.exists(stopfile):
            try:
                os.remove(stopfile)
            except:
                print('Unable to delete stop file.')
            else:
                print('Bazarr exited.')
                os._exit(0)
        
        if os.path.exists(restartfile):
            try:
                os.remove(restartfile)
            except:
                print('Unable to delete restart file.')
            else:
                start_bazarr(daemonStatus)
    
    
    daemonStatus = DaemonStatus()
    
    def shutdown():
        # indicates that everything should stop
        daemonStatus.stop()
        # emulate a Ctrl C command on itself (bypasses the signal thing but, then, emulates the "Ctrl+C break")
        os.kill(os.getpid(), signal.SIGINT)
    
    signal.signal(signal.SIGTERM, lambda signal_no, frame: shutdown())
    start_bazarr(daemonStatus)
    
    # Keep the script running forever until stop is requested through term or keyboard interrupt
    while not daemonStatus.should_stop():
        daemon(daemonStatus)
        time.sleep(1)