engine-core.py 5.75 KB
Newer Older
1
#!/usr/bin/env python3.7
2
3

#
David Trattnig's avatar
David Trattnig committed
4
5
6
# Aura Engine (https://gitlab.servus.at/aura/engine)
#
# Copyright (C) 2017-2020 - The Aura Engine Team.
7
8
9
10
11
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
David Trattnig's avatar
David Trattnig committed
12
#
13
14
15
16
# This program 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 Affero General Public License for more details.
David Trattnig's avatar
David Trattnig committed
17
#
18
19
20
21
22
23
24
25
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import os
import sys
import signal
import logging
26
import subprocess
27

28
29
from flask               import Flask
from flask_sqlalchemy    import SQLAlchemy
30
31
32

from modules.base.logger import AuraLogger
from modules.base.config import AuraConfig
33
from modules.base.utils  import SimpleUtil
34
35
36
37
38
39
40
41
42
43
44
45
46


config = AuraConfig()
def configure_flask():
    app.config["SQLALCHEMY_DATABASE_URI"] = config.get_database_uri()
    app.config['BABEL_DEFAULT_LOCALE'] = 'de'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# FIXME Instatiate SQLAlchemy without the need for Flask
app = Flask(__name__)
configure_flask()
DB = SQLAlchemy(app)

47
48

class AuraEngine:
49
    """
50
51
52
53
54
    AuraEngine does the following:

    1. Initialize the soundsystem and scheduler
    2. Initialize Redis
    3. Start Liquidsoap in a separate thread which connects to the engine
55
56
57
58
59
60
61

    """
    logger = None
    config = None
    server = None
    messenger = None
    controller = None
62
    soundsystem = None
63
    scheduler = None
64
    lqs = None
65
66
    lqs_startup = None

67
68
69
70


    def __init__(self):
        """
71
        Initializes Engine Core.
72
73
74
75
        """
        self.config = config


76
77

    def startup(self, lqs_startup):
78
        """
79
        Starts Engine Core.
80
        """
81
82
83
        AuraLogger(self.config)
        self.logger = logging.getLogger("AuraEngine")

84
85
        from modules.scheduling.scheduler import AuraScheduler
        from modules.core.engine import SoundSystem
David Trattnig's avatar
David Trattnig committed
86
        from modules.cli.redis.adapter import ServerRedisAdapter
87

88
89
90
        # If Liquidsoap should be started automatically
        self.lqs_startup = lqs_startup

91
92
        # Check if the database has to be re-created
        if self.config.get("recreate_db") is not None:
93
            AuraScheduler(self.config, None, None)
94
95
96

        # Create scheduler and Liquidsoap communicator
        self.soundsystem = SoundSystem(self.config)
97
        self.scheduler = AuraScheduler(self.config, self.soundsystem, self.on_initialized)
98
99
100
101
102
103
104
105
106
107
108

        # Create the Redis adapter
        self.messenger = ServerRedisAdapter(self.config)
        self.messenger.scheduler = self.scheduler
        self.messenger.soundsystem = self.soundsystem

        # And finally wait for redis message / start listener thread
        self.messenger.start()



109
110
111
112
113
    def on_initialized(self):
        """
        Called when the engine is initialized, before the Liquidsoap connection is established."
        """
        self.logger.info(SimpleUtil.green("Engine Core initialized - Waiting for Liquidsoap connection ..."))
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
        if self.lqs_startup:
            self.start_lqs(False, False)
        else:
            self.logger.info(SimpleUtil.yellow("Please note, Liquidsoap needs to be started manually."))


    def start_lqs(self, debug_output, verbose_output):
        """
        Starts Liquidsoap.
        """
        lqs_path = self.config.get("liquidsoap_path")
        lqs_cwd = os.getcwd() + "/" + self.config.get("liquidsoap_working_dir")
        lqs_output = ""
        lqs_output = self.get_debug_flags(debug_output, verbose_output)

        self.lqs = subprocess.Popen([lqs_path, lqs_output, "engine.liq"], \
            cwd=lqs_cwd, \
            stdout=subprocess.PIPE, \
            shell=False)



    def get_lqs_cmd(self, debug_output, verbose_output):
        """
        Returns a shell command string to start Liquidsoap
        """
        lqs_path = self.config.get("liquidsoap_path")
        lqs_cwd = os.getcwd() + "/" + self.config.get("liquidsoap_working_dir")
        lqs_output = self.get_debug_flags(debug_output, verbose_output)
        return "(cd %s && %s %s ./engine.liq)" % (lqs_cwd, lqs_path, lqs_output)



    def get_debug_flags(self, debug_output, verbose_output):
        """
David Trattnig's avatar
David Trattnig committed
149
        Build Liquidsoap debug parameters.
150
151
152
153
154
155
156
        """
        output = ""
        if debug_output:
            output += "--debug " 
        if verbose_output:
            output += "--verbose "
        return output
157
158
159
160
161



    def exit_gracefully(self, signum, frame):
        """
162
        Shutdown of the engine. Also terminates the Liquidsoap thread.
163
        """
164
165
166
167
168
169
170
        if self.lqs:
            self.lqs.terminate()
            self.logger.info("Terminated Liquidsoap")

        if self.messenger:
            self.messenger.terminate()
        
David Trattnig's avatar
David Trattnig committed
171
        self.logger.info("Gracefully terminated Aura Engine! (signum:%s, frame:%s)" % (signum, frame))
172
        sys.exit(0)        
173
174
175



176
177
178
179
180
#
# START THE ENGINE
#


181
if __name__ == "__main__":        
182

183
    engine = AuraEngine()
David Trattnig's avatar
David Trattnig committed
184
    start_lqs = True
185
    lqs_cmd = False
186
187
188

    signal.signal(signal.SIGINT, engine.exit_gracefully)
    signal.signal(signal.SIGTERM, engine.exit_gracefully)
189
190

    if len(sys.argv) >= 2:
191
        if "--without-lqs" in sys.argv:
David Trattnig's avatar
David Trattnig committed
192
            start_lqs = False
193
194
        if "--get-lqs-command" in sys.argv:
            lqs_cmd = True
195
        if "--use-test-data" in sys.argv:
196
            engine.config.set("use_test_data", True)
197
        if "--recreate-database" in sys.argv:
198
            engine.config.set("recreate_db", True)
199

200
201
202
    if lqs_cmd:
        print(engine.get_lqs_cmd(True, True))
    else:
David Trattnig's avatar
David Trattnig committed
203
        engine.startup(start_lqs)