Compare commits

...

3 Commits

9 changed files with 2897 additions and 20 deletions

Binary file not shown.

2562
app.log

File diff suppressed because it is too large Load Diff

View File

@@ -7,5 +7,14 @@
"project": "statuspage",
"git_url": "http://192.168.3.241:3000/xiaji/webstatus.git",
"remote_dir": "/home/xiaji"
},
"statuspage": {
"ip": "192.168.3.157",
"username": "xiaji",
"password": "xiaji",
"port": 22,
"project": "statuspage",
"git_url": "http://192.168.3.241:3000/xiaji/webstatus.git",
"remote_dir": "/home/xiaji"
}
}

View File

@@ -1152,14 +1152,20 @@ class GunicornTab(QWidget):
def on_server_control_result(self, success, message):
"""处理服务器控制结果"""
if success:
self.append_output(f"操作成功: {message}")
logger.info(f"服务器控制成功: {message}")
QMessageBox.information(self, "成功", message)
else:
self.append_output(f"操作失败: {message}")
logger.error(f"服务器控制失败: {message}")
QMessageBox.warning(self, "错误", f"服务器控制失败: {message}")
try:
if success:
self.append_output(f"操作成功: {message}")
logger.info(f"服务器控制成功: {message}")
QMessageBox.information(self, "成功", message)
else:
self.append_output(f"操作失败: {message}")
logger.error(f"服务器控制失败: {message}")
QMessageBox.warning(self, "错误", f"服务器控制失败: {message}")
except Exception as e:
error_msg = str(e)
self.append_output(f"处理服务器控制结果时发生异常: {error_msg}")
logger.error(f"处理服务器控制结果时发生异常: {error_msg}")
# 不显示错误对话框,只记录日志,避免程序退出
def run_gunicorn_command(self):
"""运行Gunicorn命令"""

View File

@@ -421,6 +421,11 @@ class NginxTab(QWidget):
self.download_site_config_btn.clicked.connect(self.download_site_config)
site_config_btn_layout.addWidget(self.download_site_config_btn)
# 添加静态文件映射按钮
self.add_static_mappings_btn = QPushButton("添加静态文件映射")
self.add_static_mappings_btn.clicked.connect(self.add_static_mappings)
site_config_btn_layout.addWidget(self.add_static_mappings_btn)
# 修改为Unix socket连接按钮
self.modify_to_unix_socket_btn = QPushButton("修改为Unix Socket连接")
self.modify_to_unix_socket_btn.clicked.connect(self.modify_to_unix_socket)
@@ -858,15 +863,25 @@ http {
server_config = next(iter(config.values()))
username = server_config.get('username', '')
project_name = server_config.get('project', '')
remote_dir = server_config.get('remote_dir', '')
git_url = server_config.get('git_url', '')
# 从git_url中提取项目名.git前的值
if git_url:
# 提取git_url中最后一个/和.git之间的部分
if '/' in git_url:
git_project_name = git_url.split('/')[-1]
if git_project_name.endswith('.git'):
git_project_name = git_project_name[:-4] # 移除.git后缀
else:
git_project_name = 'webstatus' # 默认值
else:
git_project_name = 'webstatus' # 默认值
# 根据要求构建静态文件路径
# BASE_DIR = Path(__file__).resolve().parent.parent
# STATIC_ROOT = BASE_DIR / "static"
# MEDIA_ROOT = BASE_DIR / "media"
# 在实际路径中这对应于项目目录下的static和media文件夹
static_path = f"{remote_dir}/{project_name}/static"
media_path = f"{remote_dir}/{project_name}/media"
# 静态文件结构为: /home/[username]/[git_url中的项目名]/[project]/static
# 媒体文件结构为: /home/[username]/[git_url中的项目名]/[project]/media
static_path = f"/home/{username}/{git_project_name}/static"
media_path = f"/home/{username}/{git_project_name}/media"
# 获取当前配置内容
current_config = self.site_config_editor.toPlainText()
@@ -874,14 +889,14 @@ http {
# 检查是否已经包含静态文件映射
if "location /static/" not in current_config:
# 添加静态文件映射配置
static_mapping = f"\n # 静态文件映射 (STATIC_ROOT = BASE_DIR / \"static\")\n"
static_mapping = f"\n # 静态文件映射 (路径: /home/{username}/{git_project_name}/{project_name}/static)\n"
static_mapping += f" location /static/ {{\n"
static_mapping += f" alias {static_path}/;\n"
static_mapping += f" expires 30d;\n"
static_mapping += f" }}\n"
# 添加媒体文件映射配置
static_mapping += f"\n # 媒体文件映射 (MEDIA_ROOT = BASE_DIR / \"media\")\n"
static_mapping += f"\n # 媒体文件映射 (路径: /home/{username}/{git_project_name}/{project_name}/media)\n"
static_mapping += f" location /media/ {{\n"
static_mapping += f" alias {media_path}/;\n"
static_mapping += f" expires 30d;\n"
@@ -931,7 +946,7 @@ http {
project_name = 'webstatus' # 默认值
# 构建Unix socket路径
unix_socket_path = f"unix:/home/{username}/{project_name}/sock/gunicorn.sock"
unix_socket_path = f"http://unix:/home/{username}/{project_name}/sock/gunicorn.sock"
# 获取当前配置内容
current_config = self.site_config_editor.toPlainText()
@@ -939,7 +954,7 @@ http {
# 查找并替换proxy_pass的值
import re
# 使用正则表达式匹配proxy_pass行
pattern = r'(\s+proxy_pass\s+)http://[^;]+;'
pattern = r'(\s+proxy_pass\s+)(http://[^;]+|unix:[^;]+);'
replacement = f'\1{unix_socket_path};'
new_config = re.sub(pattern, replacement, current_config)
@@ -1082,7 +1097,13 @@ http {
f"sudo chown -R {username}:www-data /home/{username}/{project_name}",
f"sudo chmod g+x /home/{username}/{project_name}",
f"sudo chown -R {username}:www-data /home/{username}/{project_name}/sock",
f"sudo chmod -R 770 /home/{username}/{project_name}/sock"
f"sudo chmod -R 770 /home/{username}/{project_name}/sock",
# 修复/home/xiaji目录权限
f"sudo chmod o+r /home/{username}",
# 修复后验证权限应显示drwxr-xr-x
f"ls -ld /home/{username}",
# 验证www-data能否正常访问目录
f"sudo -u www-data ls /home/{username}/{project_name}/static/admin/css/"
]
# 创建并启动权限设置线程

View File

@@ -188,6 +188,15 @@ class RemoteCommandsTab(QWidget):
self.clone_button = QPushButton("克隆项目")
self.clone_button.clicked.connect(self.clone_repository)
right_layout.addWidget(self.clone_button)
self.pull_button = QPushButton("拉取更新")
self.pull_button.clicked.connect(self.pull_repository)
right_layout.addWidget(self.pull_button)
self.handle_changes_button = QPushButton("处理本地更改")
self.handle_changes_button.clicked.connect(self.handle_local_changes)
right_layout.addWidget(self.handle_changes_button)
right_layout.addStretch()
clone_layout.addLayout(right_layout)
@@ -426,6 +435,140 @@ class RemoteCommandsTab(QWidget):
self.command_thread.finished_signal.connect(self.on_command_finished)
self.command_thread.start()
def pull_repository(self):
logger.info("拉取仓库更新")
if not self.ssh_client:
QMessageBox.warning(self, "警告", "请先连接到服务器")
return
remote_dir = self.remote_dir_display.text().strip()
if not remote_dir:
QMessageBox.warning(self, "警告", "请先设置远程目录")
return
# 从仓库URL中提取项目名称
repo_url = self.repo_url_input.text().strip()
if not repo_url:
QMessageBox.warning(self, "警告", "请输入仓库URL")
return
# 从URL中提取项目名例如http://example.com/repo.git -> repo
project_name = repo_url.split('/')[-1].replace('.git', '')
project_path = f"{remote_dir}/{project_name}"
self.output_text.clear()
self.status_label.setText("正在拉取仓库更新...")
# 构建拉取命令
pull_command = f"cd {project_path} && git pull --verbose"
# 创建并启动线程执行命令
self.command_thread = RemoteCommandThread(self.ssh_client, pull_command)
self.command_thread.output_signal.connect(self.append_output)
self.command_thread.finished_signal.connect(self.on_command_finished)
self.command_thread.start()
def handle_local_changes(self):
logger.info("处理本地更改")
if not self.ssh_client:
QMessageBox.warning(self, "警告", "请先连接到服务器")
return
remote_dir = self.remote_dir_display.text().strip()
if not remote_dir:
QMessageBox.warning(self, "警告", "请先设置远程目录")
return
# 从仓库URL中提取项目名称
repo_url = self.repo_url_input.text().strip()
if not repo_url:
QMessageBox.warning(self, "警告", "请输入仓库URL")
return
# 从URL中提取项目名例如http://example.com/repo.git -> repo
project_name = repo_url.split('/')[-1].replace('.git', '')
project_path = f"{remote_dir}/{project_name}"
self.output_text.clear()
self.status_label.setText("正在检查本地更改...")
# 创建对话框询问用户如何处理本地更改
reply = QMessageBox.question(
self,
"处理本地更改",
"检测到本地有未提交的更改,请选择处理方式:\n\n"
"是(Y) - 暂存更改(stash),拉取更新后再恢复\n"
"否(N) - 放弃本地更改,直接拉取更新\n"
"取消 - 取消操作",
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
QMessageBox.Cancel
)
if reply == QMessageBox.Yes:
# 暂存更改
self.status_label.setText("正在暂存更改...")
stash_command = f"cd {project_path} && git stash push -m 'Auto-stash before pull'"
self.command_thread = RemoteCommandThread(self.ssh_client, stash_command)
self.command_thread.output_signal.connect(self.append_output)
self.command_thread.finished_signal.connect(lambda success, msg: self.on_stash_finished(success, msg, project_path))
self.command_thread.start()
elif reply == QMessageBox.No:
# 放弃本地更改,强制拉取
self.status_label.setText("正在重置本地更改...")
reset_command = f"cd {project_path} && git reset --hard HEAD && git clean -fd"
self.command_thread = RemoteCommandThread(self.ssh_client, reset_command)
self.command_thread.output_signal.connect(self.append_output)
self.command_thread.finished_signal.connect(lambda success, msg: self.on_reset_finished(success, msg, project_path))
self.command_thread.start()
# 如果选择取消,不做任何操作
def on_stash_finished(self, success, message, project_path):
"""暂存操作完成后的处理"""
if success:
self.append_output("暂存更改成功,正在拉取更新...")
# 拉取更新
pull_command = f"cd {project_path} && git pull --verbose"
self.command_thread = RemoteCommandThread(self.ssh_client, pull_command)
self.command_thread.output_signal.connect(self.append_output)
self.command_thread.finished_signal.connect(lambda success, msg: self.on_pull_after_stash_finished(success, msg, project_path))
self.command_thread.start()
else:
self.status_label.setText("暂存更改失败")
self.status_label.setStyleSheet("color: red;")
self.append_output(f"暂存更改失败: {message}")
def on_pull_after_stash_finished(self, success, message, project_path):
"""暂存后拉取更新完成后的处理"""
if success:
self.append_output("拉取更新成功,正在恢复暂存的更改...")
# 恢复暂存的更改
pop_command = f"cd {project_path} && git stash pop"
self.command_thread = RemoteCommandThread(self.ssh_client, pop_command)
self.command_thread.output_signal.connect(self.append_output)
self.command_thread.finished_signal.connect(self.on_command_finished)
self.command_thread.start()
else:
self.status_label.setText("拉取更新失败")
self.status_label.setStyleSheet("color: red;")
self.append_output(f"拉取更新失败: {message}")
def on_reset_finished(self, success, message, project_path):
"""重置操作完成后的处理"""
if success:
self.append_output("重置本地更改成功,正在拉取更新...")
# 拉取更新
pull_command = f"cd {project_path} && git pull --verbose"
self.command_thread = RemoteCommandThread(self.ssh_client, pull_command)
self.command_thread.output_signal.connect(self.append_output)
self.command_thread.finished_signal.connect(self.on_command_finished)
self.command_thread.start()
else:
self.status_label.setText("重置本地更改失败")
self.status_label.setStyleSheet("color: red;")
self.append_output(f"重置本地更改失败: {message}")
def append_output(self, text):
self.output_text.append(text)

136
生产系统settings.py Normal file
View File

@@ -0,0 +1,136 @@
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-$w+8+hw%p$2xi_fi+7avahc&03-y@x05e^r02-x3nt5johmk6l'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['192.168.3.157']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'status',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'statuspage.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'statuspage.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# REST Framework settings
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
'DEFAULT_AUTHENTICATION_CLASSES': [
# 初期不使用认证后续可以添加Token认证
# 'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
# 初期允许所有访问,后续可以添加权限控制
'rest_framework.permissions.AllowAny',
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
],
}
STATIC_ROOT = BASE_DIR / 'static' # 注意这里是 'static' 而非 '/static'
MEDIA_ROOT = BASE_DIR / 'media'