Blame view

pyros.py 27.8 KB
4816e86b   Jeremy   removed *.sh *.ba...
1
2
3
4
5
6
7
import sys
import os
import subprocess
import platform
import fileinput
import argparse
import time
bca9a283   Jeremy   Reworked the sche...
8
import signal
4816e86b   Jeremy   removed *.sh *.ba...
9
10
11

DEBUG = False

257abe9b   Jeremy   Added comments
12
13
14
15
16
'''
    Pyros Manager, able to launch processes and handle all project commands
'''


4816e86b   Jeremy   removed *.sh *.ba...
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
class Utils:
    system = platform.system()
    columns = 100
    row = 1000
    disp = True

    def __init__(self):
        if (platform.system() != 'Windows'):
            try:
                rows, columns = os.popen('stty size', 'r').read().split()
                self.columns = int(columns)
            except:
                self.columns = 100
                if DEBUG:
                    print("Could not get terminal size")

    def printFullTerm(self, color, string):
        value = int(self.columns / 2 - len(string) / 2)
        self.printColor(color, "-" * value, eol='')
        self.printColor(color, string, eol='')
        value += len(string)
        self.printColor(color, "-" * (self.columns - value))
        return 0

    def changeDirectory(self, path):
        if DEBUG:
            print("Moving to : " + path)
        os.chdir(path)
        if DEBUG:
            print("Current directory : " + str(os.getcwd()))
        return 0

    def replacePatternInFile(self, pattern, replace, file_path):
        try:
            with fileinput.FileInput(file_path, inplace=True, backup='.bak') as file:
                for line in file:
                    print(line.replace(pattern, replace), end='')
        except:
            return 1
        return 0

    def printColor(self, color, message, file=sys.stdout, eol=os.linesep, forced=False):
        if (self.disp == False and forced == False):
            return 0
        if (self.system == 'Windows'):
            print(message, file=file, end=eol)
        else:
            print(color + message + Colors.ENDC, file=file, end=eol)
        return 0

    def askQuestion(self, message, default = ""):
        self.printColor(Colors.BLUE, message, forced=True)
        self.printColor(Colors.BOLD, "Answer (default="+default+"): ", eol='', forced=True)
        sys.stdout.flush()
27e81f38   jeremy   Update windows
71
        ret = sys.stdin.readline().replace('\n', '').replace('\r', '')
4816e86b   Jeremy   removed *.sh *.ba...
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
        if ret == "":
            return default
        return ret

    def sleep(self, t):
        time.sleep(t)
        return 0

'''
    Manager class : manager of your project
'''


class AManager(Utils):
    path = os.path.realpath(__file__)
    path_dir = os.getcwd()
    path_dir_file = os.path.dirname(os.path.realpath(__file__))
    python_path = sys.executable
    python_version = sys.version_info

    bin_dir = ""
    celery = "celery"
    venv_pip = "pip"
    venv_bin = "python"
    wait = True
    current_command = ""
    config = None
    commandMatcher = {}
    commandDescription = {}
    commands = []
    errors = {}
    executed = {}
bca9a283   Jeremy   Reworked the sche...
104
    subproc = []
4816e86b   Jeremy   removed *.sh *.ba...
105
106
107
108
109
110
111
112

    def __init__(self, param):
        super(AManager, self).__init__()
        self.wait = param.getWait()
        self.commands = param.getCommandList()
        self.disp = param.getPrint()
        config = param.getConfig()
        self.config = config
bca9a283   Jeremy   Reworked the sche...
113
        signal.signal(signal.SIGINT, self.signal_handler)
4816e86b   Jeremy   removed *.sh *.ba...
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134

        self.changeDirectory(self.path_dir_file)

        if self.system == 'Windows':
            self.bin_dir = "Scripts"
            self.bin_name = "python.exe"
            self.pip_name = "pip.exe"
            self.celery = "celery.exe"
        else:
            self.bin_dir = "bin"
            self.bin_name = "python"
            self.pip_name = "pip"
            self.celery = "celery"
        self.venv_pip = self.path_dir_file + os.sep + config["path"] + os.sep + config["env"] + os.sep + self.bin_dir + os.sep + self.pip_name
        self.venv_bin = self.path_dir_file + os.sep + config["path"] + os.sep + config["env"] + os.sep + self.bin_dir + os.sep + self.bin_name
        self.venv_cel = self.path_dir_file + os.sep + config["path"] + os.sep + config["env"] + os.sep + self.bin_dir + os.sep + self.celery

    def help(self):
        print("This function must be implemented")
        raise(NotImplementedError("Function not implemented"))

bca9a283   Jeremy   Reworked the sche...
135
136
137
138
139
140
141
142
143
    def signal_handler(self, signal, frame):
        self.printFullTerm(Colors.WARNING, "Ctrl-c catched")
        for p in self.subproc:
            proc, name = p
            self.printColor(Colors.BLUE, "Killing process " + str(name))
            proc.kill()
        self.printFullTerm(Colors.WARNING, "Exiting")
        sys.exit(0)

4816e86b   Jeremy   removed *.sh *.ba...
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
    def addExecuted(self, src, message):
        if (src in self.executed):
            self.executed[src].append(str(message))
        else:
            self.executed[src] = [str(message)]
        return 0

    def addError(self, src, message):
        if (src in self.errors):
            self.errors[src].append(str(message))
        else:
            self.errors[src] = [str(message)]
        return 0

    def execProcess(self, command):
        self.printFullTerm(Colors.BLUE, "Executing command [" + command + "]")
        process = subprocess.Popen(command, shell=True)
        process.wait()
        if process.returncode == 0:
            self.printFullTerm(Colors.GREEN, "Process executed successfully")
            self.addExecuted(self.current_command, command)
        else:
            self.printFullTerm(Colors.WARNING, "Process execution failed")
            self.addError(self.current_command, command)
        return process.returncode

bca9a283   Jeremy   Reworked the sche...
170
171
172
173
174
    def execProcessSilent(self, command):
        process = subprocess.Popen(command, shell=True)
        process.wait()
        return process.returncode

4816e86b   Jeremy   removed *.sh *.ba...
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
    def execProcessFromVenv(self, command):
        args = command.split()
        self.printFullTerm(Colors.BLUE, "Executing command from venv [" + str(' '.join(args[1:])) + "]")
        process = subprocess.Popen(args)
        process.wait()
        if process.returncode == 0:
            self.printFullTerm(Colors.GREEN, "Process executed successfully")
            self.addExecuted(self.current_command, str(' '.join(args[1:])))
        else:
            self.printFullTerm(Colors.WARNING, "Process execution failed")
            self.addError(self.current_command, str(' '.join(args[1:])))
        return process.returncode

    def execProcessAsync(self, command):
        self.printFullTerm(Colors.BLUE, "Executing command [" + command + "]")
bca9a283   Jeremy   Reworked the sche...
190
191
        p = subprocess.Popen(command, shell=True)
        self.subproc.append((p, command))
4816e86b   Jeremy   removed *.sh *.ba...
192
193
        self.printFullTerm(Colors.GREEN, "Process launched successfully")
        self.addExecuted(self.current_command, command)
bca9a283   Jeremy   Reworked the sche...
194
        return p
4816e86b   Jeremy   removed *.sh *.ba...
195

bca9a283   Jeremy   Reworked the sche...
196
    def execProcessFromVenvAsync(self, command: str):
4816e86b   Jeremy   removed *.sh *.ba...
197
198
        args = command.split()
        self.printFullTerm(Colors.BLUE, "Executing command from venv [" + str(' '.join(args[1:])) + "]")
bca9a283   Jeremy   Reworked the sche...
199
200
        p = subprocess.Popen(args)
        self.subproc.append((p, ' '.join(args[1:])))
4816e86b   Jeremy   removed *.sh *.ba...
201
202
        self.printFullTerm(Colors.GREEN, "Process launched successfully")
        self.addExecuted(self.current_command, str(' '.join(args[1:])))
bca9a283   Jeremy   Reworked the sche...
203
204
205
206
207
208
209
        return p

    def waitProcesses(self):
        if (self.wait):
            for p in self.subproc:
                proc, name = p
                proc.wait()
4816e86b   Jeremy   removed *.sh *.ba...
210
211
212
213
        return 0

    def end(self):
        count = 0
bca9a283   Jeremy   Reworked the sche...
214
        self.waitProcesses()
4816e86b   Jeremy   removed *.sh *.ba...
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        self.printFullTerm(Colors.WARNING, "Summary")
        self.printColor(Colors.GREEN, "Success : ")
        for command, valid in self.executed.items():
            if not valid:
                self.printColor(Colors.BLUE, "\t- Command : " + command + " success !")
            else:
                self.printColor(Colors.WARNING, "\t- In commmand : " + command)
                for exe in valid:
                    self.printColor(Colors.GREEN, "\t\t - Command : " + exe + " success !")
        self.printColor(Colors.FAIL, "Errors : ")
        if not self.errors:
            self.printColor(Colors.GREEN, "\tNone")
        for command, items in self.errors.items():
            count += 1
            if (not items):
                self.printColor(Colors.FAIL, "Command : " + command + " failed !")
            else:
                self.printColor(Colors.WARNING, "\t- In commmand : " + command)
                for exe in items:
                    self.printColor(Colors.FAIL, "\t\t - Command : " + exe)
        return count

    def exec(self):
        if (not self.commands):
            self.commandMatcher["help"]()
            return 0
        for command in self.commands:
            self.current_command = command
            if command in self.commandMatcher:
                self.commandMatcher[command]()
            else:
                self.addError(str(command), "invalid command")
        return self.end()

    def logError(self, message):
        self.printColor(Colors.FAIL, "Pyros : An error occurred [" + message + "]", file=sys.stderr)
        return 0

257abe9b   Jeremy   Added comments
253
254
255
256
'''
    Config file representation (able to parse and give informations)
'''

4816e86b   Jeremy   removed *.sh *.ba...
257
258

class Config:
7db4ab5f   Unknown   small change in h...
259
    __parser = argparse.ArgumentParser("Project Pyros")
4816e86b   Jeremy   removed *.sh *.ba...
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
    __content = {
        "path": "private",
        "env": "venv_py3_pyros"
    }
    __wait = True
    __print = True
    usage = ""
    __command_list = []

    def __init__(self):
        self.__parser.add_argument("command", nargs='?', default="help", help="The command you want to execute (default=help)")
        self.__parser.add_argument("--env", help="Your environment directory name default=venv")
        self.__parser.add_argument("--path", help="Path to the virtual env (from the source file directory) (default=private)")
        self.__parser.add_argument("--nowait", action='store_true', help="Don't wait the end of a program")
        self.__parser.add_argument("--noprint", action='store_true', help="Won't print")
        self.usage = self.__parser.format_usage()

    def parse(self):
        try:
            res = self.__parser.parse_args(), self.__parser.format_usage()
            return (res)
        except SystemExit as e:
            # print(e, file=sys.stderr)
            sys.exit(1)

    def parseConf(self):
        res, usage = self.parse()
        try:
            if (res.env):
                self.__content["env"] = res.env
            if (res.path):
                self.__content["path"] = res.path
            if (res.nowait):
                self.__wait = False
            if (res.noprint):
                self.__print = False
            self.__command_list.append(res.command)
            return 0
        except Exception as e:
            print(e, file=sys.stderr)
            return 1

    def getPath(self):
        return self.__content["path"]

    def getEnv(self):
        return self.__content["env"]

    def getWait(self):
        return self.__wait

    def getPrint(self):
        return self.__print

    def setPrint(self, value):
        self.__print = value
        return 0

    def setWait(self, value):
        self.__wait = value
        return 0

    def getCommandList(self):
        return self.__command_list

    def printUsage(self):
        print(self.usage, file=sys.stderr)

    def addConf(self, key, value):
        if isinstance(key, str) and isinstance(value, str):
            self.__content[key] = value
            return 0
        return 1

    def setPath(self, path):
        if (os.path.isdir(path)):
            if (path == ""):
                path = "."
            self.__content["path"] = path
            return 0
        return 1

    def setEnvName(self, name):
        self.__content["env"] = name
        return 0

    def getConfig(self):
        return self.__content


'''
    Color class
'''


class Colors:
    HEADER = '\033[95m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


'''
    Pyros class
'''


class Pyros(AManager):
    help_message = "python neo.py"
    init_fixture = "initial_fixture.json"

ff448d43   Jeremy   Update
375
376
377
378
379
380
381
382
383
384
385
386
    def signal_handler(self, signal, frame):
        self.printFullTerm(Colors.WARNING, "Ctrl-c catched")
        for p in self.subproc:
            proc, name = p
            self.printColor(Colors.BLUE, "Killing process " + str(name))
            proc.kill()
        if self.current_command == "simulator" or self.current_command == "simulator_development":
            self.changeDirectory(self.path_dir_file)
            self.kill_simulation()
        self.printFullTerm(Colors.WARNING, "Exiting")
        sys.exit(0)

4816e86b   Jeremy   removed *.sh *.ba...
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
    def install(self):
        if (self.system == "Windows"):
            self.execProcess("python install/install.py install")
        else:
            self.execProcess("python3 install/install.py install")
        return 0

    def update(self):
        if (self.system == "Windows"):
            self.execProcess("python install/install.py update")
        else:
            self.execProcess("python3 install/install.py update")
        return 0

    def server(self):
        self.changeDirectory("src")
        self.execProcessFromVenvAsync(self.venv_bin + " manage.py runserver")
        self.changeDirectory("..")
        return 0

    def clean(self):
        return self.clean_logs()

    def clean_logs(self):
        return self.execProcess("rm logs/*.log")

    def test(self):
        self.changeDirectory("src")
        self.execProcessFromVenvAsync(self.venv_bin + " manage.py test")
        self.changeDirectory("..")
        return 0

    def migrate(self):
        self.changeDirectory("src")
        self.execProcessFromVenv(self.venv_bin + " manage.py migrate")
        self.changeDirectory("..")
        return 0

    def makemigrations(self):
        self.changeDirectory("src")
        self.execProcessFromVenv(self.venv_bin + " manage.py makemigrations")
        self.changeDirectory("..")
        return 0

    def help(self):
3b0ef1c7   Jeremy   Beautify help mes...
432
433
        count = 0
        self.printFullTerm(Colors.WARNING, "Help Message")
4816e86b   Jeremy   removed *.sh *.ba...
434
        for command, message in self.commandDescription.items():
3b0ef1c7   Jeremy   Beautify help mes...
435
436
437
438
439
            count += 1
            if (self.columns > 100):
                self.printColor(Colors.BLUE, "\t"+str(count)+(' ' if count < 10 else '')+": " + command + ": ", eol='')
            else:
                self.printColor(Colors.BLUE, "-> " + command + ": ", eol='')
4816e86b   Jeremy   removed *.sh *.ba...
440
441
442
443
            self.printColor(Colors.GREEN, message)
        return 0

    def updatedb(self):
4816e86b   Jeremy   removed *.sh *.ba...
444
        self.makemigrations()
3b0ef1c7   Jeremy   Beautify help mes...
445
        self.migrate()
4816e86b   Jeremy   removed *.sh *.ba...
446
447
        return 0

c53a13e0   Jeremy   Updating a lot of...
448
449
450
451
452
453
454
455
    def reset_config(self):
        self.changeDirectory("src")
        self.replacePatternInFile("CELERY_TEST = True", "CELERY_TEST = False", "pyros/settings.py")
        self.replacePatternInFile("SIMULATOR = True", "SIMULATOR = False", "pyros/settings.py")
        self.addExecuted(self.current_command, "reset configuration")
        self.changeDirectory("..")
        return 0

4816e86b   Jeremy   removed *.sh *.ba...
456
457
458
459
460
461
462
463
    def unittest(self):
        self.changeDirectory("src")
        self.execProcessFromVenv(self.venv_bin + " manage.py test common scheduler routine_manager user_manager alert_manager.tests.TestStrategyChange")
        self.changeDirectory("..")
        return 0

    def test_all(self):
        self.unittest()
4816e86b   Jeremy   removed *.sh *.ba...
464
465
466
467
        return 0

    def loaddata(self):
        self.changeDirectory("src")
3185a08a   Unknown   updating init_dat...
468
        self.execProcessFromVenv(self.venv_bin + " manage.py loaddata misc" + os.sep + "fixtures" + os.sep + self.init_fixture)
4816e86b   Jeremy   removed *.sh *.ba...
469
470
471
472
473
474
475
476
477
478
        self.changeDirectory("..")
        return 0

    def celery_on(self):
        self.changeDirectory("src")
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q alert_listener_q -n pyros@alert_listener -c 1")
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q monitoring_q -n pyros@monitoring -c 1")
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q majordome_q -n pyros@majordome -c 1")

        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q scheduling_q --purge -n pyros@scheduling -c 1")
4816e86b   Jeremy   removed *.sh *.ba...
479
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q execute_plan_vis_q --purge -n pyros@execute_plan_vis -c 1")
c72eb17a   Jeremy   Update celery task
480
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q night_calibrations_q --purge -n pyros@night_calibrations -c 1")
c53a13e0   Jeremy   Updating a lot of...
481
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q execute_plan_nir_q --purge -n pyros@execute_plan_nir -c 1")
4816e86b   Jeremy   removed *.sh *.ba...
482
483
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q create_calibrations_q --purge -n pyros@create_calibrations -c 1")
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q analysis_q --purge -n pyros@analysis -c 1")
4816e86b   Jeremy   removed *.sh *.ba...
484
485
486
487
488
489
490
491
492
        self.changeDirectory("..")
        return 0

    def start(self):
        self.stop()
        self.celery_on()
        return 0

    def stop(self):
27e81f38   jeremy   Update windows
493
494
495
496
497
        if (self.system == "Windows"):
            self.execProcessAsync("taskkill /f /im celery.exe")
            self.execProcessAsync("taskkill /f /im python.exe")
        else:
            self.execProcessAsync("ps aux | grep \"celery worker\" | awk '{print $2}' | xargs kill -9")
4816e86b   Jeremy   removed *.sh *.ba...
498
499
        return 0

3b0ef1c7   Jeremy   Beautify help mes...
500
501
502
503
    def init_database(self):
        self.makemigrations()
        self.migrate()
        self.loaddata()
675fb3d5   Jeremy   Update scheduler ...
504
505
506
507
508
        return 0

    def simulator_development(self):
        self.changeDirectory("src")
        self.replacePatternInFile("CELERY_TEST = False", "CELERY_TEST = True", "pyros/settings.py")
ff448d43   Jeremy   Update
509
        self.replacePatternInFile("SIMULATOR = False", "SIMULATOR = True", "pyros/settings.py")
675fb3d5   Jeremy   Update scheduler ...
510
511
512
513
514
515
516
517
518
519
520
        self.execProcess("rm -f testdb.sqlite3")
        self.changeDirectory("..")
        self.migrate()
        self.loaddata()
        self.server()
        self.sleep(2)
        self.printFullTerm(Colors.WARNING, "SUMMARY")
        self.printColor(Colors.GREEN, "The simulator has been successfully initialised")
        self.printColor(Colors.GREEN, "The simulator run on a temp database : src/testdb.sqlite3")
        self.printColor(Colors.GREEN, "The simulation will be ended by the task 'simulator herself'")
        self.printColor(Colors.GREEN, "If you want to shutdown the simulation, please run :")
c53a13e0   Jeremy   Updating a lot of...
521
        self.printColor(Colors.GREEN, "CTRL-C or python pyros.py kill_simulation")
675fb3d5   Jeremy   Update scheduler ...
522
523
524
525
526
527
528
529
530
531
532
533
        self.printColor(Colors.GREEN, "If the simulation isn't correctly killed, please switch the variable")
        self.printColor(Colors.GREEN, "CELERY_TEST in src/pyros/settings.py to false")
        self.printFullTerm(Colors.WARNING, "SUMMARY")
        self.changeDirectory("simulators/config")
        self.printColor(Colors.BOLD, "Existing simulations : ", eol='')
        sys.stdout.flush()
        self.execProcessSilent("ls conf*.json")
        self.changeDirectory("..")
        conf = self.askQuestion("Which simulation do you want to use", default="conf.json")
        self.changeDirectory("..")
        self.singleWorker("scheduling")
        self.singleWorker("majordome")
c53a13e0   Jeremy   Updating a lot of...
534
535
536
537
        self.singleWorker("execute_plan_vis")
        self.singleWorker("execute_plan_nir")
        self.singleWorker("create_calibrations")
        self.singleWorker("analysis")
675fb3d5   Jeremy   Update scheduler ...
538
539
540
541
542
543
544
545
546
547
548
        self.sleep(3)
        procs = []
        self.changeDirectory("simulators")
        self.changeDirectory("user")
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " userSimulator.py " + conf))
        self.changeDirectory("..")
        for p in procs:
            p.wait()
        self.changeDirectory("..")
        self.kill_simulation()
        return 0
3b0ef1c7   Jeremy   Beautify help mes...
549

c72eb17a   Jeremy   Update celery task
550
551
552
553
554
555
556
    def reset_database_sim(self):
        self.changeDirectory("src")
        self.replacePatternInFile("CELERY_TEST = False", "CELERY_TEST = True", "pyros/settings.py")
        self.execProcess("echo 'yes' |'" + self.venv_bin + "' manage.py flush")
        self.replacePatternInFile("CELERY_TEST = False", "CELERY_TEST = True", "pyros/settings.py")
        self.changeDirectory("..")

4816e86b   Jeremy   removed *.sh *.ba...
557
558
    def simulator(self):
        self.changeDirectory("src")
cfc9d09c   Jeremy   Added dome simula...
559
        self.replacePatternInFile("CELERY_TEST = False", "CELERY_TEST = True", "pyros/settings.py")
ff448d43   Jeremy   Update
560
        self.replacePatternInFile("SIMULATOR = False", "SIMULATOR = True", "pyros/settings.py")
4816e86b   Jeremy   removed *.sh *.ba...
561
562
        self.execProcess("rm -f testdb.sqlite3")
        self.changeDirectory("..")
c72eb17a   Jeremy   Update celery task
563
        self.reset_database_sim()
4816e86b   Jeremy   removed *.sh *.ba...
564
565
566
567
568
569
570
571
572
573
574
575
576
        self.migrate()
        self.loaddata()
        self.server()
        self.sleep(2)
        self.printFullTerm(Colors.WARNING, "SUMMARY")
        self.printColor(Colors.GREEN, "The simulator has been successfully initialised")
        self.printColor(Colors.GREEN, "The simulator run on a temp database : src/testdb.sqlite3")
        self.printColor(Colors.GREEN, "The simulation will be ended by the task 'simulator herself'")
        self.printColor(Colors.GREEN, "If you want to shutdown the simulation, please run :")
        self.printColor(Colors.GREEN, "CTRL-C or ./pyrosrun.sh kill_simulation")
        self.printColor(Colors.GREEN, "If the simulation isn't correctly killed, please switch the variable")
        self.printColor(Colors.GREEN, "CELERY_TEST in src/pyros/settings.py to false")
        self.printFullTerm(Colors.WARNING, "SUMMARY")
bca9a283   Jeremy   Reworked the sche...
577
578
579
580
581
        self.changeDirectory("simulators/config")
        self.printColor(Colors.BOLD, "Existing simulations : ", eol='')
        sys.stdout.flush()
        self.execProcessSilent("ls conf*.json")
        self.changeDirectory("..")
d48f6550   Jeremy   Fix little bug on...
582
        conf = self.askQuestion("Which simulation do you want to use", default="conf.json")
bca9a283   Jeremy   Reworked the sche...
583
        self.changeDirectory("..")
4816e86b   Jeremy   removed *.sh *.ba...
584
585
        self.celery_on()
        self.sleep(3)
d48f6550   Jeremy   Fix little bug on...
586
        self.sims_launch(conf)
4816e86b   Jeremy   removed *.sh *.ba...
587
588
        return 0

3b0ef1c7   Jeremy   Beautify help mes...
589
590
591
592
    def kill_server(self):
        self.execProcessAsync("fuser -k 8000/tcp")
        return 0

4816e86b   Jeremy   removed *.sh *.ba...
593
594
595
    def kill_simulation(self):
        self.changeDirectory("src")
        self.replacePatternInFile("CELERY_TEST = True", "CELERY_TEST = False", "pyros/settings.py")
ff448d43   Jeremy   Update
596
        self.replacePatternInFile("SIMULATOR = True", "SIMULATOR = False", "pyros/settings.py")
27e81f38   jeremy   Update windows
597
598
599
600
601
        if (self.system == "Windows"):
            self.execProcessAsync("taskkill /f /im python.exe")
            self.execProcessAsync("rm -f testdb.sqlite3")
            self.changeDirectory("..")
            return 0
4816e86b   Jeremy   removed *.sh *.ba...
602
603
        self.execProcessAsync("fuser -k 8000/tcp")
        self.execProcessAsync("rm -f testdb.sqlite3")
cfc9d09c   Jeremy   Added dome simula...
604
        self.execProcessAsync("ps aux | grep \" domeSimulator.py\" | awk '{ print $2 }' | xargs kill")
4816e86b   Jeremy   removed *.sh *.ba...
605
606
607
608
609
610
611
612
613
614
615
        self.execProcessAsync("ps aux | grep \" userSimulator.py\" | awk '{ print $2 }' | xargs kill")
        self.execProcessAsync("ps aux | grep \" alertSimulator.py\" | awk '{ print $2 }' | xargs kill")
        self.execProcessAsync("ps aux | grep \" plcSimulator.py\" | awk '{ print $2 }' | xargs kill")
        self.execProcessAsync("ps aux | grep \" telescopeSimulator.py\" | awk '{ print $2 }' | xargs kill")
        self.execProcessAsync("ps aux | grep \" cameraNIRSimulator.py\" | awk '{ print $2 }' | xargs kill")
        self.execProcessAsync("ps aux | grep \" cameraVISSimulator.py\" | awk '{ print $2 }' | xargs kill")
        self.changeDirectory("..")
        self.stop()
        self.printFullTerm(Colors.GREEN, "simulation ended")
        return 0

d48f6550   Jeremy   Fix little bug on...
616
    def sims_launch(self, conf=""):
bca9a283   Jeremy   Reworked the sche...
617
        procs = []
4816e86b   Jeremy   removed *.sh *.ba...
618
        self.changeDirectory("simulators/config")
d48f6550   Jeremy   Fix little bug on...
619
        if (conf == ""):
bca9a283   Jeremy   Reworked the sche...
620
621
622
623
            self.printColor(Colors.BOLD, "Existing simulations : ", eol='')
            sys.stdout.flush()
            self.execProcessSilent("ls conf*.json")
            conf = self.askQuestion("Which simulation do you want to use ?", default="conf.json")
4816e86b   Jeremy   removed *.sh *.ba...
624
625
626
627
        if not os.path.isfile(conf):
            self.printColor(Colors.FAIL, "The simulation file " + conf + " does not exist")
            return 1
        self.changeDirectory("..")
cfc9d09c   Jeremy   Added dome simula...
628
        self.changeDirectory("dome")
bca9a283   Jeremy   Reworked the sche...
629
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " domeSimulator.py " + conf))
cfc9d09c   Jeremy   Added dome simula...
630
        self.changeDirectory("..")
4816e86b   Jeremy   removed *.sh *.ba...
631
        self.changeDirectory("user")
bca9a283   Jeremy   Reworked the sche...
632
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " userSimulator.py " + conf))
4816e86b   Jeremy   removed *.sh *.ba...
633
634
        self.changeDirectory("..")
        self.changeDirectory("alert")
bca9a283   Jeremy   Reworked the sche...
635
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " alertSimulator.py " + conf))
4816e86b   Jeremy   removed *.sh *.ba...
636
637
        self.changeDirectory("..")
        self.changeDirectory("plc")
bca9a283   Jeremy   Reworked the sche...
638
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " plcSimulator.py " + conf))
4816e86b   Jeremy   removed *.sh *.ba...
639
640
        self.changeDirectory("..")
        self.changeDirectory("camera")
bca9a283   Jeremy   Reworked the sche...
641
642
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " cameraVISSimulator.py " + conf))
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " cameraNIRSimulator.py " + conf))
4816e86b   Jeremy   removed *.sh *.ba...
643
644
        self.changeDirectory("..")
        self.changeDirectory("telescope")
bca9a283   Jeremy   Reworked the sche...
645
        procs.append(self.execProcessFromVenvAsync(self.venv_bin + " telescopeSimulator.py " + conf))
4816e86b   Jeremy   removed *.sh *.ba...
646
647
        self.changeDirectory("..")
        self.changeDirectory("..")
bca9a283   Jeremy   Reworked the sche...
648
649
650
        for p in procs:
            p.wait()
        self.kill_simulation()
4816e86b   Jeremy   removed *.sh *.ba...
651
652
653
654
655
656
657
658
        return 0

    def singleWorker(self, worker):
        self.changeDirectory("src")
        self.execProcessFromVenvAsync(self.venv_cel + " worker -A pyros -Q "+ worker +"_q -n pyros@"+worker+" -c 1")
        self.changeDirectory("..")
        return 0

c53a13e0   Jeremy   Updating a lot of...
659
660
661
662
663
664
665
666
667
668
669
670
671
672
    def mysql_on(self):
        self.changeDirectory("src")
        self.replacePatternInFile("MYSQL = False", "MYSQL = True", "pyros/settings.py")
        self.addExecuted(self.current_command, "Switch to mysql")
        self.changeDirectory("..")
        return 0

    def mysql_off(self):
        self.changeDirectory("src")
        self.replacePatternInFile("MYSQL = True", "MYSQL = False", "pyros/settings.py")
        self.addExecuted(self.current_command, "Switch to sqlite")
        self.changeDirectory("..")
        return 0

4816e86b   Jeremy   removed *.sh *.ba...
673
674
675
676
677
678
679
    def __init__(self, argv):
        super(Pyros, self).__init__(argv)
        self.commandMatcher = {
            "install": self.install,
            "update": self.update,
            "server": self.server,
            "clean": self.clean,
ff448d43   Jeremy   Update
680
            "simulator_development": self.simulator_development,
4816e86b   Jeremy   removed *.sh *.ba...
681
682
683
            "clean_logs": self.clean_logs,
            "test": self.test,
            "migrate": self.migrate,
c53a13e0   Jeremy   Updating a lot of...
684
685
            "mysql_on": self.mysql_on,
            "mysql_off": self.mysql_off,
4816e86b   Jeremy   removed *.sh *.ba...
686
687
688
            "makemigrations": self.makemigrations,
            "updatedb": self.updatedb,
            "unittest": self.unittest,
c53a13e0   Jeremy   Updating a lot of...
689
            "reset_config": self.reset_config,
4816e86b   Jeremy   removed *.sh *.ba...
690
691
            "test_all": self.test_all,
            "celery_on": self.celery_on,
c72eb17a   Jeremy   Update celery task
692
            "reset_database_sim": self.reset_database_sim,
3b0ef1c7   Jeremy   Beautify help mes...
693
694
            "init_database": self.init_database,
            "kill_server": self.kill_server,
4816e86b   Jeremy   removed *.sh *.ba...
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
            "loaddata": self.loaddata,
            "start": self.start,
            "stop": self.stop,
            "simulator": self.simulator,
            "kill_simulation": self.kill_simulation,
            "sims_launch": self.sims_launch,
            "help": self.help,
        }
        self.commandDescription = {
            "install": "Launch the server installation",
            "update": "Update the server",
            "server": "Launch the web server",
            "loaddata": "Load the initial fixture in database",
            "clean": "clean the repository",
            "clean_logs": "clean the log directory",
            "test": "launch the server tests",
            "migrate": "execute migrations",
c53a13e0   Jeremy   Updating a lot of...
712
713
            "mysql_on": "switch the database to be used to MYSQL",
            "mysql_off": "switch the database to be used usage to SQLITE",
4816e86b   Jeremy   removed *.sh *.ba...
714
            "makemigrations": "create new migrations",
c53a13e0   Jeremy   Updating a lot of...
715
            "reset_config": "Reset the configuration in settings.py",
c72eb17a   Jeremy   Update celery task
716
            "reset_database_sim": "Reset the database content",
4816e86b   Jeremy   removed *.sh *.ba...
717
718
            "help": "Help message",
            "updatedb": "Update the database",
3b0ef1c7   Jeremy   Beautify help mes...
719
720
            "kill_server": "Kill the web server on port 8000",
            "init_database": "Create a standard context for pyros in db",
2e0c8f94   Unknown   New install scrip...
721
            "unittest": "Runs the tests that don't need celery",
4816e86b   Jeremy   removed *.sh *.ba...
722
723
724
725
726
            "test_all": "Run all the existing tests (this command needs to be updated when tests are added in the project",
            "celery_on": "Starts celery workers",
            "start": "Stop the celery workers then the web server",
            "stop": "stops the celery workers",
            "simulator": "Launch a simulation",
ff448d43   Jeremy   Update
727
            "simulator_development": "Simulation for the scheduler only",
4816e86b   Jeremy   removed *.sh *.ba...
728
729
730
731
732
733
734
735
736
737
            "kill_simulation": "kill the simulators / celery workers / web server",
            "sims_launch": "Launch only the simulators",
        }

if __name__ == "__main__":
    conf = Config()
    if conf.parseConf():
        sys.exit(1)
    pyros = Pyros(conf)
    sys.exit(pyros.exec())