From 90990ab1c00f56dd0bd98f470b1c995a24f02316 Mon Sep 17 00:00:00 2001 From: absurdo Date: Wed, 29 Nov 2023 23:53:11 +0100 Subject: [PATCH] Added delete flask webapp --- scripts/webapps/delete_app_apache.py | 16 ++ scripts/webapps/flask/delete_flask.py | 49 ++++ scripts/webapps/flask/install_flask_site.py | 188 ++++++++++++++++ .../webapps/phpmyadmin/delete_phpmyadmin.py | 42 ++++ .../phpmyadmin/install_phpmyadmin_site.py | 205 +++++++++++++++++ .../webapps/phpmyadmin/update_phpmyadmin.py | 53 +++++ .../{ => wordpress}/delete_wordpress.py | 0 tasks/apache/scripts/delete_app.py | 4 +- tasks/apache/scripts/flask.py | 202 +++++++++++++++++ tasks/apache/scripts/phpmyadmin.py | 212 ++++++++++++++++++ 10 files changed, 969 insertions(+), 2 deletions(-) create mode 100644 scripts/webapps/flask/delete_flask.py create mode 100644 scripts/webapps/flask/install_flask_site.py create mode 100644 scripts/webapps/phpmyadmin/delete_phpmyadmin.py create mode 100644 scripts/webapps/phpmyadmin/install_phpmyadmin_site.py create mode 100644 scripts/webapps/phpmyadmin/update_phpmyadmin.py rename scripts/webapps/{ => wordpress}/delete_wordpress.py (100%) create mode 100644 tasks/apache/scripts/flask.py create mode 100644 tasks/apache/scripts/phpmyadmin.py diff --git a/scripts/webapps/delete_app_apache.py b/scripts/webapps/delete_app_apache.py index 31be715..14f14e7 100644 --- a/scripts/webapps/delete_app_apache.py +++ b/scripts/webapps/delete_app_apache.py @@ -48,10 +48,26 @@ if os.path.isfile(apache_php): apache_webapp='/etc/{}/vhosts.d/extra/{}-{}.conf'.format(apache_cmd, args.domain, args.webapp) +apache_sub0_webapp='/etc/{}/vhosts.d/extra/{}-000-{}.conf'.format(apache_cmd, args.domain, args.webapp) + +apache_sub1_webapp='/etc/{}/vhosts.d/extra/{}-001-{}.conf'.format(apache_cmd, args.domain, args.webapp) + if os.path.isfile(apache_webapp): if subprocess.call("sudo rm %s" % (apache_webapp), shell=True) > 0: print('Error: cannot delete webapp config %s' % apache_webapp) sys.exit(1) +if os.path.isfile(apache_sub0_webapp): + + if subprocess.call("sudo rm %s" % (apache_sub0_webapp), shell=True) > 0: + print('Error: cannot delete webapp config %s' % apache_sub0_webapp) + sys.exit(1) + +if os.path.isfile(apache_sub1_webapp): + + if subprocess.call("sudo rm %s" % (apache_sub1_webapp), shell=True) > 0: + print('Error: cannot delete webapp config %s' % apache_sub1_webapp) + sys.exit(1) + if subprocess.call("sudo systemctl restart %s" % (apache_cmd), shell=True) > 0: print('Error: cannot restart Apache server') diff --git a/scripts/webapps/flask/delete_flask.py b/scripts/webapps/flask/delete_flask.py new file mode 100644 index 0000000..693cc3b --- /dev/null +++ b/scripts/webapps/flask/delete_flask.py @@ -0,0 +1,49 @@ +#!/usr/bin/python3 -u + +import argparse +import os +from pathlib import Path +from subprocess import call, DEVNULL +import json +import time +import shutil +import pwd +import distro +import subprocess +import re +import sys + + +parser=argparse.ArgumentParser(prog='delete_flask.py', description='A tool for delete flask') + +parser.add_argument('--home_user', help='Home where flask resides', required=True) +parser.add_argument('--user', help='The user', required=True) + +print('Deleting Flask App..') + +args=parser.parse_args() + +home_user=args.home_user + +if home_user=='/': + print('What are you doing?') + sys.exit(1) + +name_service=os.path.basename(home_user[:-1]).strip() + +#d=os.path.basename(p[:-1].replace(f, '')[:-1]) + +domain=os.path.basename(home_user[:-1].replace(name_service, '')[:-1]).strip() + +#print(domain) + +if subprocess.call('sudo systemctl stop %s-%s.service && sudo rm /etc/systemd/system/%s-%s.service' % (domain, name_service, domain, name_service), shell=True) > 0: + print('Error: cannot delete app service in systemd...') + sys.exit(1) + +if subprocess.call("sudo su %s -s /bin/bash -c 'rm -f -r %s'" % (args.user, args.home_user), shell=True) > 0: + print('Error: cannot delete %s' % args.home_user) + sys.exit(1) + +print('Deleted Flask app successfully...') + diff --git a/scripts/webapps/flask/install_flask_site.py b/scripts/webapps/flask/install_flask_site.py new file mode 100644 index 0000000..7f55b70 --- /dev/null +++ b/scripts/webapps/flask/install_flask_site.py @@ -0,0 +1,188 @@ +#!/usr/bin/python3 -u + +import sys, os +import subprocess +import argparse +import platform +import shutil +import pathlib +import distro +import pwd +import getpass +import re + +#import pymysql.cursors +#pymysql.install_as_MySQLdb + +pyv=platform.python_version_tuple() + +if pyv[0]!='3': + print('Need python 3 for execute this script') + sys.exit(1) + +parser = argparse.ArgumentParser(description='Script for create a flask site.') + +parser.add_argument('--domain', help='The domain where is the site', required=True) +parser.add_argument('--home_user', help='The name of the new user', required=True) +parser.add_argument('--git_url', help='Url for download the last tag of app, can be used for update app', required=True) +parser.add_argument('--user', help='The name of the domain user', required=True) +parser.add_argument('--dependencies', help='The dependencies of the flask app separated by commas', required=True) +parser.add_argument('--app_flask', help='The string type app:app for load in gunicorn', required=True) +#parser.add_argument('--port', help='The port of the gunicorn application', required=True) +parser.add_argument('--path', help='The path of the flask install') + +args = parser.parse_args() + +linux_distro=distro.id() + +home_user=args.home_user + +if home_user.find('/', -1)==-1: + print("Error: you need backslash in home_user option") + exit(1) + +user=args.user + +apache_cmd='apache2' +apachectl='apache2ctl' + +if linux_distro!='debian' and linux_distro!='ubuntu': + + apache_cmd='httpd' + apachectl='apachectl' + + if linux_distro=='rocky' or linux_distro=='fedora': + apache_group='apache' + + if linux_distro=='arch': + apache_group='http' + +system_user=getpass.getuser() + +if os.path.isdir(home_user): + print("Cleaning %s directory" % home_user) + + if subprocess.call("sudo su %s -s /bin/bash -c 'rm -f -r %s'" % (user, home_user), shell=True) > 0: + print('Error: cannot clean directory {}'.format(home_user)) + sys.exit(1) + +""" +if linux_distro=='debian' or linux_distro=='ubuntu': + #libapache2-mod-wsgi-py3/ + if subprocess.call("sudo apt-get update && sudo apt-get upgrade && sudo apt-get install libapache2-mod-wsgi-py3", shell=True) > 0: + print('Error: cannot install mod_wsgi for apache') + sys.exit(1) +""" + +print("Creating virtualenv for the flask app...") + +if subprocess.call("sudo su %s -s /bin/bash -c 'mkdir -p %s && python3 -m venv %s/venv'" % (user, home_user, home_user), shell=True) > 0: + print('Error: cannot install python virtualenv in {}'.format(home_user)) + sys.exit(1) + +dependencies=args.dependencies + +if subprocess.call("sudo su %s -s /bin/bash -c '%s/venv/bin/pip install %s flask gunicorn'" % (user, home_user, dependencies.replace(',', ' ')), shell=True) > 0: + print('Error: cannot install python virtualenv dependencies in {}'.format(home_user)) + sys.exit(1) + +num_proc=str(os.cpu_count()*2+1) + +name=os.path.basename(home_user[:-1]).strip() + +#port=int(args.port) + +if not re.match('\w+:\w+', args.app_flask): + + print('Error: define the app_flask with app:app format') + + sys.exit(1) + +path='/' + +if args.path: + + if args.path.find('/', -1)==-1: + print("Error: you need backslash in path option") + exit(1) + + path=args.path[:-1] + + if path=='': + path='/' + +print("Creating the service for flask app with gunicorn...") + +with open('./%s-%s.service' % (args.domain, name), 'w') as f: + + f.write("# Save it in /etc/systemd/system/%s-%s.service\n" % (args.domain, name)) + + f.write("[Unit]\n") + f.write("Description=App %s\n" % name) + f.write("After=syslog.target\n") + f.write("After=network.target\n") + + f.write("[Service]\n") + f.write("Type=simple\n") + f.write("User=%s\n" % user) + f.write("Group=%s\n" % user) + f.write("WorkingDirectory=%s/app\n" % home_user) + f.write("ExecStart=%svenv/bin/gunicorn -w%s -b unix:%sgunicorn.sock --timeout 300 --error-logfile %s%s-error.log --access-logfile %s%s-access.log --reload %s\n" % (home_user, num_proc, home_user, home_user, name, home_user, name, args.app_flask)) + f.write("Restart=always\n") + f.write("Environment=USER=%s HOME=/home/%s\n" % (user, user)) + + f.write("[Install]\n") + f.write("WantedBy=multi-user.target\n") + +print("Downloading application using git...") + +if subprocess.call('sudo cp ./%s-%s.service /etc/systemd/system' % (args.domain, name), shell=True) > 0: + print('Error: cannot install app service in systemd...') + sys.exit(1) + + +if subprocess.call("sudo su %s -s /bin/bash -c 'git clone %s %sapp && cd %sapp && export GTAG=$(git describe --tags `git rev-list --tags --max-count=1`) && git checkout $GTAG -b latest-$GTAG'" % (user, args.git_url, home_user, home_user), shell=True) > 0: + print('Error: cannot download git packages in {}app'.format(home_user)) + sys.exit(1) + +if path=='/': + base_name_file='{}-001-{}.conf'.format(args.domain, name) +else: + base_name_file='{}-000-{}.conf'.format(args.domain, name) + +name_file='/home/{}/{}'.format(system_user, base_name_file) + +with open(name_file, 'w') as f: + + if path=='/': + f.write("\n" % path) + f.write("ProxyPass !\n") + f.write("\n") + + f.write("\n" % path) + #ProxyPass unix:/home/root/flask_rest/flaskrest.sock|http://127.0.0.1/ + f.write("ProxyPass unix:%sgunicorn.sock|http://127.0.0.1%s\n" % (home_user, path)) + f.write("ProxyPassReverse unix:%sgunicorn.sock|http://127.0.0.1%s\n" % (home_user, path)) + f.write("\n") + + +print('Updating apache configuration for wordpress outside of htdocs...') +if subprocess.call('sudo mv {} /etc/{}/vhosts.d/extra && sudo chown root:root /etc/{}/vhosts.d/extra/{}'.format(name_file, apache_cmd, apache_cmd, base_name_file), shell=True) > 0: + print('Error') + sys.exit(1) + +print("Preparing apache for use gunicorn...") + +if linux_distro=='debian' or linux_distro=='ubuntu': + if subprocess.call('sudo a2enmod proxy_http', shell=True) > 0: + print("Error: cannot enable proxy_http in apache in debian/ubuntu distro") + sys.exit(1) + +service=args.domain+'-'+name + +if subprocess.call("sudo systemctl enable %s && sudo systemctl start %s && sudo systemctl restart %s" % (service, service, apache_cmd), shell=True) > 0: + print("Error: cannot update and restart apache") + sys.exit(1) + +print("Flask app install successfully!") + diff --git a/scripts/webapps/phpmyadmin/delete_phpmyadmin.py b/scripts/webapps/phpmyadmin/delete_phpmyadmin.py new file mode 100644 index 0000000..eb05906 --- /dev/null +++ b/scripts/webapps/phpmyadmin/delete_phpmyadmin.py @@ -0,0 +1,42 @@ +#!/usr/bin/python3 -u + +import argparse +import os +#from pastafariutils.unix import add_user, del_user +from pathlib import Path +from subprocess import call, DEVNULL +import json +import time +import shutil +import pwd +import distro +import subprocess +import re +import sys + + +parser=argparse.ArgumentParser(prog='delete_phpmyadmin.py', description='A tool for delete phpmyadmin') + +parser.add_argument('--home_user', help='Home where phpmyadmin resides', required=True) +parser.add_argument('--user', help='The user', required=True) + +print('Deleting PHPMyAdmin..') + +args=parser.parse_args() + +home_user=args.home_user + +if home_user.find('/htdocs/', -8)!=-1: + + if subprocess.call("sudo su %s -s /bin/bash -c 'rm -f -r %s && mkdir %s'" % (args.user, args.home_user, args.home_user), shell=True) > 0: + print('Error: cannot delete %s' % args.home_user) + sys.exit(1) + +else: + + if subprocess.call("sudo su %s -s /bin/bash -c 'rm -f -r %s'" % (args.user, args.home_user), shell=True) > 0: + print('Error: cannot delete %s' % args.home_user) + sys.exit(1) + +print('Deleted PHPMyAdmin successfully...') + diff --git a/scripts/webapps/phpmyadmin/install_phpmyadmin_site.py b/scripts/webapps/phpmyadmin/install_phpmyadmin_site.py new file mode 100644 index 0000000..642ccf1 --- /dev/null +++ b/scripts/webapps/phpmyadmin/install_phpmyadmin_site.py @@ -0,0 +1,205 @@ +#!/usr/bin/python3 -u + +import sys, os +import subprocess +import argparse +import platform +import shutil +import pathlib +import distro +import pwd +import getpass + +#import pymysql.cursors +#pymysql.install_as_MySQLdb + +pyv=platform.python_version_tuple() + +if pyv[0]!='3': + print('Need python 3 for execute this script') + sys.exit(1) + +parser = argparse.ArgumentParser(description='Script for create a new wordpress site.') + +parser.add_argument('--domain', help='The domain where is the site', required=True) +parser.add_argument('--home_user', help='The name of the new user', required=True) +parser.add_argument('--user', help='The name of the new user', required=True) +parser.add_argument('--path', help='The path of the wordpress install') + +parser.add_argument('--server_mysql', help='Server of MySQL database', required=True) + +parser.add_argument('--port_mysql', help='The port of the MySQL server', required=True, type=int) + +parser.add_argument('--php_version', help='PHP version', required=True) + +args = parser.parse_args() + +php_version=args.php_version + +php_command='/usr/bin/php'+str(php_version) + +linux_distro=distro.id() + +if linux_distro=='arch': + + php_command='/usr/bin/php-legacy' + +system_user=getpass.getuser() + +apache_cmd='apache2' +apachectl='apache2ctl' + +if linux_distro!='debian' and linux_distro!='ubuntu': + + apache_cmd='httpd' + apachectl='apachectl' + + if linux_distro=='rocky' or linux_distro=='fedora' or linux_distro=='almalinux' or linux_distro=='centos': + apache_group='apache' + php_command=php_command.replace('.', '') + + if linux_distro=='arch': + apache_group='http' + + +home_user=args.home_user + +if home_user.find('/', -1)==-1: + print("Error: you need backslash in home_user option") + exit(1) + +home_user_default=home_user.replace('/htdocs/', '') + +stat_group=os.stat(home_user) +uid=stat_group.st_uid + +user=pwd.getpwuid(uid)[0] + +if args.path and args.path!='/': + + home_user=args.home_user.replace('/htdocs/', args.path) + + """ + if not os.path.isdir(home_user): + #os.mkdir(home_user) + if subprocess.call("sudo su %s -s /bin/bash -c 'mkdir -p %s'" % (user, home_user), shell=True) > 0: + print("Error, cannot create phpmyadmin folder sudo su %s -s /bin/bash -c 'mkdir -p %s'" % (args.user, home_user)+"\n") + sys.exit(1) + else: + print("Error, exists a directory with same name, i cannot install phpmyadmin in this folder") + sys.exit(1) + """ + + #os.chdir(home_user) +else: + home_user=args.home_user + +phpmyadmin_dir=args.home_user.replace('/htdocs/', '/phpmyadmin/') + +if os.path.isdir(phpmyadmin_dir): + print('Cleaning directory %s because is not empty, probably by an error in other install' % phpmyadmin_dir) + + if subprocess.call("sudo su %s -s /bin/bash -c 'rm -f -r %s'" % (user, phpmyadmin_dir), shell=True) > 0: + print('Error: cannot clean to {}\n'.format(phpmyadmin_dir)) + sys.exit(1) + + #os.chdir(home_user) +#print(home_user) +#sys.exit(0) +# Php-fpm for user + +#if not os.path.isfile('/etc/') + +#shutil.chown('/var/www/sites/'+args.domain, 'hosting', 'hosting') + +#Dash, the default debian stretch shell, don't support <<< + +#sudo debconf-set-selections <<< 'mariadb-server mariadb-server/root_password password your_password' +#sudo debconf-set-selections <<< 'mariadb-server mariadb-server/root_password_again password your_password' + +print('Installing phpmyadmin...') + +# composer create-project phpmyadmin/phpmyadmin --repository-url=https://www.phpmyadmin.net/packages.json --no-dev --working-dir={} + +ret_install=subprocess.call("sudo su %s -s /bin/bash -c '%s /usr/local/bin/composer create-project phpmyadmin/phpmyadmin --repository-url=https://www.phpmyadmin.net/packages.json --no-dev --working-dir=%s'" % (user, php_command, home_user_default), shell=True) + +if ret_install > 0 and ret_install!=5: + print('Error: cannot install phpmyadmin with composer in {} with code {}\n'.format(home_user, ret_install)) + sys.exit(1) + +if ret_install==5: + print('Updating phpmyadmin using composer...\n') + +if subprocess.call("sudo su %s -s /bin/bash -c 'cd %s && %s /usr/local/bin/composer update'" % (user,home_user_default+'/phpmyadmin/', php_command), shell=True) > 0: + print('Error: cannot update phpmyadmin with composer in {}\n'.format(home_user)) + sys.exit(1) + +if home_user.find('/htdocs/', -8)!=-1: + + if subprocess.call("sudo su %s -s /bin/bash -c 'cd %s && mv htdocs htdocs_old && mv phpmyadmin htdocs'" % (user, home_user_default), shell=True) > 0: + print('Error: cannot move phpmyadmin to {}\n'.format(home_user)) + sys.exit(1) + pass +else: + + if args.path!='/phpmyadmin/': + + if subprocess.call("sudo su %s -s /bin/bash -c 'cd %s && mv phpmyadmin %s'" % (user, home_user_default, home_user), shell=True) > 0: + print('Error: cannot move phpmyadmin to {}\n'.format(home_user)) + sys.exit(1) + + pass + +if args.server_mysql: + + #echo "\$cfg['Servers'][\$i]['host'] = '$MYSQL_HOST';" >> config.inc.php + # $cfg['Servers'][$i]['host'] = '%s'; + + config_servers=''; + + if subprocess.call("sudo su {} -s /bin/bash -c 'cp {}/config.sample.inc.php {}/config.inc.php && echo \"\$cfg[\\\"Servers\\\"][\$i][\\\"host\\\"] = \\\"{}:{}\\\";\" >> {}/config.inc.php'".format(user, home_user, home_user, args.server_mysql, args.port_mysql, home_user), shell=True) > 0: + print('Error: cannot update config of phpmyadmin {}\n'.format(home_user)) + sys.exit(1) + +""" +if subprocess.call("sudo mv %s %s & rmdir %s" % (home_user+'/phpmyadmin/*', home_user), shell=True) > 0: + print('Error: cannot move phpmyadmin to {}'.format(home_user)) + sys.exit(1) +""" + + +if args.path!='/': + + alias_apache=" Alias {} {} \n\ + \n\ + Options FollowSymLinks MultiViews \n\ + AllowOverride All \n\ + Require all granted \n\ + \n\ + \n\ + ProxyPass ! \n\ + \n\ + ".format(args.path[:-1], home_user, home_user, args.path[:-1]) + + base_name_file='{}-{}.conf'.format(args.domain, os.path.basename(args.path[:1])) + + name_file='/home/{}/{}-{}.conf'.format(system_user, args.domain, os.path.basename(args.path[:1])) + + with open(name_file, 'w') as f: + f.write(alias_apache) + + + print('Updating apache configuration for wordpress outside of htdocs...\n') + if subprocess.call('sudo mv {} /etc/{}/vhosts.d/extra && sudo chown root:root /etc/{}/vhosts.d/extra/{}'.format(name_file, apache_cmd, apache_cmd, base_name_file), shell=True) > 0: + print('Error') + sys.exit(1) + + print('Restarting apache...') + + if subprocess.call('sudo '+apachectl+' configtest && sudo systemctl restart '+apache_cmd, shell=True) > 0: + subprocess.call('sudo rm /etc/{}/vhosts.d/extra/{}'.format(apache_cmd, base_name_file), shell=True) + print('Error: Error in configtest\n') + sys.exit(1) + + +print('phpmyadmin installed!') diff --git a/scripts/webapps/phpmyadmin/update_phpmyadmin.py b/scripts/webapps/phpmyadmin/update_phpmyadmin.py new file mode 100644 index 0000000..d740fa0 --- /dev/null +++ b/scripts/webapps/phpmyadmin/update_phpmyadmin.py @@ -0,0 +1,53 @@ +#!/opt/pythonenv/bin/python3 -u + +import sys, os +import subprocess +import argparse +import platform +import shutil +import pathlib +import distro +import pwd +import getpass +import json + +#import pymysql.cursors +#pymysql.install_as_MySQLdb + +pyv=platform.python_version_tuple() + +if pyv[0]!='3': + print('Need python 3 for execute this script') + sys.exit(1) + +parser = argparse.ArgumentParser(description='Script for update phpmyadmin site.') + +parser.add_argument('--home_user', help='The path where phpmyadmin resides', required=True) +parser.add_argument('--user', help='The name of the new user', required=True) + +args = parser.parse_args() + +home_user=args.home_user +user=args.user + +json_return={} + +if subprocess.call("sudo su %s -s /bin/bash -c 'cd %s && composer update'" % (user, home_user), shell=True) > 0: + json_return['error']=1 + json_return['status']=1 + json_return['progress']=100 + json_return['message']='Error: I cannot update phpmyadmin' + + print(json.dumps(json_return)) + + exit(1) + +else: + + json_return['error']=0 + json_return['status']=0 + json_return['progress']=100 + json_return['message']='PHPMyAdmin updated...' + + print(json.dumps(json_return)) + diff --git a/scripts/webapps/delete_wordpress.py b/scripts/webapps/wordpress/delete_wordpress.py similarity index 100% rename from scripts/webapps/delete_wordpress.py rename to scripts/webapps/wordpress/delete_wordpress.py diff --git a/tasks/apache/scripts/delete_app.py b/tasks/apache/scripts/delete_app.py index f4f21bb..4643443 100644 --- a/tasks/apache/scripts/delete_app.py +++ b/tasks/apache/scripts/delete_app.py @@ -124,7 +124,7 @@ class ServerTask(WebAppTask): self.code_app=arr_webapp['code'] - self.files.append(['modules/apache/scripts/webapps/delete_'+arr_webapp['app_type']+'.py', 0o700]) + self.files.append(['modules/apache/scripts/webapps/'+arr_webapp['app_type']+'/delete_'+arr_webapp['app_type']+'.py', 0o700]) self.files.append(['modules/apache/scripts/webapps/delete_app_apache.py', 0o700]) home_user=arr_webapp['home']+'/htdocs/' @@ -145,7 +145,7 @@ class ServerTask(WebAppTask): #python3 delete_app_apache.py --domain prueba.cuchulu.com --webapp wordpress - self.commands_to_execute.append(['modules/apache/scripts/webapps/delete_'+arr_webapp['app_type']+'.py', '--user=%s --home_user=%s %s' % (arr_webapp['username'], home_user, db_opts)]) + self.commands_to_execute.append(['modules/apache/scripts/webapps/'+arr_webapp['app_type']+'/delete_'+arr_webapp['app_type']+'.py', '--user=%s --home_user=%s %s' % (arr_webapp['username'], home_user, db_opts)]) self.commands_to_execute.append(['modules/apache/scripts/webapps/delete_app_apache.py', '--domain={} --webapp={}'.format(arr_webapp['domain'], arr_webapp['app_name'])]) diff --git a/tasks/apache/scripts/flask.py b/tasks/apache/scripts/flask.py new file mode 100644 index 0000000..4dea9ca --- /dev/null +++ b/tasks/apache/scripts/flask.py @@ -0,0 +1,202 @@ +#/usr/bin/env python3 + +from collections import OrderedDict +import os +#from modules.pastafari2.models.servers import Server +from modules.apache.models.webservers import WebServer, VirtualHost +import json + +from modules.pastafari2.libraries.task import Task +from modules.pastafari2.models.pastafari2 import ServerDbTask +from paramecio2.libraries.db import coreforms +from paramecio2.libraries.i18n import I18n +from paramecio2.libraries.formsutils import show_form +from paramecio2.libraries.db.extrafields.usernamefield import UserNameField +from paramecio2.libraries.db.extrafields.emailfield import EmailField +from paramecio2.libraries.db.extrafields.urlfield import DomainField, GitUrlField +from modules.apache.libraries.webapptask import WebAppTask +from flask import url_for, request +import re + +class ServerTask(WebAppTask): + + def __init__(self, server, conn, remote_user='root', remote_password='', private_key='./ssh/id_rsa', password_key='', remote_path='pastafari2', task_id=0, data={}, port=22): + + super().__init__(server, conn, remote_user, remote_password, private_key, password_key, remote_path, task_id, data, port) + + self.name_task='Install Flask app in an Apache Httpd Server' + + self.description_task='Install Flask app using git in an Apache Httpd Server.' + + self.codename_task='apache_webserver_flask' + + self.files=[['modules/apache/scripts/webapps/flask/install_flask_site.py', 0o700]] + + #THe files to delete + + self.delete_files=[] + + self.delete_directories=['modules/apache/scripts'] + + self.arr_form=OrderedDict() + + self.arr_form['path']=coreforms.BaseForm('path', '') + + self.arr_form['path'].required=True + + self.arr_form['path'].label='The path of flask application' + self.arr_form['path'].help='The path of flask application.

For example, if you have a domain called http://example.com, if you install in / path, you access to flask app, directly in http://example.com.
If you add path to /webapp/, the flask webapp site will be accesible using http://example.com/webapp' + + self.arr_form['git_url']=coreforms.BaseForm('git_url', '') + + self.arr_form['git_url'].required=True + + self.arr_form['git_url'].label='The git url used for get the flask app' + self.arr_form['git_url'].help='The git url used for get the flask app. Pastafari get the last tag of the git repo and install it in webserver' + + self.arr_form['dependencies']=coreforms.BaseForm('dependencies', '') + + #self.arr_form['dependencies'].required=True + + self.arr_form['dependencies'].label='The python dependencies of the app' + + self.arr_form['dependencies'].help='The python dependencies of the app separated by commas. If your application need extra dependencies, for example, pymysql or paramiko, use this string in form: pymsql,paramiko' + + self.arr_form['app_flask']=coreforms.BaseForm('app_flask', '') + + self.arr_form['app_flask'].required=True + + self.arr_form['app_flask'].label='The app flask string used for gunicorn.' + + self.arr_form['app_flask'].help='The app flask string used for gunicorn. If you have a principal file of gunicorn called app, with a flask app called "app", you can use app:app' + + + def pre_task(self): + + if not super().pre_task(): + return False + + ##python3 install_flask_site.py --domain red.cuchulu.com --home_user /home/absurdo/sites/red.cuchulu.com/superapp/ --git_url https://webtsys@bitbucket.org/paramecio/flasktest.git --user=absurdo --dependencies=paramiko,pymysql --app_flask=app:app --path /superapp/ + + install_flask='--domain %s --home_user %s --git_url %s --user %s --dependencies=%s --app_flask %s --path %s' % (self.data['domain'], self.data['home_user'], self.data['git_url'], self.data['username'], self.data['dependencies'], self.data['app_flask'], self.data['path']) + + self.commands_to_execute.append(['modules/apache/scripts/webapps/flask/install_flask_site.py', install_flask]) + + + + return True + + def form(self, t, yes_error=False, pass_values=False, values={}): + + #Here load the form for it task + + return '

'+I18n.lang('webservers', 'add_flask_site', 'Add flask site')+'

'+show_form(values, self.arr_form, t, yes_error, pass_values) + + def check_form(self, post): + + return_val=True + + usernamefield=UserNameField('user') + + urlfield=GitUrlField('git_url') + + path=post['path'].strip() + + if 'path' in post: + if path=='': + + self.arr_form['path'].error=True + self.arr_form['path'].txt_error='Empty value.' + + return_val=False + + git_url=urlfield.check(request.form.get('git_url', '')) + + if git_url=='': + self.arr_form['git_url'].error=True + self.arr_form['git_url'].txt_error='Wrong value for http git url.' + + return_val=False + + app_flask=request.form.get('app_flask') + + if not re.match('\w+:\w+', app_flask): + self.arr_form['app_flask'].error=True + self.arr_form['app_flask'].txt_error='Bad format: the format must be app:app.' + + return_val=False + + dependencies=post['dependencies'].strip() + + arr_dep=[] + + if dependencies!='': + arr_dep=[dep.strip() for dep in dependencies.split(',') if dep.strip()!=''] + + final_dependencies='' + + if len(arr_dep)>0: + final_dependencies=",".join(arr_dep) + + virtualhost_id=self.data.get('virtualhost_id', '0') + # ImmutableMultiDict([('send_task', '1'), ('amp;virtualhost_id', '42')]) + + #print(virtualhost_id) + + domain='' + home='' + app_name='' + + with self.connection.query('select domain, home, username from virtualhost where id=%s', [virtualhost_id]) as cursor: + arr_virtualhost=cursor.fetchone() + + if arr_virtualhost: + domain=arr_virtualhost['domain'] + + home=arr_virtualhost['home']+'/flask/' + + app_name='flask' + + if path!='/': + home=arr_virtualhost['home']+path + app_name=os.path.basename(os.path.dirname(home)) + + username=arr_virtualhost['username'] + + if domain=='': + return_val=False + + if return_val: + + # (self.data['user_wp'], self.data['password_wp'], self.data['mysql_user'], self.data['mysql_password'], self.data['mysql_db'], self.data['email_wp'], self.data['domain_wp'], self.data['title_wp'], self.data['mysql_host'], 3306) + + self.data['domain']=domain + self.data['path']=path + + self.data['virtualhost_id']=virtualhost_id + + self.data['home_user']=home + self.data['username']=username + self.data['webapp']=app_name + self.data['dependencies']=final_dependencies + + self.data['git_url']=git_url + self.data['app_flask']=app_flask + + return return_val + + def post_task(self): + + #virtualhost=VirtualHost(self.connection) + + #virtualhost.safe_query() + + #if not virtualhost.insert({'virtualhost_id': int(self.data['virtualhost_id']), 'app_name': 'wordpress', 'path': self.data['path']}): + # return False + #print(virtualhost.show_errors()) + + #virtua + self.connection.query('insert into webapp (`virtualhost_id`, `app_name`, `app_type`, `path`, `data`) VALUES (%s, %s, %s, %s, %s)', [int(self.data['virtualhost_id']), self.data['webapp'], 'flask', self.data['path'], json.dumps(self.data)]) + + + return True diff --git a/tasks/apache/scripts/phpmyadmin.py b/tasks/apache/scripts/phpmyadmin.py new file mode 100644 index 0000000..a677724 --- /dev/null +++ b/tasks/apache/scripts/phpmyadmin.py @@ -0,0 +1,212 @@ +#/usr/bin/env python3 + +from collections import OrderedDict +import os +#from modules.pastafari2.models.servers import Server +from modules.apache.models.webservers import WebServer, VirtualHost +import json + +from modules.pastafari2.libraries.task import Task +from modules.apache.libraries.webapptask import WebAppTask +from modules.pastafari2.models.pastafari2 import ServerDbTask +from paramecio2.libraries.db import coreforms +from paramecio2.libraries.i18n import I18n +from paramecio2.libraries.formsutils import show_form +from paramecio2.libraries.db.extrafields.usernamefield import UserNameField +from paramecio2.libraries.db.extrafields.emailfield import EmailField +from paramecio2.libraries.db.extrafields.urlfield import DomainField +import uuid + +class ServerTask(WebAppTask): + + def __init__(self, server, conn, remote_user='root', remote_password='', private_key='./ssh/id_rsa', password_key='', remote_path='pastafari2', task_id=0, data={}, port=22): + + super().__init__(server, conn, remote_user, remote_password, private_key, password_key, remote_path, task_id, data, port) + + self.name_task='Install PHPMyAdmin in an Apache Httpd Server' + + self.description_task='Installation of PhpMyAdmin site in an Apache httpd server.' + + self.codename_task='apache_webserver_phpmyadmin' + + #self.files=[['modules/apache/scripts/check_php.sh', 0o700], ['modules/apache/scripts/install_phpmyadmin_site.py', 0o700], ['modules/apache/scripts/add_php_vhost.py', 0o700]] + self.files=[['modules/apache/scripts/webapps/phpmyadmin/install_phpmyadmin_site.py', 0o700]] + + + #THe files to delete + + self.delete_files=[] + + self.delete_directories=['modules/apache/scripts'] + + self.arr_form=OrderedDict() + + self.arr_form['path']=coreforms.BaseForm('path', '') + + self.arr_form['path'].required=True + + self.arr_form['path'].label='The path of phpmyadmin application' + self.arr_form['path'].help='The path of phpmyadmin application.

For example, if you have a domain called http://example.com, if you install in / path, you access to wordpress, directly in http://example.com.
If you add path to /phpmyadmin/, the phpmyadmin site will be accesible using http://example.com/phpmyadmin' + + self.arr_form['mysql_host']=coreforms.BaseForm('mysql_host', '') + + self.arr_form['mysql_host'].required=True + + self.arr_form['mysql_host'].label='The mysql/mariadb server used by phpmyadmin' + self.arr_form['mysql_host'].help='You can get the host from "MariaDB servers" section in the control panel' + + self.path_module='admin_app.webservers' + + + def pre_task(self): + + #self.commands_to_execute.append(['modules/apache/scripts/install_mariadb.py', '--password=%s' % self.extra_data['mysql_password']]) + + with self.connection.query('select php from virtualhost where id=%s', [self.data['virtualhost_id']]) as cursor: + arr_virtualhost=cursor.fetchone() + + + if arr_virtualhost['php']=='': + + self.logtask.insert({'status':1, 'progress': 100, 'error': 1, 'task_id': self.id, 'server': self.server, 'message': 'You need install php for this virtualhost!'}) + + return False + + if not super().pre_task(): + return False + + #self.commands_to_execute.append(['modules/apache/scripts/check_php.sh', '8.2']) + + #python3 install_phpmyadmin_site.py --home_user /home/developer/sites/enjoy.cuchulu.com/htdocs/ --user developer --path /sql/ --server_mysql localhost --port_mysql 3306 --domain enjoy.cuchulu.com + #python3 install_phpmyadmin_site.py --home_user /home/developer/sites/enjoy.cuchulu.com/htdocs/ --user developer --server_mysql localhost --port_mysql 3306 --domain enjoy.cuchulu.com + + path='--path='+self.data['path'] + + if path=='/': + path='' + pass + + mysql_port=3306 + + #self.commands_to_execute.append(['modules/apache/scripts/install_phpmyadmin.sh', '%s %s %s' % (self.data['home'], self.data['mysql_host'], self.data['username'])]) + self.commands_to_execute.append(['modules/apache/scripts/webapps/phpmyadmin/install_phpmyadmin_site.py', '--home_user=%s --user=%s %s --server_mysql=%s --port_mysql=%i --domain=%s --php_version=%s' % (self.data['home'], self.data['username'], path, self.data['mysql_host'], mysql_port, self.data['domain'], arr_virtualhost['php'])]) + + #self.commands_to_execute.append(['modules/apache/scripts/add_php_vhost.py', '--user=%s --php_version=8.2 --domain=%s' % (self.data['username'], self.data['domain']), 'sudo']) + + return True + + def form(self, t, yes_error=False, pass_values=False, values={}): + + #Here load the form for it task + + return '

'+I18n.lang('webservers', 'add_phpmyadmin_site', 'Add PHPMyAdmin')+'

'+show_form(values, self.arr_form, t, yes_error, pass_values) + + def check_form(self, post): + + return_val=True + + if 'mysql_host' in post: + + #for i in ('mysql_host'): + if post['mysql_host'].strip()=='': + + self.arr_form['mysql_host'].error=True + self.arr_form['mysql_host'].txt_error='Empty value.' + + return_val=False + + else: + return_val=False + + path='' + + if 'path' in post: + + path=post['path'].strip() + + if path=='': + + self.arr_form['path'].error=True + self.arr_form['path'].txt_error='Empty value.' + + return_val=False + + virtualhost_id=self.data.get('virtualhost_id') + + with self.connection.query('select domain, home, username from virtualhost where id=%s', [virtualhost_id]) as cursor: + arr_virtualhost=cursor.fetchone() + + if arr_virtualhost: + domain=arr_virtualhost['domain'] + home=arr_virtualhost['home']+'/htdocs/' + username=arr_virtualhost['username'] + + if domain=='': + return_val=False + + if return_val: + + # (self.data['user_wp'], self.data['password_wp'], self.data['mysql_user'], self.data['mysql_password'], self.data['mysql_db'], self.data['email_wp'], self.data['domain_wp'], self.data['title_wp'], self.data['mysql_host'], 3306) + + self.data['path']=path + + self.data['mysql_host']=post['mysql_host'].strip() + + self.data['virtualhost_id']=virtualhost_id + self.data['domain']=domain + self.data['home']=home + self.data['username']=username + self.data['webapp']='phpmyadmin' + + return return_val + + def post_task(self): + + #virtualhost=VirtualHost(self.connection) + + #virtualhost.safe_query() + + #if not virtualhost.insert({'virtualhost_id': int(self.data['virtualhost_id']), 'app_name': 'wordpress', 'path': self.data['path']}): + # return False + #print(virtualhost.show_errors()) + + #virtua + + app_name=os.path.basename(os.path.dirname(self.data['path'])) + + if app_name=='': + app_name='phpmyadmin' + + code_webapp=uuid.uuid4() + + self.connection.query('insert into webapp (`virtualhost_id`, `app_name`, `app_type`, `path`, `data`, `code`) VALUES (%s, %s, %s, %s, "{}", %s)', [int(self.data['virtualhost_id']), app_name, 'phpmyadmin', self.data['path'], code_webapp]) + + """ + | id | int(11) | NO | PRI | NULL | auto_increment | + | name | varchar(255) | NO | | | | + | file | varchar(255) | NO | | | | + | server_id | int(11) | YES | MUL | NULL | | + | position | int(11) | NO | | 0 | | + """ + + with self.connection.query('select id from serverdbtask where ip=%s', [self.server]) as cursor: + arr_server=cursor.fetchone() + + with self.connection.query('select domain, home, username from virtualhost where id=%s', [self.data['virtualhost_id']]) as cursor: + arr_virtualhost=cursor.fetchone() + + if arr_virtualhost: + domain=arr_virtualhost['domain'] + + if self.data['path']=='/': + + home=arr_virtualhost['home']+'/htdocs/' + + else: + home=arr_virtualhost['home']+self.data['path'] + + args='--user={} --home_user={}'.format(self.data['username'], home) + + self.connection.query('insert into updateserverscripts (`name`, `file`, `args`, `server_id`, `position`, `code`) VALUES (%s, %s, %s, %s, %s, %s)', ['phpadmin update', './modules/apache/scripts/webapps/phpmyadmin/update_phpmyadmin.py', args, arr_server['id'], 20, code_webapp]) + + return True