pyros.py 15.2 KB
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 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 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 253 254 255 256 257 258 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 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 375 376 377 378 379 380 381 382 383 384 385 386 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 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
#!/usr/bin/env python3


import argparse
import fileinput
import os
import platform
import signal
import subprocess
import sys
import time



"""
*****************************************************************
******************** GENERAL CONSTANTS **************************
*****************************************************************
"""

DEBUG = True

INIT_FIXTURE = "initial_fixture.json"

AGENTS = {
    #"agentX" : "majordome", 
    "agentX" : "agent", 
    "webserver" : "webserver", 
    "monitoring" : "monitoring", 
    "majordome" : "majordome", 
    "scheduler" : "scheduler", 
    "alert_manager" : "alert_manager"
}
#AGENTS = ["agentX", "webserver", "monitoring", "majordome", "scheduler", "alert_manager"]
#AGENTS = ["all", "webserver", "monitoring", "majordome", "scheduler", "alert"]

#COMMANDS = {"install": [], "start": AGENTS, "stop": AGENTS}

IS_WINDOWS = platform.system() == "Windows"

my_abs_path = os.path.dirname(os.path.realpath(__file__))
if IS_WINDOWS:
    b_in_dir = "Scripts"
    PYTHON = "python.exe"
    # should also be ok:
    #PYTHON = "python"
else:
    b_in_dir = "bin"
    PYTHON = "python3"
    # ok only from venv:
    #PYTHON = "python"
VENV_BIN = (
    my_abs_path
    + os.sep + "private"
    + os.sep + "venv_py3_pyros"
    + os.sep + b_in_dir
    + os.sep + PYTHON
)

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"




# First, install the click package !!!
#import fire
try:
    import click # https://click.palletsprojects.com
except:
    #pip = "pip" if platform.system() == "Windows" else "pip3"
    pip = "pip" if IS_WINDOWS else "pip3"
    process = subprocess.Popen(pip + " install --upgrade click", shell=True)
    process.wait()
    if process.returncode == 0:
        print("click package installation successfull")
        # self.addExecuted(self.current_command, command)
        import click
    else:
        print("click package installation failed")
        # self.addError(self.current_command, command)
        
    




"""
**************************************************************************
******************** GENERAL AND UTIL FUNCTIONS **************************
**************************************************************************
"""

def _in_dir(dirname: str = ""):
    return os.path.basename(os.getcwd()) == dirname


def _in_abs_dir(dirname: str = ""):
    return os.getcwd() == dirname


def die(msg: str = ""):
    print()
    print("...ERROR...")
    print(msg)
    print()
    exit(1)
    

#TODO: implement is_async
def execProcess(command, from_venv=False, is_async=False):
    from_venv_str = " from venv ("+VENV_BIN+")" if from_venv else ""
    printFullTerm(Colors.BLUE, "Executing command" + " [" + command + "]" + from_venv_str)
    if from_venv: command = VENV_BIN+' ' + command
    process = subprocess.Popen(command, shell=True)
    process.wait()
    if process.returncode == 0:
        printFullTerm(Colors.GREEN, "Process executed successfully")
        # self.addExecuted(self.current_command, command)
    else:
        printFullTerm(Colors.WARNING, "Process execution failed")
        # self.addError(self.current_command, command)
    #return process.returncode
    return True if process.returncode==0 else False

def execProcessFromVenv(command:str):
    return execProcess(command, from_venv=True)

#TODO: fusionner dans execProcess avec param is_async
def execProcessFromVenvAsync(command:str):
    args = command.split()
    printFullTerm(
        Colors.BLUE, "Executing command from venv [" + str(" ".join(args[1:])) + "]"
    )
    p = subprocess.Popen(args)
    subproc.append((p, " ".join(args[1:])))
    printFullTerm(Colors.GREEN, "Process launched successfully")
    # self.addExecuted(self.current_command, str(' '.join(args[1:])))
    # p.wait()
    return p


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


def printFullTerm(color: Colors, string: str):
    #system = platform.system()
    columns = 100
    row = 1000
    disp = True
    value = int(columns / 2 - len(string) / 2)
    printColor(color, "-" * value, eol="")
    printColor(color, string, eol="")
    value += len(string)
    printColor(color, "-" * (columns - value))
    return 0





"""
********************************************************************************
******************** CLI COMMANDS DEFINITION (click format) ********************
********************************************************************************
"""

'''
_global_test_options = [
    click.option('--test', '-t', is_flag=True, help="don't do it for real, just show what it would do"),
    click.option('--verbose', '-v', 'verbosity', flag_value=2, default=1, help='Verbose output'),
    click.option('--quiet', '-q', 'verbosity', flag_value=0, help='Minimal output'),
    #click.option('--fail-fast', '--failfast', '-f', 'fail_fast', is_flag=True, default=False, help='Stop on failure'),
]
def global_test_options(func):
    for option in reversed(_global_test_options):
        func = option(func)
    return func
'''

GLOBAL_OPTIONS = {}
def verbose_mode(): return GLOBAL_OPTIONS["verbose"]
def test_mode(): return GLOBAL_OPTIONS["test"]

@click.group()
@click.option('--test', '-t', is_flag=True, help="don't do it for real, just show what it would do")
@click.option('--verbose', '-v', is_flag=True, help='Verbose output')
#@click.option('--verbose', '-v', 'verbosity', flag_value=2, default=1, help='Verbose output'),
#@click.option('--quiet', '-q', 'verbosity', flag_value=0, help='Minimal output'),
#@click.option('--fail-fast', '--failfast', '-f', 'fail_fast', is_flag=True, default=False, help='Stop on failure'),
def pyros_launcher(test, verbose):
    #pass
    if test: click.echo('Test mode')
    if verbose: click.echo('Verbose mode')
    GLOBAL_OPTIONS["test"] = test
    GLOBAL_OPTIONS["verbose"] = verbose



@pyros_launcher.command(help="Run a pyros shell (django included)")
#@global_test_options
def shell():
    print()
    print("Launching a pyros shell")
    print("From this shell, type 'from common.models import *' to import all the pyros objects")
    print("Then, you can create any pyros object just by typing its name")
    print("For example, to create a AgentsSurvey object, type 'agent_survey = AgentsSurvey()'")
    print("See documentation, chapter '9.6 - Play with the pyros objects' for more details")
    print("Type 'exit()' to quit")
    print()
    os.chdir("src/")
    # execProcess("python install.py install")
    if not test_mode(): execProcessFromVenv("manage.py shell")
    # Go back to the initial dir
    os.chdir("../")
    return True


@pyros_launcher.command(help="Run a database (Mysql) shell")
def dbshell():
    print()
    print("Launching a database (mysql) shell")
    print("From this shell, type 'use database pyros;' to select the pyros database")
    print("Then type 'show tables;' to see all the pyros tables")
    print("Then for example, type 'select * from config;' to see the content of the 'config' table")
    print("Type 'exit' to quit")
    print()
    # execProcess("python install.py install")
    if not test_mode(): execProcessFromVenv("src/manage.py dbshell")
    # Go back to the initial dir
    return True


@pyros_launcher.command(help="Install the pyros software")
#@global_test_options
def install():
    print("Running install command")
    #if test_mode(): print("in test mode")
    # self.execProcess("python3 install/install.py install")
    # if (os.path.basename(os.getcwd()) != "private"):
    start_dir = os.getcwd()
    os.chdir("install/") ; _in_dir("install") or die("Bad dir")
    # execProcess("python install.py install")
    if not test_mode(): execProcess(PYTHON + " install.py")
    # cd -
    # os.chdir("-")
    os.chdir(start_dir) ; _in_abs_dir(start_dir) or die("Bad dir")
    # return 0
    return True



    
'''
TODO:
'''
@pyros_launcher.command(help="Update the pyros software (git pull + update DB if necessary)")
def update():
    print("Running update command")
    #res = _gitpull()
    _gitpull() or die()
    #if not res: return False
    _updatedb() or die()
    return True


def _gitpull():
    print("-- running git pull")
    GIT = "git.exe" if IS_WINDOWS else "git"
    if not test_mode(): return execProcess(f"{GIT} pull")
    return True

#@pyros_launcher.command(help="Update the pyros database")
def _updatedb():
    print("-- update db (make migrations + migrate)")
    if not test_mode() :
        _makemigrations() or die()
        _migrate() or die()
    return True


@pyros_launcher.command(help="Update the pyros database and fill it with initial fixture data")
def initdb():
    if not test_mode():
        #updatedb()
        _makemigrations()
        _migrate()
        _loaddata()
    return True



@pyros_launcher.command(help="Launch an agent")
#@global_test_options
@click.argument('agent')
@click.option('--configfile', '-c', help='the configuration file to be used')
#@click.option('--format', '-f', type=click.Choice(['html', 'xml', 'text']), default='html', show_default=True)
#@click.option('--port', default=8000)
#def start(agent:str, configfile:str, test, verbosity):
def start(agent:str, configfile:str):
    print("Running start command")
    if configfile: 
        print("With config file", configfile)
    else: 
        configfile = '' 
    #if test_mode(): print("in test mode")
    #if verbose_mode(): print("in verbose mode")
    if not _check_agent(agent): return
    # VENV_BIN = 'private/venv_py3_pyros' +  os.sep + self.b_in_dir + os.sep + self.bin_name


    # Start Agents
    """            
    if agent=="majordome" or agent=="all":
        from majordome.tasks import Majordome
        Majordome().run()
    if agent=="alert_manager" or agent=="all":
        from alert_manager.tasks import AlertListener
        AlertListener().run()
    """
    for agent_name,agent_folder in AGENTS.items():

        if agent in ("all", agent_name) :
            
            # Default case, launch agentX
            #if agent_name == "agentX":

            # execProcessFromVenvAsync(VENV_BIN + " manage.py runserver")
            print(VENV_BIN)
            print("Launching agent", agent_name, "...")
            #if not test_mode(): execProcess(VENV_BIN + " manage.py runserver")
            #if not test_mode(): execProcessFromVenv("start_agent_" + agent_name + ".py " + configfile)
            cmd = "start_agent.py " + agent_name + " " + configfile
            if agent_name == "webserver": 
                cmd = "manage.py runserver"
                os.chdir("src")
            #if not test_mode(): execProcessFromVenv("start_agent.py " + agent_name + " " + configfile)
            if not test_mode(): execProcessFromVenv(cmd)
            # self._change_dir("..")

            '''
            # Any other agent
            else:
                # Go into src/
                # self._change_dir("src")
                os.chdir("src")
                # print("Current directory : " + str(os.getcwd()))
                if agent_name != "webserver": os.chdir(agent_folder)
                # self.execProcessFromVenvAsync(self.VENV_BIN + ' start_agent_'+agent+'.py')
                #print(VENV_BIN)
                print("Launching agent", agent_name, "...")
                #if not test_mode(): execProcess(VENV_BIN + " start_agent_" + agent_name + ".py")
                #TODO:
                # - start_agent agent_name (1 script unique)
                # - start_agent -c configfile
                cmd = "start_agent_" + agent_name + ".py " + configfile
                # Django default dev web server
                if agent_name == "webserver": cmd = "manage.py runserver"
                if not test_mode(): execProcessFromVenv(cmd)
                # Go back to src/
                # self._change_dir('..')
                os.chdir("..")
            '''
                
    # Go back to root folder (/)
    # self._change_dir('..')
    os.chdir("..")
    return True




@pyros_launcher.command(help="Kill an agent")
@click.argument('agent')
def stop(agent):
    print("Running stop command")
    if not _check_agent(agent): return



"""
********************************************************************************
******************** PRIVATE FUNCTIONS DEFINITION ******************************
********************************************************************************
"""

def _migrate():
    _change_dir("src")
    res = execProcessFromVenv("manage.py migrate")
    _change_dir("..")
    return res

def _makemigrations():
    _change_dir("src")
    #execProcessFromVenv(self.venv_bin + " manage.py makemigrations")
    res = execProcessFromVenv("manage.py makemigrations")
    print("res is", res)
    _change_dir("..")
    return res

#TODO: mettre la fixture en date naive (sans time zone)
def _loaddata():
    _change_dir("src")
    #execProcessFromVenv(self.venv_bin + " manage.py loaddata misc" + os.sep + "fixtures" + os.sep + self.INIT_FIXTURE)
    res = execProcessFromVenv("manage.py loaddata misc" + os.sep + "fixtures" + os.sep + INIT_FIXTURE)
    _change_dir("..")
    return res

def _change_dir(path):
    if DEBUG: print("Moving to : " + path)
    os.chdir(path)
    if DEBUG: print("Current directory : " + str(os.getcwd()))



def _check_agent(agent):
    # Check that agent exists
    if agent not in AGENTS.keys() and agent != "all": 
        print("This agent does not exist")
        print("Here is the allowed list of agents:")
        print("- all => will launch ALL agents")
        for agent_name in AGENTS.keys(): print('-',agent_name)
        return False
    return True



"""
********************************************************************************
********************************* main() FUNCTION ******************************
********************************************************************************
"""
def main():
    pyros_launcher()
    
    
# AVIRER
#@click.command()
#@click.argument('start')
def oldmain():
    '''
    cli()
    return
    '''
    
    #fire.Fire(Commands)
    #return

    # if len(sys.argv) == 3 and sys.argv[1].startswith("simulator"): SIMULATOR_CONFIG_FILE = sys.argv[2]
    # print(sys.argv)
    """
    system = platform.system()
    columns = 100
    row = 1000
    disp = True
    """

    # Read command
    if len(sys.argv) <= 1:
        die("You must give a command name")
    command = sys.argv[1]
    if not command in COMMANDS.keys():
        die("This command does not exist")
    command_all_args = COMMANDS[command]

    # Read command args if should be
    command_arg = None
    if command_all_args:
        if len(sys.argv) <= 2:
            die("This command should be given an argument")
        command_arg = sys.argv[2]
        if not command_arg in command_all_args:
            die("This argument does not exist for command " + command)

    print("Executing command", command)
    if command_arg:
        print("with arg", command_arg)

    # command(command_arg)
    if command_arg:
        globals()[command](command_arg)
    else:
        globals()[command]()
    # sys.exit(pyros.exec())



if __name__ == "__main__": main()