__init__.py 14.5 KB
Newer Older
echel0n's avatar
echel0n committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# ##############################################################################
#  Author: echel0n <[email protected]>
#  URL: https://sickrage.ca/
#  Git: https://git.sickrage.ca/SiCKRAGE/sickrage.git
#  -
#  This file is part of SiCKRAGE.
#  -
#  SiCKRAGE is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  -
#  SiCKRAGE is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  -
#  You should have received a copy of the GNU General Public License
#  along with SiCKRAGE.  If not, see <http://www.gnu.org/licenses/>.
# ##############################################################################
echel0n's avatar
echel0n committed
21

echel0n's avatar
echel0n committed
22
__version__ = "10.0.18.dev1"
echel0n's avatar
echel0n committed
23
__install_type__ = ""
24

25
import argparse
echel0n's avatar
echel0n committed
26
import atexit
27
import gettext
28
import os
29
import pathlib
30
import site
31
import subprocess
32
import sys
33
import threading
echel0n's avatar
echel0n committed
34
import time
35
import traceback
echel0n's avatar
echel0n committed
36
from signal import SIGTERM
echel0n's avatar
echel0n committed
37

38
39
import pkg_resources

40
app = None
echel0n's avatar
echel0n committed
41

42
43
MAIN_DIR = os.path.abspath(os.path.realpath(os.path.expanduser(os.path.dirname(os.path.dirname(__file__)))))
PROG_DIR = os.path.abspath(os.path.realpath(os.path.expanduser(os.path.dirname(__file__))))
44
LOCALE_DIR = os.path.join(PROG_DIR, 'locale')
45
LIBS_DIR = os.path.join(PROG_DIR, 'libs')
echel0n's avatar
echel0n committed
46
CHANGELOG_FILE = os.path.join(MAIN_DIR, 'CHANGELOG.md')
echel0n's avatar
echel0n committed
47
REQS_FILE = os.path.join(MAIN_DIR, 'requirements.txt')
echel0n's avatar
echel0n committed
48
CHECKSUM_FILE = os.path.join(PROG_DIR, 'checksums.md5')
49
AUTO_PROCESS_TV_CFG_FILE = os.path.join(*[PROG_DIR, 'autoProcessTV', 'autoProcessTV.cfg'])
50

51

echel0n's avatar
echel0n committed
52
53
class Daemon(object):
    """
echel0n's avatar
echel0n committed
54
    Usage: subclass the Daemon class
echel0n's avatar
echel0n committed
55
56
    """

echel0n's avatar
echel0n committed
57
    def __init__(self, pidfile, working_dir="/"):
echel0n's avatar
echel0n committed
58
59
60
61
        self.stdin = getattr(os, 'devnull', '/dev/null')
        self.stdout = getattr(os, 'devnull', '/dev/null')
        self.stderr = getattr(os, 'devnull', '/dev/null')
        self.pidfile = pidfile
echel0n's avatar
echel0n committed
62
        self.working_dir = working_dir
63
        self.pid = None
echel0n's avatar
echel0n committed
64
65
66
67
68
69
70
71
72
73
74

    def daemonize(self):
        """
        do the UNIX double-fork magic, see Stevens' "Advanced
        Programming in the UNIX Environment" for details (ISBN 0201563177)
        http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
        """
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
75
                os._exit(0)
76
        except OSError as e:
echel0n's avatar
echel0n committed
77
78
79
80
            sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        os.setsid()
81
        os.umask(0)
echel0n's avatar
echel0n committed
82
83
84
85
86
87

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
88
                os._exit(0)
89
        except OSError as e:
echel0n's avatar
echel0n committed
90
91
92
93
            sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        # redirect standard file descriptors
echel0n's avatar
echel0n committed
94
95
96
        sys.stdin = sys.__stdin__
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
echel0n's avatar
echel0n committed
97
98
        sys.stdout.flush()
        sys.stderr.flush()
99
100
        si = open(self.stdin, 'r')
        so = open(self.stdout, 'a+')
101
        se = open(self.stderr, 'a+')
echel0n's avatar
echel0n committed
102
103
104
105
106
107
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # write pidfile
        atexit.register(self.delpid)
108
        self.pid = os.getpid()
109
        open(self.pidfile, 'w+').write("%s\n" % self.pid)
echel0n's avatar
echel0n committed
110
111
112
113
114
115
116
117
118
119
120

    def delpid(self):
        if os.path.exists(self.pidfile):
            os.remove(self.pidfile)

    def start(self):
        """
        Start the daemon
        """
        # Check for a pidfile to see if the daemon already runs
        try:
121
            pf = open(self.pidfile, 'r')
echel0n's avatar
echel0n committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if pid:
            message = "pidfile %s already exist. Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)

        # Start the daemon
        self.daemonize()

    def stop(self):
        """
        Stop the daemon
        """

        # Get the pid from the pidfile
        try:
142
            pf = open(self.pidfile, 'r')
echel0n's avatar
echel0n committed
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if not pid:
            message = "pidfile %s does not exist. Daemon not running?\n"
            sys.stderr.write(message % self.pidfile)
            return  # not an error in a restart

        # Try killing the daemon process
        try:
            while 1:
                os.kill(pid, SIGTERM)
                time.sleep(0.1)
158
        except OSError as err:
echel0n's avatar
echel0n committed
159
160
161
162
163
164
165
            err = str(err)
            if err.find("No such process") > 0:
                self.delpid()
            else:
                sys.exit(1)


166
def isElevatedUser():
167
    try:
168
        return os.getuid() == 0
169
    except AttributeError:
170
171
        import ctypes
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
172
173


174
def isVirtualEnv():
175
    return hasattr(sys, 'real_prefix')
176
177


178
179
def check_requirements():
    if os.path.exists(REQS_FILE):
180
181
182
183
184
185
186
187
188
189
190
191
        with open(REQS_FILE) as f:
            for line in f.readlines():
                try:
                    req_name, req_version = line.strip().split('==')
                    if not pkg_resources.get_distribution(req_name).version == req_version:
                        print('Updating requirement {} to {}'.format(req_name, req_version))
                        subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-deps", "--no-cache-dir", line.strip()])
                except pkg_resources.DistributionNotFound:
                    print('Installing requirement {}'.format(line.strip()))
                    subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-deps", "--no-cache-dir", line.strip()])
                except ValueError:
                    continue
192

193

echel0n's avatar
echel0n committed
194
195
def file_cleanup(remove=False):
    valid_files = []
196
    exempt_files = [pathlib.Path(CHECKSUM_FILE), pathlib.Path(AUTO_PROCESS_TV_CFG_FILE)]
echel0n's avatar
echel0n committed
197
198
199
200
201
202

    if not os.path.exists(CHECKSUM_FILE):
        return

    with open(CHECKSUM_FILE, "rb") as fp:
        for line in fp.readlines():
203
204
            file, checksum = line.decode().strip().split(' = ')
            full_filename = pathlib.Path(MAIN_DIR).joinpath(file)
echel0n's avatar
echel0n committed
205
206
207
208
            valid_files.append(full_filename)

    for root, dirs, files in os.walk(PROG_DIR):
        for file in files:
209
            full_filename = pathlib.Path(root).joinpath(file)
210

211
            if full_filename in exempt_files or full_filename.suffix == '.pyc':
212
213
214
                continue

            if full_filename not in valid_files and PROG_DIR in str(full_filename):
echel0n's avatar
echel0n committed
215
216
                try:
                    if remove:
217
218
                        print('Found unwanted file {}, removed!'.format(full_filename))
                        full_filename.unlink()
echel0n's avatar
echel0n committed
219
220
221
222
223
224
                    else:
                        print('Found unwanted file {}, you should delete this file manually!'.format(full_filename))
                except OSError:
                    print('Unable to delete filename {} during cleanup, you should delete this file manually!'.format(full_filename))


225
226
def version():
    # Get the version number
echel0n's avatar
echel0n committed
227
    return __version__
228
229


230
231
def changelog():
    # Get the version number
232
    with open(CHANGELOG_FILE) as f:
233
234
235
        return f.read()


236
def main():
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
    global app

    # set thread name
    threading.currentThread().setName('MAIN')

    # fix threading time bug
    time.strptime("2012", "%Y")

    # add sickrage libs path to python system path
    if not (LIBS_DIR in sys.path):
        sys.path, remainder = sys.path[:1], sys.path[1:]
        site.addsitedir(LIBS_DIR)
        sys.path.extend(remainder)

    # set system default language
252
    gettext.install('messages', LOCALE_DIR, codeset='UTF-8', names=["ngettext"])
253

echel0n's avatar
echel0n committed
254
255
256
257
    # sickrage startup options
    parser = argparse.ArgumentParser(prog='sickrage')
    parser.add_argument('-v', '--version',
                        action='version',
echel0n's avatar
echel0n committed
258
                        version=version())
echel0n's avatar
echel0n committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
    parser.add_argument('-d', '--daemon',
                        action='store_true',
                        help='Run as a daemon (*NIX ONLY)')
    parser.add_argument('-q', '--quiet',
                        action='store_true',
                        help='Disables logging to CONSOLE')
    parser.add_argument('-p', '--port',
                        default=0,
                        type=int,
                        help='Override default/configured port to listen on')
    parser.add_argument('-H', '--host',
                        default='',
                        help='Override default/configured host to listen on')
    parser.add_argument('--dev',
                        action='store_true',
                        help='Enable developer mode')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Enable debugging')
    parser.add_argument('--datadir',
                        default=os.path.abspath(os.path.join(os.path.expanduser("~"), '.sickrage')),
                        help='Overrides data folder for database, config, cache and logs (specify full path)')
    parser.add_argument('--config',
                        default='config.ini',
                        help='Overrides config filename (specify full path and filename if outside datadir path)')
    parser.add_argument('--pidfile',
                        default='sickrage.pid',
                        help='Creates a PID file (specify full path and filename if outside datadir path)')
    parser.add_argument('--no_clean',
                        action='store_true',
                        help='Suppress cleanup of files not present in checksum.md5')
    parser.add_argument('--nolaunch',
                        action='store_true',
                        help='Suppress launching web browser on startup')
    parser.add_argument('--disable_updates',
                        action='store_true',
                        help='Disable application updates')
    parser.add_argument('--web_root',
                        default='',
                        type=str,
                        help='Overrides URL web root')
    parser.add_argument('--db_type',
                        default='sqlite',
                        help='Database type: sqlite or mysql')
    parser.add_argument('--db_prefix',
                        default='sickrage',
                        help='Database prefix you want prepended to database table names')
    parser.add_argument('--db_host',
                        default='localhost',
                        help='Database hostname (not used for sqlite)')
    parser.add_argument('--db_port',
                        default='3306',
                        help='Database port number (not used for sqlite)')
    parser.add_argument('--db_username',
                        default='sickrage',
                        help='Database username (not used for sqlite)')
    parser.add_argument('--db_password',
                        default='sickrage',
                        help='Database password (not used for sqlite)')

    # Parse startup args
    args = parser.parse_args()

322
323
324
325
    # sickrage requires python 3.6+
    if sys.version_info < (3, 6, 0):
        sys.exit("Sorry, SiCKRAGE requires Python 3.6+")

326
    # check lib requirements
327
328
    if __install_type__ not in ['windows', 'synology', 'docker', 'qnap', 'readynas', 'pip']:
        check_requirements()
329

echel0n's avatar
echel0n committed
330
    # cleanup unwanted files
331
    file_cleanup(remove=not args.no_clean)
echel0n's avatar
echel0n committed
332

333
    try:
echel0n's avatar
echel0n committed
334
        from sickrage.core import Core
335

336
337
338
        # main app instance
        app = Core()

echel0n's avatar
echel0n committed
339
        app.quiet = args.quiet
340
        app.web_host = args.host
341
        app.web_port = int(args.port)
342
        app.web_root = args.web_root.lstrip('/').rstrip('/')
343
        app.no_launch = args.nolaunch
344
        app.disable_updates = args.disable_updates
345
        app.developer = args.dev
346
347
348
349
350
351
        app.db_type = args.db_type
        app.db_prefix = args.db_prefix
        app.db_host = args.db_host
        app.db_port = args.db_port
        app.db_username = args.db_username
        app.db_password = args.db_password
352
353
354
355
        app.debug = args.debug
        app.data_dir = os.path.abspath(os.path.realpath(os.path.expanduser(args.datadir)))
        app.cache_dir = os.path.abspath(os.path.realpath(os.path.join(app.data_dir, 'cache')))
        app.config_file = args.config
echel0n's avatar
echel0n committed
356
357
        daemonize = (False, args.daemon)[not sys.platform == 'win32']
        pid_file = args.pidfile
358

359
360
        if not os.path.isabs(app.config_file):
            app.config_file = os.path.join(app.data_dir, app.config_file)
361

362
        if not os.path.isabs(pid_file):
echel0n's avatar
echel0n committed
363
            pid_file = os.path.join(app.data_dir, pid_file)
364
365
366
367
368
369
370

        # add sickrage module to python system path
        if not (PROG_DIR in sys.path):
            sys.path, remainder = sys.path[:1], sys.path[1:]
            site.addsitedir(PROG_DIR)
            sys.path.extend(remainder)

371
        # Make sure that we can create the data dir
372
        if not os.access(app.data_dir, os.F_OK):
373
            try:
374
                os.makedirs(app.data_dir, 0o744)
375
            except os.error:
376
                sys.exit("Unable to create data directory '" + app.data_dir + "'")
377
378

        # Make sure we can write to the data dir
379
380
        if not os.access(app.data_dir, os.W_OK):
            sys.exit("Data directory must be writeable '" + app.data_dir + "'")
381

382
        # Make sure that we can create the cache dir
383
        if not os.access(app.cache_dir, os.F_OK):
384
            try:
385
                os.makedirs(app.cache_dir, 0o744)
386
            except os.error:
387
                sys.exit("Unable to create cache directory '" + app.cache_dir + "'")
388
389

        # Make sure we can write to the cache dir
390
391
        if not os.access(app.cache_dir, os.W_OK):
            sys.exit("Cache directory must be writeable '" + app.cache_dir + "'")
392

echel0n's avatar
echel0n committed
393
        # daemonize if requested
echel0n's avatar
echel0n committed
394
        if daemonize:
395
            app.no_launch = True
echel0n's avatar
echel0n committed
396
            app.quiet = True
echel0n's avatar
echel0n committed
397
            app.daemon = Daemon(pid_file, app.data_dir)
398
            app.daemon.daemonize()
399
            app.pid = app.daemon.pid
echel0n's avatar
echel0n committed
400

401
        # start app
402
        app.start()
echel0n's avatar
echel0n committed
403
    except (SystemExit, KeyboardInterrupt):
404
405
        if app:
            app.shutdown()
echel0n's avatar
echel0n committed
406
407
408
409
410
411
412
413
    except Exception as e:
        # attempt to send exception to sentry
        try:
            import sentry_sdk
            sentry_sdk.capture_exception(e)
        except ImportError:
            pass

414
        traceback.print_exc()
415

416

echel0n's avatar
echel0n committed
417
418
if __name__ == '__main__':
    main()