Added modify php.ini from phpserver module

This commit is contained in:
Antonio de la Rosa 2025-10-24 00:15:45 +02:00
parent 56157e4adb
commit ffdf81ec07
6 changed files with 295 additions and 37 deletions

View file

@ -1,6 +1,6 @@
from modules.phpserver import phpserver_app from modules.phpserver import phpserver_app
from settings import config from settings import config
from flask import g, url_for, request, session, make_response, abort from flask import g, url_for, request, session, make_response, abort, flash
from paramecio2.libraries.generate_admin_class import GenerateAdminClass from paramecio2.libraries.generate_admin_class import GenerateAdminClass
from paramecio2.libraries.lists import SimpleList from paramecio2.libraries.lists import SimpleList
from paramecio2.libraries.i18n import I18n, PGetText from paramecio2.libraries.i18n import I18n, PGetText
@ -20,6 +20,7 @@ from modules.pastafari2.models.tasks import Task as SSHTask
from modules.pastafari2.libraries.configtask import config_task from modules.pastafari2.libraries.configtask import config_task
from modules.pastafari2.libraries.progress import load_progress from modules.pastafari2.libraries.progress import load_progress
import os import os
import configparser
try: try:
import ujson as json import ujson as json
@ -98,8 +99,9 @@ def delete_php(php_server_id):
if arr_server: if arr_server:
#select * from virtualhost, webserver, serverdbtask, phpserver where virtualhost.webserver_id=webserver.id AND serverdbtask.id=webserver.server_id AND phpserver.server_id=serverdbtask.id AND phpserver.id=19 #select * from virtualhost, webserver, serverdbtask, phpserver where virtualhost.webserver_id=webserver.id AND serverdbtask.id=webserver.server_id AND phpserver.server_id=serverdbtask.id AND phpserver.id=19
with db.query('select count(*) as num_php_vhosts from virtualhost, webserver, serverdbtask, phpserver where virtualhost.webserver_id=webserver.id AND serverdbtask.id=webserver.server_id AND phpserver.server_id=serverdbtask.id AND phpserver.id=%s', [php_server_id]) as cursor: with db.query('select count(*) as num_php_vhosts from virtualhost, webserver, serverdbtask, phpserver where virtualhost.webserver_id=webserver.id AND serverdbtask.id=webserver.server_id AND phpserver.server_id=serverdbtask.id AND phpserver.id=%s AND virtualhost.php=%s', [php_server_id, arr_server['version']]) as cursor:
num_php_vhosts=cursor.fetchone()['num_php_vhosts'] num_php_vhosts=cursor.fetchone()['num_php_vhosts']
return t.load_template('del_phpserver.phtml', title=_('Remove PHP FPM server'), path_module='phpserver_app.php_dashboard', php_server_id=php_server_id, domain=arr_server['hostname'], num_php_vhosts=num_php_vhosts) return t.load_template('del_phpserver.phtml', title=_('Remove PHP FPM server'), path_module='phpserver_app.php_dashboard', php_server_id=php_server_id, domain=arr_server['hostname'], num_php_vhosts=num_php_vhosts)
@ -167,6 +169,7 @@ def php_edit_server(php_server_id):
if arr_server: if arr_server:
#arr_form=BaseForm
return t.load_template('edit_phpserver.phtml', title=_('Edit PHP FPM server'), path_module='phpserver_app.php_dashboard', domain=arr_server['hostname'], php_server_id=php_server_id) return t.load_template('edit_phpserver.phtml', title=_('Edit PHP FPM server'), path_module='phpserver_app.php_dashboard', domain=arr_server['hostname'], php_server_id=php_server_id)
@ -213,32 +216,42 @@ def get_php_server(php_server_id):
# No more of 60 seconds # No more of 60 seconds
arr_log={} if task_id:
check_task=True arr_log={}
result={}
while check_task:
with db.query('select * from logtask where task_id=%s order by id DESC limit 1', [task_id]) as cursor: check_task=True
result={}
while check_task:
arr_log=cursor.fetchone() with db.query('select * from logtask where task_id=%s order by id DESC limit 1', [task_id]) as cursor:
if arr_log:
if arr_log['status']==1: arr_log=cursor.fetchone()
if arr_log:
if arr_log['status']==1:
error=arr_log['error'] error=arr_log['error']
check_task=False check_task=False
if not error: if not error:
with db.query('select * from resulttask where task_id=%s', [task_id]) as cursor: with db.query('select * from resulttask where task_id=%s', [task_id]) as cursor:
result=cursor.fetchone() result=cursor.fetchone()
# PHP configuration
#
#config=configparser.ConfigParser()
#print(json.loads(result['message'])['file'])
#config.read_string(json.loads(result['message'])['file'])
#print(config['PHP']['display_errors'])
return {'error': error, 'error_form': error_form, 'log': arr_log, 'result': result, 'task_id': task_id} return {'error': error, 'error_form': error_form, 'log': arr_log, 'result': result, 'task_id': task_id}
@phpserver_app.route('/phpserver/save_php_ini/<int:php_server_id>/') @phpserver_app.route('/phpserver/save_php_ini/<int:php_server_id>/', methods=['POST'])
def save_php_ini(php_server_id): def save_php_ini(php_server_id):
db=g.connection db=g.connection
@ -248,6 +261,7 @@ def save_php_ini(php_server_id):
task_id=0 task_id=0
result={} result={}
arr_log={}
with db.query('select serverdbtask.hostname, serverdbtask.ip, serverdbtask.ssh_port, phpserver.version from serverdbtask, phpserver where phpserver.server_id=serverdbtask.id and phpserver.id=%s', [php_server_id]) as cursor: with db.query('select serverdbtask.hostname, serverdbtask.ip, serverdbtask.ssh_port, phpserver.version from serverdbtask, phpserver where phpserver.server_id=serverdbtask.id and phpserver.id=%s', [php_server_id]) as cursor:
arr_server=cursor.fetchone() arr_server=cursor.fetchone()
@ -255,5 +269,46 @@ def save_php_ini(php_server_id):
if arr_server: if arr_server:
sshtask=SSHTask(db) sshtask=SSHTask(db)
file=request.form.get('php_ini_file')
if file.strip()!='':
with open('./tmp/php.ini', 'w') as f:
f.write(file)
if not sshtask.run_task(arr_server['ip'], 'modules.phpserver.tasks.php.php.save_php_ini', 'Save PHP.ini in server', 'save_php_ini', 'Task for save php.ini config on server', {'version': arr_server['version'], 'php_server_id': php_server_id}, config_task.remote_user, '', '', url_for('phpserver_app.php_dashboard'), ssh_key_priv=config_task.ssh_private_key, ssh_key_password=config_task.ssh_private_key_password, send_task=True, ssh_port=arr_server['ssh_port']):
error=1
else:
error=0
task_id=sshtask.task_id
if task_id:
check_task=True
while check_task:
with db.query('select * from logtask where task_id=%s order by id DESC limit 1', [task_id]) as cursor:
arr_log=cursor.fetchone()
if arr_log:
if arr_log['status']==1:
error=arr_log['error']
check_task=False
if not error:
flash(_('The php configuration was sucessfully changed'))
return {'error': error, 'error_form': error_form, 'log': arr_log, 'result': result, 'task_id': task_id} else:
error=1
error_form['empty_file']=1
return {'error': error, 'error_form': error_form, 'log': arr_log, 'task_id': task_id}

View file

@ -34,7 +34,7 @@ if linux_distro=='debian':
if not os.path.isfile(path_php_ini): if not os.path.isfile(path_php_ini):
linux.json_log('Error: php.ini not found in {}'.path_php_ini(), error=1, status=1, progress=100, no_progress=0); linux.json_log('Error: php.ini not found in {}'+path_php_ini, error=1, status=1, progress=100, no_progress=0);
exit(1) exit(1)
php_ini_file='' php_ini_file=''

View file

@ -36,7 +36,7 @@ if linux_distro=='debian':
if not os.path.isfile('/etc/apt/sources.list.d/php.list'): if not os.path.isfile('/etc/apt/sources.list.d/php.list'):
# Add sury repos # Add sury repos
add_repos={'debian': "sudo apt-get update & sudo apt-get -y install lsb-release ca-certificates curl & sudo curl -sSLo /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg &sudo ln -s /usr/share/keyrings/deb.sury.org-php.gpg /etc/apt/trusted.gpg.d/deb.sury.org-php.gpg & sudo sh -c 'echo \"deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main\" > /etc/apt/sources.list.d/php.list'"} add_repos={'debian': "sudo curl -sSLo /tmp/debsuryorg-archive-keyring.deb https://packages.sury.org/debsuryorg-archive-keyring.deb && sudo dpkg -i /tmp/debsuryorg-archive-keyring.deb && sudo sh -c 'echo \"deb [signed-by=/usr/share/keyrings/debsuryorg-archive-keyring.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main\" > /etc/apt/sources.list.d/php.list' && sudo apt-get update"}
linux.exec(add_repos) linux.exec(add_repos)
@ -54,7 +54,7 @@ linux.json_log('Repos installed...', error=0, status=0, progress=100, no_progres
install_php={'debian': 'sudo DEBIAN_FRONTEND="noninteractive" apt-get install -y php{version}-fpm php{version}-gd php{version}-mysql php{version}-curl php{version}-mbstring php{version}-intl php{version}-imagick php{version}-xml php{version}-zip php{version}-redis unzip'.format(version=version)} install_php={'debian': 'sudo DEBIAN_FRONTEND="noninteractive" apt-get install -y php{version}-fpm php{version}-gd php{version}-mysql php{version}-curl php{version}-mbstring php{version}-intl php{version}-imagick php{version}-xml php{version}-zip php{version}-redis unzip'.format(version=version)}
install_php={'fedora': 'sudo dnf -y install php{version} php{version}-php-gd php{version}-php-mysqlnd php{version}-php-imap php{version}-php-intl php{version}-php-fpm php{version}-php-process composer unzip mariadb php{version}-php-pecl-zip'.format(version=version.replace('.', ''))} install_php['fedora']='sudo dnf -y install php{version} php{version}-php-gd php{version}-php-mysqlnd php{version}-php-imap php{version}-php-intl php{version}-php-fpm php{version}-php-process composer unzip mariadb php{version}-php-pecl-zip'.format(version=version.replace('.', ''))
install_php['almalinux']=install_php['fedora'] install_php['almalinux']=install_php['fedora']
install_php['rocky']=install_php['fedora'] install_php['rocky']=install_php['fedora']

91
scripts/save_php_ini.py Normal file
View file

@ -0,0 +1,91 @@
from pastafariutils import linux
import distro
import argparse
import os
import json
php_versions=['8.2', '8.3', '8.4']
linux_distro=distro.id()
parser=argparse.ArgumentParser(prog='save_php_ini.py', description='Script for save php.ini')
parser.add_argument('--version', help='The version of php', required=True)
#parser.add_argument('--ip', help='The IP where php-fpm receive orders')
args=parser.parse_args()
version=args.version
linux.json_log('Saving php.ini from server', error=0, status=0, progress=0, no_progress=1);
path_php_ini='/etc/php/php.ini'
if linux_distro=='debian':
path_php_ini='/etc/php/{}/fpm/php.ini'.format(version)
move_php_ini={'debian': 'sudo cp {} {}'.format(path_php_ini, path_php_ini+'.bak')}
move_php_ini['ubuntu']=move_php_ini['debian']
cp_php_ini={'debian': 'sudo cp ./tmp/php.ini {}'.format(path_php_ini)}
cp_php_ini['ubuntu']=cp_php_ini['debian']
linux.exec(move_php_ini)
linux.exec(cp_php_ini)
service_php={'debian': 'php{}-fpm.service'.format(version)}
service_php['ubuntu']=service_php['debian']
error=0
if not linux.systemd_service('restart', service_php):
restore_php_ini={'debian': 'sudo cp {} {}'.format(path_php_ini+'.bak', path_php_ini)}
restore_php_ini['ubuntu']=restore_php_ini['debian']
linux.json_log('Error: cannot save the new php.ini', error=1, status=1, progress=0, no_progress=1)
else:
linux.json_log('php.ini modified successfully', error=0, status=1, progress=100, no_progress=0)
# sudo systemctl restart php8.4-fpm
#linux.json_log('Getting php.ini from server', error=0, status=0, progress=0, no_progress=1);
"""
linux.json_log('Getting php.ini from server', error=0, status=0, progress=0, no_progress=1);
if not version in php_versions:
linux.json_log('Error: php version not supported', error=1, status=1, progress=100, no_progress=0);
exit(1)
path_php_ini='/etc/php/php.ini'
if linux_distro=='debian':
path_php_ini='/etc/php/{}/fpm/php.ini'.format(version)
#print(path_php_ini)
if not os.path.isfile(path_php_ini):
linux.json_log('Error: php.ini not found in {}'.path_php_ini(), error=1, status=1, progress=100, no_progress=0);
exit(1)
php_ini_file=''
with open(path_php_ini) as f:
php_ini_file=f.read()
#print(json.dumps({'error': 0, 'status': 1, 'progress': 100, 'no_progress':0, 'message': '{"distro": "'+distro.id()+'"}', 'result': 1}))
linux.json_log(json.dumps({'file':php_ini_file}), error=0, status=1, progress=100, no_progress=0, result=1)
"""

View file

@ -0,0 +1,68 @@
#/usr/bin/env python3
from collections import OrderedDict
import json
from modules.pastafari2.libraries.task import Task
from modules.pastafari2.models.pastafari2 import ServerDbTask
from modules.pastafari2.libraries.configtask import config_task
#import distro
class ServerTask(Task):
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='Get php.ini from server'
self.description_task='Get php.ini from server'
self.codename_task='save_php_ini'
self.files=[]
self.files=[['modules/phpserver/scripts/save_php_ini.py', 0o755]]
# Format first array element is command with the interpreter, the task is agnostic, the files in os directory. The commands are setted with 750 permission.
# First element is the file, next elements are the arguments
self.commands_to_execute=[['modules/phpserver/scripts/save_php_ini.py', '']]
#THe files to delete
self.delete_files=[]
#self.delete_directories=['modules/phpserver/scripts']
#self.task=Task(conn)
self.one_time=False
self.version='1.0'
self.path_module='php_app.php_dashboard'
def pre_task(self):
#self.commands_to_execute=[['modules/webservers/scripts/manager/${os_server}/manage_apache.py', '--password=%s' % self.extra_data['mysql_password']]]
# usage: manager.py [-h] --operation OPERATION --domain DOMAIN [--email EMAIL] [--user USER] [--root_dir ROOT_DIR] [--indexes] [--allow_override]
self.commands_to_execute=[['/home/{}/pythonenv/bin/python3 -u modules/phpserver/scripts/save_php_ini.py'.format(config_task.remote_user), '--version={}'.format(self.data['version'])]]
self.files.append(['./tmp/php.ini', 0o755])
#with open('./mo/php.ini', 'w') as f:
# f.write(self.data['file'])
return True
def post_task(self):
#vhost=VirtualHost(self.connection)
#vhost.safe_query()
#vhost.insert({'servers': servers, 'principal_ip': servers[0], 'domain': self.extra_data['domain'], 'email': self.extra_data['email'], 'user': self.extra_data['user'], 'root_dir': self.extra_data['root_dir'], 'indexes': self.extra_data['indexes'], 'allow_override': self.extra_data['allow_override']})
#if not vhost.set_conditions('WHERE domain=%s', [self.data['domain']]).delete():
return True

View file

@ -3,19 +3,24 @@
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ace-builds@1.43.4/css/ace.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ace-builds@1.43.4/css/ace.min.css">
</%block> </%block>
<%block name="content"> <%block name="content">
<h3>${_('Edit php.ini')}</h3> <p><a href="${url_for('phpserver_app.php_dashboard')}">${_('PHP servers list')}</a> &gt;&gt; ${_('Edit php.ini')}</p>
<h3>${_('Edit php.ini')} - ${domain}</h3>
<div class="form"> <div class="form">
<div id="php_ini" style="height:600px;"> <div id="php_ini" style="height:600px;">
</div> </div>
</div> </div>
<p> <p>
<form method="post" name="save_php_ini" id="save_php_ini"> <form method="post" name="save_php_ini" id="save_php_ini" action="${url_for('phpserver_app.save_php_ini', php_server_id=php_server_id)}">
<input type="hidden" name="php_ini_file" id="php_ini_file" value="" />
<input type="submit" name="php_ini" value="${_('Save php.ini')}" id="php_ini" /> <input type="submit" name="php_ini" value="${_('Save php.ini')}" id="php_ini" />
</form> </form>
</p> </p>
<p><a href="${url_for('phpserver_app.php_dashboard')}">${_('PHP servers list')}</a> &gt;&gt; ${_('Edit php.ini')}</p>
</%block> </%block>
<%block name="jscript_block"> <%block name="jscript_block">
<script language="Javascript" src="${make_media_url('js/jsutils/posting2.js', 'pastafari2')}"></script>
<script src=" https://cdnjs.cloudflare.com/ajax/libs/ace/1.43.3/ace.min.js"></script> <script src=" https://cdnjs.cloudflare.com/ajax/libs/ace/1.43.3/ace.min.js"></script>
<script> <script>
@ -65,22 +70,61 @@ $(document).ready( function (e) {
editor.setTheme("ace/theme/twilight"); editor.setTheme("ace/theme/twilight");
editor.session.setMode("ace/mode/ini"); editor.session.setMode("ace/mode/ini");
});
options={'url': '${url_for("phpserver_app.save_php_ini", php_server_id=php_server_id)}', 'loading': '#layer_loading', 'success': function (data) {
/*$('#save_php_ini').submit( function (e) {
document.getElementById('php_ini_file').value=editor.getValue();
});*/
options={'url': '${url_for("phpserver_app.save_php_ini", php_server_id=php_server_id)}', 'loading': '#layer_loading', 'success': function (data) {
if(!data.error) {
window.location='${url_for("phpserver_app.php_dashboard")}';
}
else {
alert(_('I cannot modify the php configuration!. Please try later.'));
}
}, 'error': function (data) {
}
}; console.log('Retry send the file because a horrible bug in ace editor...');
if(data.hasOwnProperty('error_form')) {
if(data.error_form.hasOwnProperty('empty_file')) {
//Try send again.
$('#save_php_ini').submit();
}
}
},
'before_send': function (jxhr, settings) {
//$('#php_ini_file').val(editor.getValue());
document.getElementById('php_ini_file').value=editor.getValue();
/*if(document.getElementById('php_ini_file').value=='') {
jxhr.abort();
alert('No file');
}*/
//console.log(editor.getValue());
}
};
$('#del_phpserver').sendPost(options); $('#save_php_ini').sendPost(options);
$('#save_php_ini').click( function (e) {
//console.log(editor.session.getValue());
}); });