Compare commits

..

379 Commits

Author SHA1 Message Date
耗子 b330f8de82 feat: 接口调整 2023-10-27 02:58:59 +08:00
耗子 66ae4e4537 feat: 入口不准设置成 /api 2023-10-27 00:44:25 +08:00
耗子 e975d0e03f fix: 统计数据库排除自带的 2023-10-27 00:42:38 +08:00
耗子 8b1e8176a1 fix: 修复 PostgreSQL 数据库数量计算 2023-10-26 13:30:25 +08:00
耗子 3af985e501 feat: 发布 v2.1.1 2023-10-26 13:03:37 +08:00
耗子 2c60481525 ci: try to fix public 2023-10-26 13:03:12 +08:00
耗子 93bbefd40e fix: lint 2023-10-26 12:37:35 +08:00
耗子 63865ff1da feat: 优化安全入口 2023-10-26 03:33:05 +08:00
耗子 1b75b3a9a5 feat: 插件列表支持分页 2023-10-25 23:39:21 +08:00
耗子 21ccf17439 fix: lint 2023-10-25 21:52:02 +08:00
耗子 b00ae6f008 fix: 更新版本号 2023-10-25 21:44:05 +08:00
耗子 5b83a2c067 feat: 更新日志接口 2023-10-25 21:42:41 +08:00
耗子 a4f1c8c6fa feat: 首页优化 2023-10-25 20:40:37 +08:00
耗子 abf5962821 chore: 修改赞助信息 2023-10-25 02:53:50 +08:00
耗子 1c7b14d803 feat: Create FUNDING.yml 2023-10-25 02:51:34 +08:00
耗子 f0c8deee7d chore: 修改许可证为 AGPL v3 2023-10-25 02:22:55 +08:00
耗子 e96d95700a feat: 校验后移除 checksums 文件 2023-10-25 02:14:33 +08:00
耗子 0e10823448 feat: 优化更新和重启流程 2023-10-24 03:15:09 +08:00
耗子 e28b00f76d feat: 优化更新和重启流程 2023-10-24 02:51:07 +08:00
耗子 76dde17573 feat: 校验面板安装包 2023-10-23 22:19:35 +08:00
耗子 342b8048f0 fix: 修复极狐的版本号获取 2023-10-23 21:59:50 +08:00
耗子 9e58b613df feat: 优化 shell 执行错误处理 2023-10-23 21:54:22 +08:00
耗子 fe66704aaf feat: 优化 shell 执行错误处理 2023-10-23 21:48:02 +08:00
耗子 b62bcbaa73 feat: init env in test 2023-10-23 21:30:20 +08:00
耗子 39039534ba feat: init env in test 2023-10-23 21:29:41 +08:00
耗子 fd0092a299 feat: 添加 checksums 校验 2023-10-23 21:26:07 +08:00
耗子 5ec25deaf6 feat: 安装脚本优化 2023-10-23 20:15:06 +08:00
耗子 af21a6307e feat: 为面板安装添加 checksum 验证 2023-10-23 20:12:42 +08:00
耗子 a7de247f60 feat: 优化 curl 命令 2023-10-23 19:41:21 +08:00
耗子 12c25bfcab feat: 支持获取指定版本 2023-10-23 19:39:38 +08:00
耗子 24a32c03fd chore: 移除 resources 文件夹 2023-10-23 16:03:16 +08:00
耗子 5c4346d101 fix(workflow): 移除 public 文件夹 2023-10-23 16:01:40 +08:00
耗子 a4c80dd919 fix(workflow): 修复 apt 2023-10-23 15:47:53 +08:00
耗子 ccfd5550b9 fix(CI): 修复测试 2023-10-23 15:45:18 +08:00
耗子 5217e04bbf Merge branch 'v2.1' 2023-10-23 15:37:21 +08:00
耗子 4203f1b1bf fix(CI): 修复产物传递 2023-10-23 15:37:09 +08:00
耗子 02e4536f62 fix(CI): 修复文件名错误 2023-10-23 11:38:52 +08:00
耗子 ab1ba21823 feat(CI): 添加下载前端构建 2023-10-23 10:34:28 +08:00
耗子 441327b80f fix(SSH): 规范端口类型 2023-10-23 03:26:54 +08:00
耗子 eb0df71ef5 feat: 支持 Websocket 2023-10-23 02:52:49 +08:00
耗子 50ec426181 feat: 同步前端接口更新 2023-10-23 02:37:19 +08:00
耗子 949248b994 docs: 更新说明 2023-10-22 14:19:59 +08:00
耗子 d2e904c557 feat: 同步 v2.1 前端修改 2023-10-22 14:15:59 +08:00
耗子 834d707710 feat: 发布 v2.0.58 2023-10-19 22:36:45 +08:00
耗子 03b3d776b1 docs: 更新赞助商信息 2023-10-19 14:04:45 +08:00
耗子 3b5df9765e feat: 优化安装脚本 2023-10-19 03:39:13 +08:00
耗子 14baa7f7c3 feat: 发布 v2.0.57 2023-10-19 03:16:59 +08:00
耗子 0ecd60184b feat: 移除更新代理 2023-10-19 03:13:42 +08:00
耗子 6fcd65d0dd feat: 下载节点全局替换 2023-10-19 02:43:18 +08:00
耗子 1ca0cc0fa3 feat: 发布 v2.0.56 2023-10-16 20:57:27 +08:00
耗子 b844081956 ci: 调整发布配置 2023-10-16 20:56:56 +08:00
耗子 2724ba2751 ci: 调整发布配置 2023-10-16 20:40:44 +08:00
耗子 1dbf2ea9a3 ci: 修复错误 2023-10-16 20:29:35 +08:00
耗子 07c4083005 feat: 发布 v2.0.54 2023-10-16 20:28:12 +08:00
耗子 032133b54a ci: 在极狐发布版本 2023-10-16 20:27:06 +08:00
耗子 e10e0d4b9b feat: 将限速的阿里云镜像更换为腾讯云镜像 2023-10-16 19:44:23 +08:00
耗子 22b9b7f2aa feat: 将限速的阿里云镜像更换为腾讯云镜像 2023-10-16 19:39:12 +08:00
耗子 97562f189e fix: 修复在有 swap 的情况下无法安装的 bug 2023-10-15 22:31:25 +08:00
耗子 50daebeb0e Merge remote-tracking branch 'origin/main' 2023-10-10 20:04:40 +08:00
耗子 4bf23ff7ba feat: 更新依赖机器人配置 2023-10-10 20:04:28 +08:00
耗子 013b70d7ad Merge branch 'renovate/github.com-bytedance-sonic-1.x' into 'main'
chore(deps): Update module github.com/bytedance/sonic to v1.10.2

See merge request haozi-team/panel!21
2023-10-10 02:00:28 +08:00
耗子 aecb0a2ee6 Merge remote-tracking branch 'origin/main' 2023-10-10 00:59:19 +08:00
耗子 74d2bda1fe feat: 发布 v2.0.53 2023-10-10 00:59:12 +08:00
Renovate 918bdd0d95 chore(deps): Update module github.com/bytedance/sonic to v1.10.2 2023-10-08 04:07:18 +00:00
耗子 d5108ae684 Merge branch 'renovate/github.com-goravel-framework-1.x' into 'main'
chore(deps): Update module github.com/goravel/framework to v1.13.2

See merge request haozi-team/panel!20
2023-10-07 20:23:34 +08:00
耗子 1165d149f3 Merge branch 'renovate/golang.org-x-exp-digest' into 'main'
chore(deps): Update golang.org/x/exp digest to 7918f67

See merge request haozi-team/panel!19
2023-10-07 20:23:20 +08:00
耗子 4c8f4fa4ea feat: 卸载面板删除 /usr/bin/panel 2023-10-07 20:05:07 +08:00
耗子 be74716f74 feat: 操作 swap 后检查 /etc/fstab 是否正确 2023-10-07 20:03:29 +08:00
耗子 fdfe5725fd Merge remote-tracking branch 'origin/main' 2023-10-07 19:55:11 +08:00
耗子 8f33693228 feat: 添加面板卸载脚本 2023-10-07 19:55:04 +08:00
Renovate d9b5ed096b chore(deps): Update module github.com/goravel/framework to v1.13.2 2023-10-07 10:12:51 +00:00
Renovate 4cae56a56e chore(deps): Update golang.org/x/exp digest to 7918f67 2023-10-06 14:06:37 +00:00
耗子 2898801b27 Merge branch 'renovate/github.com-imroc-req-v3-3.x' into 'main'
chore(deps): Update module github.com/imroc/req/v3 to v3.42.1

See merge request haozi-team/panel!18
2023-10-06 20:56:54 +08:00
Renovate 5a22fc8fe5 chore(deps): Update module github.com/imroc/req/v3 to v3.42.1 2023-10-06 11:06:40 +00:00
耗子 ac9642d344 Merge remote-tracking branch 'origin/main' 2023-10-06 14:59:41 +08:00
耗子 f542491a38 ci: 调整作业产物为 3 天过期 2023-10-06 14:59:34 +08:00
耗子 64163575e2 Merge branch 'renovate/golang.org-x-exp-digest' into 'main'
chore(deps): Update golang.org/x/exp digest to 3e424a5

See merge request haozi-team/panel!17
2023-10-06 14:26:11 +08:00
耗子 2e07a26646 fix: 创建网站同步创建 PostgreSQL 数据库 2023-10-06 14:07:53 +08:00
Renovate 36b1478e32 chore(deps): Update golang.org/x/exp digest to 3e424a5 2023-10-05 20:06:26 +00:00
耗子 e5b24f25bd docs: 更新 README 2023-10-06 03:25:34 +08:00
耗子 6a100245de Merge branch 'renovate/golang.org-x-crypto-0.x' into 'main'
chore(deps): Update module golang.org/x/crypto to v0.14.0

See merge request haozi-team/panel!16
2023-10-06 02:27:59 +08:00
耗子 046c28a387 feat: 安装脚本优化 2023-10-06 00:22:09 +08:00
Renovate 937e940dd8 chore(deps): Update module golang.org/x/crypto to v0.14.0 2023-10-05 16:18:22 +00:00
耗子 be7063b4fc fix: 回滚,OpenResty 需更新 1.22 后才能支持 OpenSSL 3 编译 2023-10-05 00:05:11 +08:00
耗子 70e9342c5d feat: 发布 v2.0.51 2023-10-04 23:49:34 +08:00
耗子 0756a7b507 feat: OpenResty 使用 OpenSSL 3 编译 2023-10-04 23:49:05 +08:00
耗子 47f104bcae feat: 发布 v2.0.50 2023-10-04 23:08:56 +08:00
耗子 d20e57dca9 feat: 移除 OpenResty 的 GeoIP 模块 2023-10-04 23:08:34 +08:00
耗子 09cc10a563 docs: 文档更新 2023-10-03 20:47:58 +08:00
耗子 b188b3f1b8 feat: 优化 arm 判断 2023-10-02 16:32:05 +08:00
耗子 99dac8721e feat: 更新 PostgreSQL 的描述 2023-09-30 23:42:56 +08:00
耗子 c93eb4b309 feat: 优化网站添加 2023-09-29 17:37:01 +08:00
耗子 266f12d15a feat: 发布 v2.0.49 2023-09-29 17:02:12 +08:00
耗子 3a18b36df2 feat: 优化面板更新校验 2023-09-28 20:23:08 +08:00
耗子 ebcc022418 fix: 发布 v2.0.48 2023-09-28 19:50:23 +08:00
耗子 aa0fb2afcc fix: 修复 MySQL 更新 2023-09-28 19:50:03 +08:00
耗子 bde2c50696 fix: 修复 MySQL 版本号未更新 2023-09-28 19:39:26 +08:00
耗子 0945949b37 fix: 多打了一个引号 2023-09-28 17:01:37 +08:00
耗子 4fcd65da70 feat: 发布 v2.0.45 2023-09-28 13:25:09 +08:00
耗子 afb12dd664 feat: 更新 MySQL 版本 2023-09-28 13:20:08 +08:00
耗子 8c5d0e905e feat: 优化 MySQL systemd 判断 2023-09-28 13:06:31 +08:00
耗子 92e77720f7 feat: 优化 MySQL EL9 兼容性 2023-09-28 02:48:24 +08:00
耗子 124912368e feat: 发布 v2.0.44 2023-09-26 17:58:30 +08:00
耗子 084f0a06ca fix: 修复 PostgreSQL 创建数据库未修改所有者 2023-09-26 16:48:36 +08:00
耗子 c08fd0af7f fix: 调整 fail2ban 安装 2023-09-26 01:58:40 +08:00
耗子 3229685729 fix: 修复 logind 的问题 2023-09-26 01:19:05 +08:00
耗子 77ae021a2f feat: 发布 v2.0.43 2023-09-26 01:15:09 +08:00
耗子 69cf5dcb65 fix: PostgreSQL 16 不讲武德,来骗,来偷袭 2023-09-26 01:14:44 +08:00
耗子 9bd9833ca9 feat: 发布 v2.0.42 2023-09-26 00:42:36 +08:00
耗子 5fb58476ba feat: 优化 PostgreSQL 安装更新 2023-09-26 00:41:55 +08:00
耗子 da4a04ad87 fix: 安装 PostgreSQL 后重启一次 2023-09-26 00:32:12 +08:00
耗子 ae4736d86e feat: 发布 v2.0.41 2023-09-26 00:07:10 +08:00
耗子 198c56cb25 feat: 更新 PostgreSQL 16.0 和 15.4 2023-09-25 23:59:24 +08:00
耗子 4950b48fc9 Merge remote-tracking branch 'origin/main' 2023-09-18 10:34:36 +08:00
耗子 3f323588c0 fix: 修复空目录打包 2023-09-18 10:34:29 +08:00
耗子 e651a8ed6b Merge branch 'renovate/goreleaser-goreleaser-action-5.x' into 'main'
chore(deps): Update goreleaser/goreleaser-action action to v5

See merge request haozi-team/panel!15
2023-09-16 11:06:16 +08:00
耗子 bc9274a8b7 Merge branch 'renovate/github.com-imroc-req-v3-3.x' into 'main'
chore(deps): Update module github.com/imroc/req/v3 to v3.42.0

See merge request haozi-team/panel!14
2023-09-16 02:52:17 +08:00
耗子 1047374c2b Merge branch 'renovate/github.com-bytedance-sonic-1.x' into 'main'
chore(deps): Update module github.com/bytedance/sonic to v1.10.1

See merge request haozi-team/panel!13
2023-09-16 02:40:17 +08:00
Renovate 1f2f51fb55 chore(deps): Update goreleaser/goreleaser-action action to v5 2023-09-15 18:25:32 +00:00
Renovate 872af0b298 chore(deps): Update module github.com/imroc/req/v3 to v3.42.0 2023-09-15 18:25:29 +00:00
Renovate bc22e23cda chore(deps): Update module github.com/bytedance/sonic to v1.10.1 2023-09-15 18:25:19 +00:00
耗子 4ca2446dc3 docs: 更新赞助商信息 2023-09-12 00:13:58 +08:00
耗子 840d6824f0 docs: 更新赞助商信息 2023-09-11 20:44:50 +08:00
耗子 f366e4e267 workflow: 更新版本 2023-09-11 20:17:15 +08:00
耗子 25436325b2 chore: 框架更新的其他调整和更新 PHP 版本号 2023-09-11 19:33:29 +08:00
耗子 25d295f4a1 chore: 框架更新的其他调整 2023-09-11 17:02:14 +08:00
耗子 f8d874b9d7 fix: 路由报错 2023-09-11 16:55:54 +08:00
耗子 959fdaa6de fix: 路由报错 2023-09-11 16:54:37 +08:00
耗子 c4d672173e chore: update framework 2023-09-11 16:43:39 +08:00
耗子 262e72c17a feat: 优化安装脚本 2023-08-28 01:16:10 +08:00
耗子 e260652373 feat: release v2.0.39 2023-08-27 11:49:41 +08:00
耗子 427f7dc230 feat: 添加网站前确保记录不存在 2023-08-27 11:48:38 +08:00
耗子 c32ae4a733 fix: src error 2023-08-19 00:03:29 +08:00
耗子 34d9d245e1 refactor: replace apt with apt-get 2023-08-18 14:28:04 +08:00
耗子 2a2008b959 feat: add rsyslog for Debian 12 2023-08-18 13:07:42 +08:00
耗子 bab4efa807 feat: release v2.0.37 2023-08-17 12:02:48 +08:00
耗子 5052170046 feat(toolbox): swap support btrfs 2023-08-17 12:02:08 +08:00
耗子 32fef1e9e4 fix(toolbox): swap permission 2023-08-17 11:54:46 +08:00
耗子 67ff105cba fix(toolbox): kb 2023-08-17 11:53:34 +08:00
耗子 514baf4fb3 feat: release v2.0.36 2023-08-16 21:21:17 +08:00
耗子 30f9fada39 feat: add avif for php >= 81 2023-08-16 13:35:42 +08:00
耗子 8b01035d1a docs: drop fastdun 2023-08-15 11:20:17 +08:00
耗子 883e489ca1 feat: release v2.0.35 2023-08-15 02:10:05 +08:00
耗子 d16854ceaf fix(website): close ssl port error 2023-08-15 02:09:11 +08:00
耗子 bdb5442659 feat(task): auto reload page 2023-08-15 02:02:50 +08:00
耗子 f991586f94 feat: release v2.0.34 2023-08-15 01:43:30 +08:00
耗子 b7869c36dc feat: add ssl info 2023-08-15 01:42:20 +08:00
耗子 83d7aec8f5 feat: release v2.0.33 2023-08-15 00:40:28 +08:00
耗子 b43e5b5c80 feat: toolbox plugin 2023-08-15 00:39:11 +08:00
耗子 acb792950a fix: tests 2023-08-14 22:40:37 +08:00
耗子 41d83719ff fix: tests 2023-08-14 22:29:32 +08:00
耗子 de1c269a4a refactor: tools 2023-08-14 22:26:42 +08:00
耗子 c3bf62ebf7 feat: new tools methods 2023-08-14 00:53:16 +08:00
耗子 317851d982 fix: php pdo_pgsql install 2023-08-14 00:51:10 +08:00
耗子 f52d95ae11 fix: arm mysql install 2023-08-14 00:38:22 +08:00
耗子 6420092c90 feat: release v2.0.32 2023-08-13 22:39:58 +08:00
耗子 2fa108dd67 feat: remove unnecessary bootstrap 2023-08-13 22:38:39 +08:00
耗子 86bfcfb9f1 fix(monitor): select date 2023-08-13 22:37:42 +08:00
耗子 db65a493dc feat: release v2.0.31 2023-08-13 16:01:00 +08:00
耗子 4dd99a149c feat: escape log output 2023-08-13 15:50:22 +08:00
耗子 5d1fbb2e2b feat: postgresql plugin 2023-08-13 15:37:23 +08:00
耗子 94569cca02 fix: mysql check 2023-08-13 11:21:30 +08:00
耗子 905aaf102b feat: update dependence 2023-08-10 02:17:25 +08:00
耗子 d91aa666cc feat: postgresql install script 2023-08-10 01:56:01 +08:00
耗子 4f90bbc177 workflow: optimize auto reply 2023-08-10 01:39:02 +08:00
耗子 f6c3bd27fd feat: release v2.0.30 2023-08-09 02:16:44 +08:00
耗子 137c5ceba4 fix: php redis script 2023-08-09 02:16:22 +08:00
耗子 c6f5b99373 docs: update readme 2023-08-09 01:12:27 +08:00
耗子 d7f647a8db feat: release v2.0.29 2023-08-09 00:55:07 +08:00
耗子 77277a6af6 feat: optimize config save 2023-08-09 00:54:38 +08:00
耗子 d9acaec3c5 feat: redis plugin 2023-08-09 00:50:45 +08:00
耗子 c8692844b6 workflow: delete 2023-08-08 02:31:14 +08:00
耗子 0b49301e9e feat: go mod tidy 2023-08-08 02:30:59 +08:00
耗子 30fded4552 ci: update 2023-08-08 02:00:30 +08:00
耗子 9b3b76d1d0 Merge branch 'renovate/github.com-imroc-req-v3-3.x' into 'main'
fix(deps): update module github.com/imroc/req/v3 to v3.40.1

See merge request haozi-team/panel!4
2023-08-07 14:11:35 +08:00
Renovate f37f22b86b fix(deps): update module github.com/imroc/req/v3 to v3.40.1 2023-08-07 05:20:46 +00:00
耗子 52eedad3da Merge branch 'renovate/github.com-iancoleman-strcase-0.x' into 'main'
fix(deps): update module github.com/iancoleman/strcase to v0.3.0

See merge request haozi-team/panel!3
2023-08-07 13:05:19 +08:00
耗子 0e2dda597f Merge branch 'renovate/golang.org-x-crypto-0.x' into 'main'
fix(deps): update module golang.org/x/crypto to v0.12.0

See merge request haozi-team/panel!5
2023-08-07 13:04:48 +08:00
Renovate 313511b474 fix(deps): update module golang.org/x/crypto to v0.12.0 2023-08-06 19:24:11 +00:00
Renovate d2ed2b5082 fix(deps): update module github.com/iancoleman/strcase to v0.3.0 2023-08-06 18:52:46 +00:00
耗子 cce19e1a64 Merge branch 'renovate/configure' into 'main'
Configure Renovate

See merge request haozi-team/panel!1
2023-08-07 02:13:45 +08:00
Renovate 62b84a8909 Add renovate.json 2023-08-06 17:58:04 +00:00
耗子 ff7b4f5f3b ci: delete 2023-08-07 01:26:40 +08:00
耗子 43a8d8cc2a ci: fix 2023-08-07 01:01:10 +08:00
耗子 bf09ffd316 workflow: delete unnecessary workflows 2023-08-07 00:30:16 +08:00
耗子 b0d08e2901 feat: panel update script 2023-08-05 16:10:24 +08:00
耗子 62684ccfda feat: release v2.0.28 2023-08-05 14:19:59 +08:00
耗子 6353231f4a feat: update openresty 1.21.4.2 2023-08-05 14:19:31 +08:00
耗子 6abd6b139f docs: Update README.md 2023-08-05 01:51:22 +08:00
耗子 40358b2551 fix(website): reload openresty after save raw config 2023-08-04 22:53:33 +08:00
耗子 6e6342f0a6 feat: release v2.0.27 2023-08-04 22:45:32 +08:00
耗子 cea485133f fix: website ssl and php 2023-08-04 22:44:58 +08:00
耗子 08e14a84a5 fix: lint 2023-08-04 02:38:44 +08:00
耗子 bc179923a0 feat: optimize readme 2023-08-04 02:31:14 +08:00
耗子 67ef7ccd7a feat: optimize readme 2023-08-04 02:23:54 +08:00
耗子 1abb9691f4 fix(safe): null rule 2023-08-04 00:33:27 +08:00
耗子 4dc2895781 feat: release v2.0.26 2023-08-03 23:39:02 +08:00
耗子 e7635d4b36 fix: lint 2023-08-03 23:34:18 +08:00
耗子 e731c025b5 feat: pure-ftpd plugin 2023-08-03 23:33:31 +08:00
耗子 8234a16f9e feat: release v2.0.25 2023-07-30 03:52:56 +08:00
耗子 0e3dba7dc8 fix: lint 2023-07-30 03:51:46 +08:00
耗子 7e8ef74bee feat: fail2ban plugin 2023-07-30 03:50:55 +08:00
耗子 26ef34ef9b refactor: rename 2023-07-29 02:39:32 +08:00
耗子 4aa6dfa1ee feat(ssh): auto refresh when save 2023-07-29 02:35:21 +08:00
耗子 51989254d6 feat: release v2.0.24 2023-07-28 04:12:34 +08:00
耗子 5cfeb49468 fix(website): open_basedir 2023-07-28 04:12:06 +08:00
耗子 614a5f15b5 fix(cron): backup path 2023-07-28 03:47:43 +08:00
耗子 f5a6f17108 fix(cron): frontend bug 2023-07-27 17:15:41 +08:00
耗子 6356b82a21 feat: release v2.0.23 2023-07-27 17:03:06 +08:00
耗子 b3b1afe77e feat(task): add time 2023-07-27 16:45:07 +08:00
耗子 f9628643be feat(cron): optimize frontend 2023-07-27 16:29:47 +08:00
耗子 c8352d567d fix: php imagemagick install 2023-07-27 16:12:09 +08:00
耗子 2b92a0c693 fix(info): php version check 2023-07-27 16:09:07 +08:00
耗子 8fec8af0d7 fix(ssl): read cert 2023-07-27 16:06:45 +08:00
耗子 5b83e042c2 fix(mysql): path 2023-07-27 15:52:57 +08:00
耗子 525cb154ca fix(website): ssl problem 2023-07-27 15:52:25 +08:00
耗子 1cbd282e40 fix(safe): ping status 2023-07-27 15:14:45 +08:00
耗子 9ffa32160b feat: release v2.0.22 2023-07-27 13:09:08 +08:00
耗子 872da5f8e1 fix(safe): ping status 2023-07-27 13:08:10 +08:00
耗子 eed3651cb1 fix(cron): editor space 2023-07-27 02:31:46 +08:00
耗子 653900fd73 fix(website): root setting and clean log 2023-07-27 02:29:00 +08:00
耗子 ff1f2569dd fix: login 2023-07-27 01:04:29 +08:00
耗子 0c6354fc6e feat: release v2.0.20 2023-07-27 00:57:58 +08:00
耗子 2ed5c36890 feat: add php 81 82 2023-07-27 00:57:13 +08:00
耗子 ecaf8edf14 feat: fix status 2023-07-27 00:47:54 +08:00
耗子 2429cf023a feat: release v2.0.19 2023-07-26 19:06:32 +08:00
耗子 c7adc39887 feat: update framework 2023-07-26 18:13:09 +08:00
耗子 f4e267ef1b feat: optimize openresty install 2023-07-26 15:26:22 +08:00
耗子 98bb24d97a fix: build 2023-07-26 15:22:38 +08:00
耗子 9e603a3003 revert: use v2 version 2023-07-26 15:16:24 +08:00
耗子 7164541415 feat: use v2 version 2023-07-26 15:15:47 +08:00
耗子 a51b391634 feat: use v2 version 2023-07-26 15:15:34 +08:00
耗子 edd3b2a622 fix: openresty install in rhel9 2023-07-26 14:59:42 +08:00
耗子 c55ef5c1f2 feat: release v2.0.18 2023-07-26 02:19:20 +08:00
耗子 65a46796ea feat: supervisor plugin and optimize code 2023-07-26 02:14:26 +08:00
耗子 b4720a1c84 feat: release v2.0.17 2023-07-25 23:42:27 +08:00
耗子 5ec6a88a60 fix: lint 2023-07-25 23:36:33 +08:00
耗子 cc70ab1fde feat: web ssh 2023-07-25 20:33:25 +08:00
耗子 cf58857fd1 workflow: fix issues-helper 2023-07-25 13:31:47 +08:00
耗子 cc5bacedee feat: support restart panel 2023-07-25 13:19:08 +08:00
耗子 fe0fe810ab feat: release v2.0.15 2023-07-25 03:27:18 +08:00
耗子 826b7f65f8 docs: update README 2023-07-25 03:26:50 +08:00
耗子 ce7a380e6e feat(cron): support backup 2023-07-25 03:21:00 +08:00
耗子 a128d295ea feat(task): show failed tasks 2023-07-25 00:24:28 +08:00
耗子 85db98ec10 feat: 移除插件作者字段 2023-07-25 00:20:31 +08:00
耗子 44ae4b9d67 feat: s3fs 插件 2023-07-25 00:16:00 +08:00
耗子 d9b4162e63 feat: 更新版本号 2023-07-24 21:25:05 +08:00
耗子 a15ee96156 refactor: database backup and restore 2023-07-24 19:21:15 +08:00
耗子 4e71e8884a fix(monitor): net count error 2023-07-24 18:56:49 +08:00
耗子 346bb2d2b9 fix(monitor): net count error 2023-07-24 18:55:28 +08:00
耗子 0b476c2764 fix(monitor): net count error 2023-07-24 18:53:50 +08:00
耗子 bd5854cef3 feat: website backup and restore 2023-07-24 18:46:38 +08:00
耗子 5d7ae8d632 fix: file upload 2023-07-24 18:19:13 +08:00
耗子 adbca77687 feat: release v2.0.12 2023-07-23 04:28:44 +08:00
耗子 6377a2111c feat(tools): swap add to 4G 2023-07-23 04:27:50 +08:00
耗子 c9cc9f1fa7 feat(tools): jump /var 2023-07-23 04:04:04 +08:00
耗子 49e32beb8a fix: rhel9 build 2023-07-23 04:02:24 +08:00
耗子 f6f10aca26 feat: release v2.0.11 2023-07-22 18:02:11 +08:00
耗子 cb5d9acf3f feat: add phpmyadmin 2023-07-22 18:01:16 +08:00
耗子 903218dabb feat: auto create php conf for openresty 2023-07-22 17:39:41 +08:00
耗子 71f0e5d7cd feat: auto setting website path user 2023-07-22 17:26:05 +08:00
耗子 a5e1fbc232 feat: update v2.0.10 2023-07-22 16:44:41 +08:00
耗子 1689ef4e4a feat: add task check in update 2023-07-22 03:15:48 +08:00
耗子 fb383f9f90 feat: update v2.0.9 2023-07-22 03:09:16 +08:00
耗子 624fc9c77c feat(cmd): update cleanTask 2023-07-22 03:02:09 +08:00
耗子 793b2ee989 fix: missing file 2023-07-22 02:58:39 +08:00
耗子 e56cf991ae fix: dos2unix 2023-07-22 02:50:45 +08:00
耗子 1daaab1e93 feat: update v2.0.7 2023-07-22 02:47:56 +08:00
耗子 b9f75534ef feat: update v2.0.7 2023-07-22 02:36:08 +08:00
耗子 594dfea986 feat: update v2.0.7 2023-07-22 02:31:07 +08:00
耗子 915403e3c0 feat: update 2023-07-21 15:27:52 +08:00
耗子 0715a4e497 feat: update 2023-07-21 15:27:42 +08:00
耗子 0ab4738e1d feat: update 2023-07-21 04:32:41 +08:00
耗子 0d4f8bbea1 feat: update 2023-07-21 02:26:12 +08:00
耗子 ea59149175 fix: remove file menu 2023-07-21 00:34:42 +08:00
耗子 87a7350f9a fix: some bugs 2023-07-21 00:28:44 +08:00
耗子 59243d5203 fix(cmd): optimize getInfo 2023-07-20 15:39:19 +08:00
耗子 83e2526ce8 fix(plugin controller): script path 2023-07-20 13:39:43 +08:00
耗子 1f5718cd67 fix(cmd): conf path 2023-07-20 01:46:05 +08:00
耗子 3d8f2948be fix(conf): disable debug 2023-07-20 01:45:12 +08:00
耗子 6ef713ab3d fix(install script): oom 2023-07-20 01:30:35 +08:00
耗子 feb377a8f1 fix(install script): run migrate 2023-07-20 01:21:20 +08:00
耗子 bce2f27500 feat(website controller): optimize ssl config 2023-07-20 01:10:27 +08:00
耗子 5ce65653ad refactor: packages to pkg 2023-07-20 01:06:49 +08:00
耗子 ec7138ae2a feat: website controller 2023-07-20 01:03:05 +08:00
耗子 46644c352d feat: optimize code 2023-07-19 01:23:31 +08:00
耗子 2a3119fe9a feat: cron controller 2023-07-19 00:24:41 +08:00
耗子 6119626f50 feat: monitor controller 2023-07-18 14:38:13 +08:00
耗子 c004acbfa0 feat: safe controller 2023-07-18 00:42:37 +08:00
耗子 da58071a0a feat: task controller 2023-07-17 23:18:02 +08:00
耗子 ab599ef0f7 feat: php74 2023-07-16 17:22:49 +08:00
耗子 03f531eff4 feat: fail2ban script 2023-07-15 04:25:39 +08:00
耗子 09d4d15f72 feat: update scripts 2023-07-15 04:09:46 +08:00
耗子 a4cc6570f4 fix: lint 2023-07-11 20:08:47 +08:00
耗子 9556aac923 fix: lint 2023-07-11 20:03:08 +08:00
耗子 8ef737253c fix: lint 2023-07-11 19:55:05 +08:00
耗子 047a743aed fix: lint 2023-07-11 19:52:24 +08:00
耗子 ab78122036 feat: mysql80 plugin 2023-07-11 19:52:08 +08:00
耗子 ce918533ab feat: mysql80 plugin 2023-07-11 19:49:27 +08:00
耗子 e5226c4bf3 fix: tests 2023-07-11 01:46:28 +08:00
耗子 98c4764b95 fix: tests 2023-07-11 01:40:27 +08:00
耗子 8b31415f5c fix: tests 2023-07-11 01:37:18 +08:00
耗子 b606431305 feat: system helpers and website service 2023-07-11 01:26:04 +08:00
耗子 e2c2717852 feat: update framework 2023-07-10 18:25:47 +08:00
耗子 4ff6561942 feat: update framework 2023-07-10 18:05:15 +08:00
耗子 f5529b732f feat: update framework 2023-07-10 17:47:15 +08:00
耗子 397273012c feat: update framework 2023-07-10 17:29:58 +08:00
耗子 91f1125e6a Merge remote-tracking branch 'origin/main'
# Conflicts:
#	go.mod
#	go.sum
2023-07-10 17:10:12 +08:00
耗子 e44a783e9f feat: update framework 2023-07-10 17:09:47 +08:00
dependabot[bot] b33a35286d build(deps): bump the go-modules group with 1 update (#8) 2023-07-10 04:17:21 +00:00
耗子 200d763ba4 refactor: plugin dir 2023-07-10 01:43:16 +08:00
耗子 b9b1735d03 feat: update config 2023-07-09 00:37:20 +08:00
耗子 b88a398343 feat: optimize openresty scripts 2023-07-08 02:39:45 +08:00
耗子 c4199dad4e feat: update
1. panel entrance
2. optimize cli
3. website service init
2023-07-08 02:26:42 +08:00
耗子 9034c76096 feat: remove tests 2023-07-07 20:45:54 +08:00
耗子 bd6cf76d1d fix: tests 2023-07-07 20:26:46 +08:00
耗子 ba3a1eb29e fix: tests 2023-07-07 20:09:31 +08:00
耗子 88061496d8 fix: tests 2023-07-07 19:52:17 +08:00
耗子 f0c08d36dd fix: tests 2023-07-07 19:48:25 +08:00
耗子 7188af738b fix: tests 2023-07-07 19:46:22 +08:00
耗子 3309b79f9c feat: setting service 2023-07-07 19:43:04 +08:00
耗子 f20e942bea fix: lint 2023-07-07 19:24:47 +08:00
耗子 92f84d278e feat: panel update 2023-07-07 19:09:46 +08:00
耗子 9769715295 fix: LICENSE 2023-07-07 18:08:34 +08:00
耗子 4e83f2850a fix: build error 2023-07-07 18:02:41 +08:00
耗子 599899d960 fix: url error 2023-07-07 17:24:55 +08:00
耗子 4c5c89094c feat: update openresty install script 2023-07-07 17:16:48 +08:00
dependabot[bot] 896c6fd144 Merge pull request #7 from HaoZi-Team/dependabot/go_modules/go-modules-f84cb69f2e 2023-07-04 03:06:05 +00:00
耗子 4bb07f1a20 fix: plugin check 2023-07-04 02:25:47 +08:00
dependabot[bot] 2cd1fb832b build(deps): bump the go-modules group with 1 update
Bumps the go-modules group with 1 update: [github.com/goravel/framework](https://github.com/goravel/framework).

- [Release notes](https://github.com/goravel/framework/releases)
- [Commits](https://github.com/goravel/framework/compare/v1.12.4...v1.12.5)

---
updated-dependencies:
- dependency-name: github.com/goravel/framework
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: go-modules
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-03 18:16:27 +00:00
耗子 9ad517863e workflow: fix build 2023-07-04 02:12:31 +08:00
耗子 7cd7aaa8d0 fix(plugin): openresty OS check 2023-07-04 02:10:17 +08:00
耗子 a46fec9016 feat: optimize views 2023-07-04 02:09:35 +08:00
耗子 86d5d22209 refactor: plugin 2023-07-04 01:36:32 +08:00
耗子 a07ac77d2b refactor: models 2023-07-04 01:31:55 +08:00
耗子 9d3417c6f3 workflow: optimize dependabot 2023-06-28 23:59:34 +08:00
耗子 9551213bfb workflow: optimize cr 2023-06-28 12:38:12 +08:00
耗子 f9f27d1d8a Merge remote-tracking branch 'origin/main' 2023-06-28 12:33:26 +08:00
耗子 2120957968 workflow: optimize cr 2023-06-28 12:32:28 +08:00
耗子 04e73859f7 workflow: optimize pr check and cr 2023-06-28 12:31:13 +08:00
dependabot[bot] 208a25899e build(deps): bump github.com/imroc/req/v3 from 3.37.1 to 3.37.2 (#5) 2023-06-28 04:10:59 +00:00
耗子 f972f849ae workflow: optimize pr check 2023-06-28 01:55:24 +08:00
耗子 6c4d95406f workflow: optimize pr check 2023-06-28 01:52:49 +08:00
耗子 4f5c6f3afe workflow: optimize pr check 2023-06-28 01:51:06 +08:00
耗子 545cf2c952 Merge remote-tracking branch 'origin/main' 2023-06-28 01:22:58 +08:00
耗子 f4beb731d8 workflow: optimize pr check 2023-06-28 01:22:16 +08:00
耗子 af6419971b workflow: add pr check 2023-06-28 01:17:29 +08:00
dependabot[bot] d49ddbeb74 Merge pull request #4 from HaoZi-Team/dependabot/go_modules/github.com/goravel/framework-1.12.4 2023-06-27 04:15:58 +00:00
dependabot[bot] 23e96aaf6d build(deps): bump github.com/goravel/framework from 1.12.3 to 1.12.4
Bumps [github.com/goravel/framework](https://github.com/goravel/framework) from 1.12.3 to 1.12.4.
- [Release notes](https://github.com/goravel/framework/releases)
- [Commits](https://github.com/goravel/framework/compare/v1.12.3...v1.12.4)

---
updated-dependencies:
- dependency-name: github.com/goravel/framework
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-06-27 04:12:12 +00:00
耗子 360e709ee9 feat: use 16k model 2023-06-27 12:10:52 +08:00
耗子 2c935023de feat: use 16k model 2023-06-26 02:15:48 +08:00
耗子 4607129933 feat: add code review 2023-06-26 02:14:13 +08:00
耗子 8f512a620e feat: add dependabot 2023-06-26 01:56:52 +08:00
耗子 6fbbd28d23 fix: goreleaser 2023-06-25 01:17:35 +08:00
耗子 175b413432 fix: goreleaser 2023-06-25 01:07:32 +08:00
耗子 e26ce4ce86 fix: goreleaser 2023-06-25 00:59:25 +08:00
耗子 6a09d1373e feat: optimize build workflow 2023-06-25 00:19:59 +08:00
耗子 6bdf850c58 feat: optimize build workflow 2023-06-25 00:11:16 +08:00
耗子 c36640c1d8 feat: optimize build workflow 2023-06-25 00:04:58 +08:00
耗子 f918f40c8d feat: build workflow 2023-06-24 23:53:13 +08:00
耗子 34077272df fix: workflow 2023-06-24 23:06:11 +08:00
耗子 ab6882e5f6 fix: lint 2023-06-24 22:44:48 +08:00
耗子 ff50f3e1de fix: lint 2023-06-24 22:40:04 +08:00
耗子 8b262cf289 feat: openresty plugin 2023-06-24 22:27:41 +08:00
耗子 1c0fb1d298 fix: tests 2023-06-23 04:26:37 +08:00
耗子 98a92da490 feat: add tests 2023-06-23 04:20:57 +08:00
耗子 5e4d02f2cc feat: readme add cards 2023-06-23 03:48:30 +08:00
耗子 3dc8f348c5 feat: home page add disk 2023-06-23 00:37:21 +08:00
耗子 674586b844 feat: home page 2023-06-22 23:00:33 +08:00
耗子 43a44b08b8 fix: actions 2023-06-22 19:56:16 +08:00
耗子 c16a30c434 feat: static use cdn 2023-06-22 19:53:24 +08:00
耗子 16d18d1052 feat: update views 2023-06-22 18:18:51 +08:00
耗子 5b72f4b09e feat: update echarts 2023-06-22 18:07:29 +08:00
耗子 4b2a722308 fix: lint 2023-06-22 17:56:24 +08:00
耗子 2e7d0b9b47 feat: github workflows 2023-06-22 17:49:15 +08:00
耗子 d2afa89d21 fix: lint 2023-06-22 17:01:56 +08:00
耗子 c6e34bdab9 feat: command and user service 2023-06-22 16:51:37 +08:00
耗子 6481c2e65e feat: captcha and login 2023-06-22 00:22:50 +08:00
耗子 c14f4de880 feat: v2 Initial commit 2023-06-22 00:09:56 +08:00
415 changed files with 21133 additions and 27800 deletions
+32
View File
@@ -0,0 +1,32 @@
root = "."
tmp_dir = "storage/temp"
[build]
bin = "./storage/temp/main.exe --env=panel.conf"
cmd = "go build -o ./storage/temp/main.exe ."
delay = 1000
exclude_dir = ["storage", "database"]
exclude_file = []
exclude_regex = []
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html"]
kill_delay = "0s"
log = "build-errors.log"
send_interrupt = false
stop_on_error = true
[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"
[log]
time = false
[misc]
clean_on_exit = false
+4
View File
@@ -0,0 +1,4 @@
# These are supported funding model platforms
open_collective: haozi-panel
custom: ['https://afdian.net/a/haozi-team']
+143
View File
@@ -0,0 +1,143 @@
name: 🐛 报告问题 (Bug Report)
description: 创建一个报告以帮助我们改进 (Create a report to help us improve)
title: "🐛 [Bug] "
labels: [ "☢️ Bug", "bug" ]
body:
- type: markdown
attributes:
value: |
**请仅使用 简体中文 或 英文 进行填写**
**Please only use Simplified Chinese or English to fill in**
- type: checkboxes
id: checks
attributes:
label: 在提问之前 (Before Asking)
description: |
提问之前,先回答几个小问题。
Before asking questions, answer a few quick questions.
options:
- label: 我已经搜索了现有的 Issues, Discussions 和 Google (I've searched the existing Issues, Discussions and Google)
required: true
- label: 我已经阅读了 README 中除版本记录以外的所有内容 (I've read everything in the README except the version notes)
required: true
- label: 我在提问题之前至少花费了 5 分钟来思考和准备 (I spend at least 5 minutes thinking and preparing before asking a question)
required: true
- label: 我没有改动过面板及系统的任何文件 (I have not changed any files of the panel and system)
required: false
- label: 这个问题可以被稳定复现 (The problem can be stably reproduced)
required: false
- label: 问题是在升级之后产生的 (The problem is generated after upgrading)
required: false
- type: dropdown
id: system
attributes:
label: 操作系统 (Operating System)
description: |
请提供安装面板的操作系统。
Please provide the operating system on which the panel is installed.
options:
- RockyLinux
- AlmaLinux
- Debian
- Other
validations:
required: true
- type: input
id: system-version
attributes:
label: 操作系统版本 (Operating System Version)
description: |
请提供操作系统的版本号。
Please provide the version number of the operating system.
placeholder: "9.0"
validations:
required: true
- type: input
id: version
attributes:
label: 耗子面板版本 (HaoZi Panel Version)
description: |
请提供面板的版本号。
Please provide the version number of the panel.
placeholder: "2.0.0"
validations:
required: true
- type: textarea
id: describe
attributes:
label: 描述问题 (Describe The Problem)
description: |
简明概要地描述你遇到的问题。
Briefly describe the problem you are having.
validations:
required: true
- type: textarea
id: reproduce
attributes:
label: 如何复现 (How To Reproduce)
description: |
重现该问题的详细步骤。
Detailed steps to reproduce the problem.
value: |
1. 安装面板
2. 设置 '...'
3. 点击 '...'
4. 出现问题
validations:
required: false
- type: textarea
id: expected
attributes:
label: 预期行为 (Expected Behavior)
description: |
简明概要地描述你期望发生的事情。
Briefly describe what you expect to happen.
validations:
required: true
- type: textarea
id: logs
attributes:
label: 相关日志 (Related Logs)
description: |
请复制并粘贴任何相关的日志输出。
Please copy and paste any relevant log output.
可以把文件拖入这个区域以添加日志文件。
Files can be dragged into this area to add log files.
面板日志文件可在 `/www/panel/storage/logs` 中找到。
Panel log files can be found in `/www/panel/storage/logs`.
validations:
required: false
- type: textarea
id: screenshots
attributes:
label: 截图 (Screenshots)
description: |
如果有,添加屏幕截图可帮助更快定位你的问题。
If so, adding screenshots can help locate your issue faster.
可以复制图片后在此区域内粘贴以添加图片。
Pictures can be copied and pasted in this area to add pictures.
如有必要,使用马赛克遮盖敏感信息。
Use a mosaic to obscure sensitive information if necessary.
validations:
required: false
- type: textarea
id: others
attributes:
label: 还有别的吗 (Anything Else)
description: |
运行环境?浏览器?软件版本?相关的配置?链接?参考资料?
Environment? Browser? Software version? Related configuration? Link? References?
任何能让我们对你所遇到的问题有更多了解的东西。
Anything that can give us more insight into the problem you're having.
validations:
required: false
- type: textarea
id: yellows
attributes:
label: 来点色图 (Porn Pictures)
description: |
如果你不提供色图而你的 Issue 中又有其他不符合标准的地方,那么你的 Issue 可能会被直接关闭。
If you don't provide some porn pictures and there are other non-conformities in your issue, then your issue may be closed directly.
validations:
required: false
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: ❓ 讨论、问答和非项目问题 (Discussions, questions, and non-project issues)
url: https://jq.qq.com/?_wv=1027&k=I1oJKSTH
about: 其他不明之处,请移步我们的QQ群 12370907 (For other unclear things, please move to our qq group 12370907)
@@ -0,0 +1,64 @@
name: ✨ 功能请求 (Feature Request)
description: 为这个项目提出一个想法 (Suggest an idea for this project)
title: "✨ [Feature] "
labels: [ "✏️ Feature", "enhancement" ]
body:
- type: markdown
attributes:
value: |
**请仅使用 简体中文 或 英文 进行填写**
**Please only use Simplified Chinese or English to fill in**
- type: checkboxes
attributes:
label: 在提问之前 (Before Asking)
description: |
提问之前,先回答几个小问题。
Before asking questions, answer a few quick questions.
options:
- label: 我已经搜索了全部 Issues 和 Commits (I have searched all Issues and Commits)
required: true
- label: 它们当中没有我将要提交的新功能 (None of them have new feature that I'm going to submit)
required: true
- type: textarea
id: feature
attributes:
label: 描述功能 (Describe Feature)
description: |
简明概要地描述你的新功能,以及它将解决什么问题。
Briefly describe your new feature and what problem it will solve.
validations:
required: true
- type: textarea
id: workflow
attributes:
label: 工作流程 (WorkFlow)
description: |
请向我们提供有关该功能的实现流程。
Please provide us with the implementation flow for this feature.
value: |
1. 新建文件 ....
2. 添加函数 ....
3. ...
validations:
required: true
- type: textarea
id: others
attributes:
label: 还有别的吗 (Anything Else)
description: |
运行环境?浏览器?软件版本?相关的配置?链接?参考资料?
Environment? Browser? Software version? Related configuration? Link? References?
任何能让我们对该功能的实现有更多帮助的东西。
Anything that can help us more with the implementation of this feature.
validations:
required: false
- type: textarea
id: yellows
attributes:
label: 来点色图 (Porn Pictures)
description: |
如果你不提供色图而你的 Issue 中又有其他不符合标准的地方,那么你的 Issue 可能会被直接关闭。
If you don't provide some porn pictures and there are other non-conformities in your issue, then your issue may be closed directly.
validations:
required: false
+32
View File
@@ -0,0 +1,32 @@
name: Build
on:
push:
branches:
- main
pull_request:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
goarch: [ amd64, arm64 ]
fail-fast: true
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
cache: true
go-version: 'stable'
- name: Install dependencies
run: go mod tidy
- name: Build ${{ matrix.goarch }}
env:
CGO_ENABLED: 0
GOOS: linux
GOARCH: ${{ matrix.goarch }}
run: go build -ldflags '-s -w --extldflags "-static -fpic"' -o panel-${{ matrix.goarch }}
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: panel-${{ matrix.goarch }}
path: panel-${{ matrix.goarch }}
+23
View File
@@ -0,0 +1,23 @@
name: Codecov
on:
push:
branches:
- main
pull_request:
jobs:
codecov:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version: 'stable'
- name: Install dependencies
run: go mod tidy
- name: Run tests with coverage
run: go test -v -coverprofile="coverage.out" ./...
- name: Upload coverage report to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage.out
token: ${{ secrets.CODECOV }}
+33
View File
@@ -0,0 +1,33 @@
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: 'stable'
- name: Fetch Frontend
run: |
sudo apt-get install -y curl jq unzip zip
curl -sSL https://api.github.com/repos/haozi-team/panel-frontend/releases/latest | jq -r ".assets[] | select(.name | contains(\"dist\")) | .browser_download_url" | xargs curl -L -o frontend.zip
rm -rf public
unzip frontend.zip
mv dist public
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v5
with:
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+44
View File
@@ -0,0 +1,44 @@
name: Issue Auto Reply
on:
issues:
types: [ labeled ]
permissions:
contents: read
jobs:
issue-reply:
permissions:
issues: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- name: ✏️ Feature
if: github.event.label.name == '✏️ Feature'
uses: actions-cool/issues-helper@v3
with:
actions: 'create-comment'
token: ${{ secrets.GITHUB_TOKEN }}
issue-number: ${{ github.event.issue.number }}
body: |
Hi @${{ github.event.issue.user.login }} 👋
我们认为您的建议非常有价值!欢迎提交 PR,请包含相应的测试用例、文档等,并确保 CI 通过,感谢和期待您的贡献!
We think your suggestion is very valuable! Welcome to submit a PR, please include test cases, documentation, etc., and ensure that the CI is passed, thank you and look forward to your contribution!
![aoligei](https://github.com/haozi-team/panel/assets/115467771/fb04debf-3f4c-4fac-a0b8-c3455f8e57a0)
- name: ☢️ Bug
if: github.event.label.name == '☢️ Bug'
uses: actions-cool/issues-helper@v3
with:
actions: 'create-comment'
token: ${{ secrets.GITHUB_TOKEN }}
issue-number: ${{ github.event.issue.number }}
body: |
Hi @${{ github.event.issue.user.login }} 👋
我们认为您的反馈非常有价值!欢迎提交 PR,请包含相应的测试用例、文档等,并确保 CI 通过,感谢和期待您的贡献!
We think your feedback is very valuable! Welcome to submit a PR, please include test cases, documentation, etc., and ensure that the CI is passed, thank you and look forward to your contribution!
![aoligei](https://github.com/haozi-team/panel/assets/115467771/fb04debf-3f4c-4fac-a0b8-c3455f8e57a0)
@@ -0,0 +1,25 @@
name: Issue Close Question
on:
schedule:
- cron: "0 0 * * *"
permissions:
contents: read
jobs:
issue-close-require:
permissions:
issues: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- name: needs more info
uses: actions-cool/issues-helper@v3
with:
actions: 'close-issues'
labels: 'question'
inactive-day: 3
body: |
由于该 Issue 3天未收到回应,现已被自动关闭,若有任何问题,可评论回复。
This issue has been closed automatically because it has not had recent activity for 3 days. If you have any questions, please comment here.
+26
View File
@@ -0,0 +1,26 @@
name: Lint
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
jobs:
lint:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version: 'stable'
cache: false
- name: Lint
uses: golangci/golangci-lint-action@v3
with:
skip-cache: true
skip-pkg-cache: true
skip-build-cache: true
version: latest
args: --timeout=30m ./...
+22
View File
@@ -0,0 +1,22 @@
name: Test
on:
push:
branches:
- main
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version: 'stable'
- name: Install dependencies
run: sudo apt-get install -y curl jq
- name: Set up environment
run: |
cp panel-example.conf .env
go run . artisan key:generate
- name: Run tests
run: go test ./...
+73 -2
View File
@@ -1,3 +1,74 @@
.idea
tmp
/.air.toml
/panel.conf
# Golang #
# `go test -c` 生成的二进制文件
*.test
# go coverage 工具
*.out
*.prof
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
# 编译文件 #
*.com
*.class
*.dll
*.exe
*.o
*.so
/panel
# 压缩包 #
# Git 自带压缩,如果这些压缩包里有代码,建议解压后 commit
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# 日志文件和数据库 #
*.log
*.sqlite
*.db
# 临时文件 #
tmp/
.tmp/
# 系统生成文件 #
.DS_Store
vendor/
.DS_Store?
.AppleDouble
.LSOverride
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
.TemporaryItems
.fseventsd
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# IDE 和编辑器 #
.idea/
/go_build_*
out/
.vscode/
.vscode/settings.json
*.sublime*
__debug_bin
.project
# 前端工具链 #
.sass-cache/*
node_modules/
/public
+94
View File
@@ -0,0 +1,94 @@
image: golang:bookworm
# 在每个任务执行前运行
before_script:
- mkdir -p .go
- go version
- go env -w GO111MODULE=on
- go env -w GOPROXY=https://goproxy.cn,direct
.go_cache:
variables:
GOPATH: $CI_PROJECT_DIR/.go
cache:
paths:
- .go/pkg/mod/
# 全局变量
variables:
OUTPUT_NAME: "panel"
GO111MODULE: "on"
GOPROXY: "https://goproxy.cn,direct"
stages:
- prepare
- build
- release
golangci_lint:
stage: prepare
image: golangci/golangci-lint:latest-alpine
extends: .go_cache
allow_failure: true
script:
- golangci-lint run --timeout 30m
unit_test:
stage: prepare
extends: .go_cache
allow_failure: true
script:
- rm -rf /etc/apt/sources.list
- rm -rf /etc/apt/sources.list.d/*
- wget -O /etc/apt/sources.list https://mirrors.ustc.edu.cn/repogen/conf/debian-http-4-bookworm
- apt-get update
- apt-get install -y curl jq
- cp panel-example.conf .env
- go run . artisan key:generate
- go test -v -coverprofile=coverage.txt -covermode=atomic ./...
build:
stage: build
extends: .go_cache
script:
- go mod download
- CGO_ENABLED=0 go build -ldflags '-s -w --extldflags "-static -fpic"' -o $OUTPUT_NAME
artifacts:
name: "$OUTPUT_NAME"
paths:
- $OUTPUT_NAME
expire_in: 3 days
fetch:
stage: build
image: alpine:latest
before_script:
- sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
- apk add --no-cache curl jq unzip zip
script:
- curl -sSL "https://jihulab.com/api/v4/projects/haozi-team%2Fpanel-frontend/releases" | jq -r '.[0].assets.links[] | select(.name | contains("dist")) | .direct_asset_url' | xargs curl -L -o frontend.zip
- rm -rf public
- unzip frontend.zip
- mv dist public
artifacts:
name: "frontend"
paths:
- public
expire_in: 3 days
release:
stage: release
dependencies:
- build
- fetch
image:
name: goreleaser/goreleaser
entrypoint: [ '' ]
only:
- tags
variables:
# Disable shallow cloning so that goreleaser can diff between tags to
# generate a changelog.
GIT_DEPTH: 0
script:
- goreleaser release --clean
+50
View File
@@ -0,0 +1,50 @@
project_name: panel
builds:
-
id: panel
binary: panel
env:
- CGO_ENABLED=0
- GOPROXY=https://goproxy.cn,direct
goos:
- linux
goarch:
- amd64
- arm64
goamd64:
- v2
ldflags:
- -s -w --extldflags "-static -fpic"
archives:
-
id: panel-archive
builds:
- panel
format: zip
wrap_in_directory: false
strip_parent_binary_folder: true
files:
- LICENSE
- public/*
- storage/*
- database/*
- scripts/*
- panel-example.conf
gitlab_urls:
api: https://jihulab.com/api/v4/
download: https://jihulab.com
# set to true if you use a self-signed certificate
skip_tls_verify: false
# set to true if you want to upload to the Package Registry rather than attachments
# Only works with GitLab 13.5+
#
# Since: v1.3
use_package_registry: true
# Set this if you set GITLAB_TOKEN to the value of CI_JOB_TOKEN.
#
# Since: v1.11
use_job_token: true
-98
View File
@@ -1,98 +0,0 @@
# 更新日志
所有重要的更改都将在此文件中记录。
## [20230130] - 常规更新
- 优化数据库备份流程
## [20230130] - 常规更新
- 代码格式化
- 更新许可证
- 修复更新备份逻辑错误
- 主页新增新年祝福
- 主页新增检查更新
## [20230113] - 常规更新
- 优化更新流程
- 优化备份流程
## [20230108] - 常规更新
- 提升面板安全性
- 修复网站删除报错的Bug
- 规范网站名称
## [20221222] - 常规更新
- 优化计划任务日志格式
- 网站管理支持分页
- 文件管理的初步实现
- 样式微调
- 部分代码优化
- 框架版本更新
## [20221212] - 常规更新
- 修复创建网站可能重复添加listen端口的Bug
## [20221210] - 安全更新
- 增强面板安全性
- 其他微调及Bug修复
## [20221208] - 常规更新
- 新增网站免费SSL证书申请
- 前端细节优化
## [20221205] - 常规更新
- 新增自动备份插件(需配合20221203+版本的面板使用)
- 优化面板命令行显示
- 前端细节优化
## [20221203] - 常规更新
- 修复禁用Ping不生效的问题
- 修复网站设置PHP版本未赋值的问题
- 新增网站目录备份功能
- 新增面板多用户登录功能
- 新增资源监控时间选择功能
- 实装网站运行状态设置功能
- 实装网站配置文件重置功能
- 前端多处优化
## [20221202] - 常规更新
- 修复网站添加数据库不能为空的问题
- 校验网站目录必须以/开头
- 修复网站名可以编辑的问题
- 新增面板API开关
- 新增计划任务模块
- 安装脚本优化,提高在不同地区下的安装成功率
## [20221201] - 首版发布
- 修复了二测时发现的一些问题
- 首发于Hostloc,感谢各位mjj大佬的支持。
## [20221130] - 内部二测
- 内部二测
- 修复了一测发现的问题
- 新增了一些插件,基本功能已经完善
## [20221121] - 内部一测
- 内部一测
## 2022-10 - 2022-11
- 重构版本开始开发
## 2022-07 - 2022-08
- 项目启动、早期开发
+17
View File
@@ -0,0 +1,17 @@
## 行为准则
耗子Linux面板遵守业界通用的行为准则。任何违反行为准则的行为都可以报告给我们:
- 参与者将容忍反对意见。
- 参与者必须确保他们的语言和行为没有人身攻击和贬低个人言论。
- 在解释他人的言行时,参与者应始终保持良好的意图。
- 不能容忍可合理视为骚扰的行为。
## Code of Conduct
The HaoZi Linux Panel complies with the industry's common code of conduct. Any breach of the Code of Conduct can be reported to us:
- Participants will be tolerant of opposing views.
- Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
- When interpreting the words and actions of others, participants should always assume good intentions.
- Behavior that can be reasonably considered harassment will not be tolerated.
+628 -169
View File
@@ -1,202 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Preamble
1. Definitions.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
The precise terms and conditions for copying, distribution and
modification follow.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
TERMS AND CONDITIONS
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
0. Definitions.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
"This License" refers to version 3 of the GNU Affero General Public License.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
A "covered work" means either the unmodified Program or a work based
on the Program.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
1. Source Code.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
END OF TERMS AND CONDITIONS
The Corresponding Source for a work in source code form is that
same work.
APPENDIX: How to apply the Apache License to your work.
2. Basic Permissions.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
Copyright [yyyy] [name of copyright owner]
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
http://www.apache.org/licenses/LICENSE-2.0
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+117 -21
View File
@@ -1,35 +1,131 @@
耗子Linux面板
===============
<h1 align="center">耗子 Linux 面板</h1>
#### 这是耗子Linux面板的开源仓库,基于Apache License 2.0协议进行开源,目前处于积极开发状态。
<p align="center">
<a href="https://github.com/haozi-team/panel/releases"><img src="https://img.shields.io/github/release/haozi-team/panel.svg"></a>
<a href="https://github.com/haozi-team/panel/actions"><img src="https://github.com/haozi-team/panel/actions/workflows/test.yml/badge.svg"></a>
<a href="https://goreportcard.com/report/github.com/haozi-team/panel"><img src="https://goreportcard.com/badge/github.com/haozi-team/panel"></a>
<a href="https://codecov.io/gh/haozi-team/panel"><img src="https://codecov.io/gh/haozi-team/panel/branch/main/graph/badge.svg?token=XFT5NGNSRG"></a>
<a href="https://img.shields.io/github/license/haozi-team/panel"><img src="https://img.shields.io/github/license/haozi-team/panel"></a>
</p>
#### 我们正在进行基于 Golang 的 V2 版本的开发,加入我们的 交流QQ群:[12370907](https://jq.qq.com/?_wv=1027&k=I1oJKSTH) | QQ频道:[耗子](https://pd.qq.com/s/fyol46wfy) 获取最新动态。
<p align="center">
[简体中文] | [<a href="README_EN.md">English</a>]
</p>
耗子 Linux 面板是针对我们自身业务需要使用 Golang 开发的轻量 Linux 服务器运维管理面板,以 GNU Affero General Public License v3.0 开源。
免责声明:严禁使用耗子 Linux 面板从事任何非法活动,非法站点请勿向我们请求任何形式的技术支持,如果在技术支持过程中发现非法内容,我们将立即停止技术支持并留存相关证据。
交流QQ群:[12370907](https://jq.qq.com/?_wv=1027&k=I1oJKSTH) | QQ频道:[pd.qq.com/s/fyol46wfy](https://pd.qq.com/s/fyol46wfy)
## 重要说明
目前我们正在重构面板前端部分开发 2.1 版本,v2.0.58 将是 2.0 的最后一个版本。
新前端将使用 Vue + Naive UI 开发,预计 10 月底可以完成。
存量用户请尽快更新至 v2.0.58,以便后续升级到 2.1 版本。
## 运行环境
| 系统 | 版本 |
|---------------|-----|
| CentOS Stream | 9 |
| CentOS Stream | 8 |
| RockyLinux | 9 |
| RockyLinux | 8 |
| AlmaLinux | 9 |
| AlmaLinux | 8 |
| 其他RHEL发行版 | 8 |
| 其他RHEL发行版 | 9 |
耗子Linux面板仅支持 `amd64` | `arm64` 架构下的主流系统的最新版本,不支持 `Ubuntu`,因为其发版太过频繁,难以维护。
广告: [`WeAvatar` —统一头像服务](https://weavatar.com)
低配机器建议使用 `Debian`,资源占用较 `RHEL` 系更低。其他机器建议使用 `AlmaLinux` | `RockyLinux`,维护周期更长也更稳定。
服务器赞助:
[![](https://img-cdn.haozi.xyz/2022/12/09/54a1b368700423a992789eca4af8b7e2.jpg)](http://www.ddunyun.com/aff/PNYAXMKI)
## 安装说明
不在下表中的其他系统(OpenCloudOS 8、Anolis 8、CentOS Stream 8/9、Debian 11等),可自行尝试安装,但不保证能够正常运行,且不提供无偿技术支持(理论上不会有大问题)。
CentOS Stream 可使用迁移脚本迁移至支持的系统: [CentOS 8/9 迁移脚本](https://github.com/haozi-team/byecentos)
| 系统 | 版本 |
|------------|----|
| RHEL | 9 |
| AlmaLinux | 9 |
| RockyLinux | 9 |
| Debian | 12 |
随着系统版本的不断更新,我们亦可能会终止部分过于老旧的系统的支持,以保证面板的稳定性。
## 安装面板
安装面板前,你需要了解LNMP环境的基本知识,以及如何处理常见的LNMP环境问题,不建议0基础的用户安装和使用耗子Linux面板([推荐: 宝塔 - 简单好用服务器运维面板](https://www.bt.cn/?invite_code=M190eXRpZWE=))。
如果你决定继续,请以`root`用户登录服务器,执行以下命令安装面板:
```shell
wget -O install_panel.sh https://dl.panel.haozi.xyz/script/install_panel.sh && bash install_panel.sh
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh.checksum.txt && sha256sum -c install_panel.sh.checksum.txt && bash install_panel.sh || echo "Checksum 验证失败,文件可能被篡改,已终止操作"
```
## 更新说明
## 卸载面板
优先建议备份数据重装系统,这样可以保证系统纯净。
如果你无法重装系统,请以`root`用户登录服务器,执行以下命令卸载面板:
```shell
panel update
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh.checksum.txt && sha256sum -c uninstall_panel.sh.checksum.txt && bash uninstall_panel.sh || echo "Checksum 验证失败,文件可能被篡改,已终止操作"
```
卸载面板前请务必备份好所有数据,提前卸载面板全部插件。卸载后数据将**无法恢复**!
## 日常维护
使用`panel`命令进行日常维护:
```shell
panel
```
在 [Wiki](https://github.com/haozi-team/panel/wiki) 中查看更多使用方法和技巧。
## 问题反馈
使用类问题,可在 [WePublish 社区论坛](https://wepublish.cn/forums) 提问或QQ群`@坤坤`寻求 AI 帮助,亦可在群里寻求付费支持。
面板自身问题,可在 GitHub 的`Issues`页面提交问题反馈,注意[提问的智慧](https://github.com/ryanhanwu/How-To-Ask-Questions-The-Smart-Way/blob/main/README-zh_CN.md)。
## 贡献代码
### 寻找/创建 Issue
您可以在 [Issue 列表](https://github.com/haozi-team/panel/issues) 中寻找或创建一个 Issue,留言表达想要处理该 Issue 的意愿,得到维护者的确认后,即可开始处理。
### 创建 PR
- 在开发过程中,如果遇到问题可以随时在 Issue 中详尽描述该问题,以进一步沟通,但在此之前请确保自己已通过 Google 等方式尽可能的尝试解决问题;
- PR 须提交至我们的极狐 GitLab 仓库[https://jihulab.com/haozi-team/panel](https://jihulab.com/haozi-team/panel),勿在 GitHub 上提交;
- 当 PR 开发完毕后,请为其添加 `🚀 Review Ready` 标签,维护者将及时进行评审;
- 我们非常欢迎您的贡献,将在下次发版时将您添加到首页贡献者中;❤️
## 赞助商
### CDN
- [无畏云加速](https://su.sctes.com/register?code=8st689ujpmm2p)
- [盾云CDN](http://cdn.ddunyun.com/)
### 对象存储
- [又拍云](https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral)
### DevOps
- [极狐 GitLab](https://www.jihulab.com/)
**接受云资源和资金赞助,可通过QQ群咨询联系**
## 贡献者
这个项目的存在要归功于所有做出贡献的人,参与贡献请先查看贡献代码部分。
<a href="https://github.com/DevHaoZi" target="_blank"><img src="https://avatars.githubusercontent.com/u/115467771?v=4" width="48" height="48"></a>
## Star 历史
<a href="https://star-history.com/#haozi-team/panel&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date" />
</picture>
</a>
+127
View File
@@ -0,0 +1,127 @@
<h1 align="center">HaoZi Linux Panel</h1>
<p align="center">
<a href="https://github.com/haozi-team/panel/releases"><img src="https://img.shields.io/github/release/haozi-team/panel.svg"></a>
<a href="https://github.com/haozi-team/panel/actions"><img src="https://github.com/haozi-team/panel/actions/workflows/test.yml/badge.svg"></a>
<a href="https://goreportcard.com/report/github.com/haozi-team/panel"><img src="https://goreportcard.com/badge/github.com/haozi-team/panel"></a>
<a href="https://codecov.io/gh/haozi-team/panel"><img src="https://codecov.io/gh/haozi-team/panel/branch/main/graph/badge.svg?token=XFT5NGNSRG"></a>
<a href="https://img.shields.io/github/license/haozi-team/panel"><img src="https://img.shields.io/github/license/haozi-team/panel"></a>
</p>
<p align="center">
[<a href="README.md">简体中文</a>] | [English]
</p>
The HaoZi Linux Panel is a lightweight Linux server operation and maintenance management panel developed using Golang for our own business needs. It is open source under the GNU Affero General Public License v3.0 protocol.
Disclaimer: It is strictly prohibited to use the HaoZi Linux Panel to engage in any illegal activities. Please do not request any form of technical support from us for illegal sites. If illegal content is discovered during the technical support process, we will immediately stop technical support and retain relevant evidence.
Communication QQ group: [12370907](https://jq.qq.com/?_wv=1027&k=I1oJKSTH) | QQ channel: [pd.qq.com/s/fyol46wfy](https://pd.qq.com/s/fyol46wfy)
## UI Screenshots
![UI Screenshots](ui.png)
## Operating Environment
HaoZi Linux Panel only supports the latest version of mainstream systems under the `amd64` | `arm64` architecture. It does not support `Ubuntu` because its releases are too frequent and difficult to maintain.
Recommended to use `Debian` for low-configuration machines, as its resource usage is lower than that of the `RHEL` system. For other machines, recommended to use `RockyLinux` | `AlmaLinux`, which has a longer maintenance cycle and is more stable.
For other systems not in the table below (OpenCloudOS 8, Anolis 8, CentOS Stream 8/9, Debian 11, etc.), you can try to install it yourself, but normal operation is not guaranteed, and free technical support is not provided (theoretically there will be no major question).
CentOS Stream can be migrated to a supported system using the migration script: [CentOS 8/9 Migration Script](https://github.com/haozi-team/byecentos)
| OS | Version |
|------------|---------|
| RHEL | 9 |
| RockyLinux | 9 |
| AlmaLinux | 9 |
| Debian | 12 |
As system versions are constantly updated, we may also terminate support for some older systems to ensure the stability of the panel.
## Install Panel
Before installing the panel, you need to understand the basic knowledge of the LNMP environment and how to deal with common LNMP environment problems. It is not recommended for users with zero basic knowledge to install and use HaoZi Linux Panel ([Recommended: aaPanel - easy-to-use server operation and maintenance panel](https://aapanel.com)).
If you decide to continue, please log in to the server as `root` user and execute the following command to install the panel:
```shell
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/install_panel.sh.checksum.txt && sha256sum -c install_panel.sh.checksum.txt && bash install_panel.sh || echo "Checksum Verification Failed, File May Have Been Tampered With, Operation Terminated"
```
## Uninstall Panel
Recommended to back up data and reinstall the system first, so that the system can be kept clean.
If you are unable to reinstall the system, log in to the server as the `root` user and execute the following command to uninstall the panel:
```shell
HAOZI_DL_URL="https://jihulab.com/haozi-team/download/-/raw/main/panel"; curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh && curl -sSL -O ${HAOZI_DL_URL}/uninstall_panel.sh.checksum.txt && sha256sum -c uninstall_panel.sh.checksum.txt && bash uninstall_panel.sh || echo "Checksum Verification Failed, File May Have Been Tampered With, Operation Terminated"
```
Before uninstalling the panel, please be sure to back up all data and uninstall all panel plugins in advance. The data will **not be recoverable** after uninstallation!
## Daily Maintenance
Use `panel` command for daily maintenance:
```shell
panel
```
See more usage methods and tips in [Wiki](https://github.com/haozi-team/panel/wiki).
## Feedback
For usage issues, you can ask questions in the [WePublish Community Forum](https://wepublish.cn/forums) or seek AI help in the QQ group `@坤坤`. You can also seek paid support in the group.
For issues with the panel itself, you can submit feedback on the `Issues` page of GitHub. Please note [the wisdom of asking questions](http://www.catb.org/~esr/faqs/smart-questions.html).
## Contribute code
### Find/Create Issue
You can find or create an Issue in [Issue List](https://github.com/haozi-team/panel/issues), leave a message to express your willingness to deal with the Issue, and get confirmation from the maintainer. Start processing.
### Create PR
- During the development process, if you encounter a problem, you can describe the problem in detail in the Issue at any time for further communication, but before doing so, please make sure that you have tried your best to solve the problem through Google and other methods;
- PRs must be submitted to our JiHu GitLab repository [https://jihulab.com/haozi-team/panel](https://jihulab.com/haozi-team/panel). Do not submit on GitHub;
- When the PR is completed, please add the `🚀 Review Ready` tag to it, and the maintainer will review it in time;
- We very much welcome your contributions and will add you to the homepage contributors in the next release; ❤️
## Sponsor
### CDN
- [无畏云加速](https://su.sctes.com/register?code=8st689ujpmm2p)
- [盾云CDN](http://cdn.ddunyun.com/)
### Object Storage
- [又拍云](https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral)
### DevOps
- [JiHu GitLab](https://www.jihulab.com/)
**Accept cloud resources and financial sponsorship, you can contact us through QQ group**
## Contributor
This project owes its existence to all those who have contributed. To contribute, please check the contributed code section first.
<a href="https://github.com/DevHaoZi" target="_blank"><img src="https://avatars.githubusercontent.com/u/115467771?v=4" width="48" height="48"></a>
## Star History
<a href="https://star-history.com/#haozi-team/panel&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=haozi-team/panel&type=Date" />
</picture>
</a>
+25
View File
@@ -0,0 +1,25 @@
## 安全说明
安全性是我们最关心的问题之一,我们已在多个不同应用的生产环境广泛应用耗子Linux面板,至今无一例安全事故。
耗子Linux面板采用业界多种方案尽可能保证面板的安全性,但是我们不能保证面板的绝对安全性,**因此我们不对面板的安全性做任何保证**。
如果您在使用面板的过程中发现任何安全问题,请勿提交 Issue,可通过以下方式直接联系我们:
- 邮箱:i@haozi.net
- QQ826896000
致某些 CVE 爱好者:通过面板 `access_token` 执行的任何操作(包括且不限于:获取 root 权限、读取/写入系统敏感文件、执行任意 shell 命令等)均不被认为是安全问题,请不要刷此类报告浪费彼此的时间,这类低水平的报告对你的简历也没有任何帮助。
## Security Policy
Security is one of our biggest concerns. We have widely used HaoZi Linux Panel in production environments for many different applications, and there has been no safety incident so far.
HaoZi Linux Panel adopts various solutions in the industry to ensure the security of the panel as much as possible, but we cannot guarantee the absolute security of the panel, **therefore we do not make any guarantees on the security of the panel**.
If you find any security issues while using the panel, please do not submit an Issue. You can contact us directly through the following methods:
- Email: i@haozi.net
- Telegram: @devhaozi
To some CVE enthusiasts: Any operation performed through the panel `access_token` (including but not limited to: obtaining root permissions, reading/writing system sensitive files, executing arbitrary shell commands, etc.) is not considered a security issue, please Dont waste each others time with these types of reports. These low-level reports wont do anything to help your resume.
-142
View File
@@ -1,142 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Monitor as MonitorModel;
use App\Models\Setting;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
class Monitor extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'monitor';
/**
* The console command description.
*
* @var string
*/
protected $description = '耗子Linux面板 - 系统监控';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
if (Setting::query()->where('name', 'monitor')->value('value')) {
$info = self::getNowMonitor();
MonitorModel::query()->create(['info' => json_encode($info)]);
// 删除过期的记录
$days = Setting::query()->where('name', 'monitor_days')->value('value');
MonitorModel::query()->where('created_at', '<', Carbon::now()->subDays($days))->delete();
$this->info(time().' 监控完成');
} else {
$this->info('监控未开启');
}
return Command::SUCCESS;
}
/**
* 系统资源统计
* @return array
*/
private function getNowMonitor(): array
{
// 第一次获取网络信息
$netInfo1 = getNetInfo();
// 卡它一秒钟
sleep(1);
// 第二次获取网络信息
$netInfo2 = getNetInfo();
// CPU统计信息及负载
$cpuInfoRaw = file_get_contents('/proc/cpuinfo');
$physicalArr = array();
$siblingsSum = 0;
preg_match("/(\d+\.\d+), (\d+\.\d+), (\d+\.\d+)/", exec('uptime'), $uptime);
$uptime1 = $uptime[1] ?? 0;
$processorArr = explode("\nprocessor", $cpuInfoRaw);
foreach ($processorArr as $v) {
preg_match("/physical id\s*:\s(.*)/", $v, $physical);
preg_match("/siblings\s*:\s(.*)/", $v, $siblings);
if (isset($physical[1])) {
if (!in_array($physical[1], $physicalArr)) {
if (isset($siblings[1])) {
$siblingsSum += $siblings[1];
}
}
$physicalArr[] = $physical[1];
}
}
// CPU使用率
$cpuUse = 0.1;
$cpuRaw = explode("\n", shell_exec('ps aux'));
// 弹出第一项和最后一项
array_pop($cpuRaw);
array_shift($cpuRaw);
// 获取当前php进程的pid
$pid = getmypid();
foreach ($cpuRaw as $v) {
$v = preg_replace("/\s+/", " ", $v);
$v = (explode(' ', $v));
// 排除当前进程
if ($v[1] == $pid) {
continue;
}
$cpuUse += isset($v[2]) ? (float) $v[2] : 0;
}
$cpuUse = $siblingsSum > 0 ? ($cpuUse / $siblingsSum) : $cpuUse;
$cpuUse = round($cpuUse, 2);
$cpuUse = min($cpuUse, 100);
// 内存使用率
$memRaw = explode("\n", shell_exec('free -m'));
foreach ($memRaw as $v) {
if (str_contains($v, 'Mem')) {
$memList = preg_replace("/\s+/", " ", $v);
} elseif (str_contains($v, 'Swap')) {
$swapList = preg_replace("/\s+/", " ", $v);
}
}
$memArr = explode(' ', $memList);
$swapArr = explode(' ', $swapList);
// 内存大小MB
$memTotal = $memArr[1];
// Swap大小MB
$swapTotal = $swapArr[1];
// 使用中MB
$memUse = (str_contains($memRaw[0], 'buff/cache')) ? $memArr[2] : ($memArr[2] - $memArr[5] - $memArr[6]);
// Swap使用中MB
$swapUse = $swapArr[2];
// 使用中%
$memUseP = round($memUse / $memTotal, 2) * 100;
// Swap使用中%
$swapUseP = round($swapUse / $swapTotal, 2) * 100;
// 1分钟负载%
$uptime1P = round(min($uptime1 * 10, 100), 2);
// 构建返回数组
$res['cpu_use'] = $cpuUse;
$res['uptime'] = $uptime1;
$res['uptime_p'] = $uptime1P;
$res['mem_total'] = $memTotal;
$res['mem_use'] = $memUse;
$res['mem_use_p'] = $memUseP;
$res['swap_total'] = $swapTotal;
$res['swap_use'] = $swapUse;
$res['swap_use_p'] = $swapUseP;
$res['tx_now'] = $netInfo2['tx'] - $netInfo1['tx'];
$res['rx_now'] = $netInfo2['rx'] - $netInfo1['rx'];
return $res;
}
}
-537
View File
@@ -1,537 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Plugin;
use App\Models\Setting;
use App\Models\Task;
use App\Models\User;
use App\Models\Website;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Symfony\Component\Console\Command\Command as CommandAlias;
class Panel extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'panel {action?} {a1?} {a2?} {a3?} {a4?} {a5?} {a6?} {a7?} {a8?} {a9?} {a10?}';
/**
* The console command description.
*
* @var string
*/
protected $description = '耗子Linux面板命令行工具';
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
// 检测是否以root用户运行
if (trim(shell_exec('whoami')) != 'root') {
$this->error('耗子Linux面板:请以root用户运行');
return 1;
}
$action = $this->argument('action');
switch ($action) {
case 'init':
$this->init();
break;
case 'update':
$this->update();
break;
case 'getInfo':
$this->getInfo();
break;
case 'getPort':
$this->getPort();
break;
case 'writePluginInstall':
$this->writePluginInstall();
break;
case 'writePluginUnInstall':
$this->writePluginUnInstall();
break;
case 'writeMysqlPassword':
$this->writeMysqlPassword();
break;
case 'cleanRunningTask':
$this->cleanRunningTask();
break;
case 'backup':
$this->backup();
break;
case 'writeSite':
$this->writeSite();
break;
case 'deleteSite':
$this->deleteSite();
break;
case 'writeSetting':
$this->writeSetting();
break;
case 'deleteSetting':
$this->deleteSetting();
break;
default:
$this->info('耗子Linux面板命令行工具');
$this->info('请使用以下命令:');
$this->info('panel update 更新/修复面板到最新版本');
$this->info('panel getInfo 重新初始化面板账号信息');
$this->info('panel getPort 获取面板访问端口');
$this->info('panel cleanRunningTask 强制清理面板正在运行的任务');
$this->info('panel backup {website/mysql/postgresql} {name} {path} 备份网站/MySQL数据库/PostgreSQL数据库到指定目录');
$this->warn('以下命令请在开发者指导下使用:');
$this->info('panel init 初始化面板');
$this->info('panel writePluginInstall {slug} 写入插件安装状态');
$this->info('panel writePluginUnInstall {slug} 移除插件安装状态');
$this->info('panel writeMysqlPassword {password} 写入MySQL root密码');
$this->info('panel writeSite {name} {status} {path} {php} {ssl} 写入网站数据到面板');
$this->info('panel deleteSite {name} 删除面板网站数据');
$this->info('panel writeSetting {name} {value} 写入/更新面板设置数据');
$this->info('panel deleteSetting {name} 删除面板设置数据');
break;
}
return CommandAlias::SUCCESS;
}
/**
* 初始化
* @return void
*/
private function init(): void
{
Setting::query()->updateOrCreate(['name' => 'name'], ['value' => '耗子Linux面板']);
Setting::query()->updateOrCreate(['name' => 'monitor'], ['value' => '1']);
Setting::query()->updateOrCreate(['name' => 'monitor_days'], ['value' => '30']);
Setting::query()->updateOrCreate(['name' => 'mysql_root_password'], ['value' => '']);
Setting::query()->updateOrCreate(['name' => 'postgresql_root_password'], ['value' => '']);
User::query()->create([
'id' => 1,
'username' => 'admin',
'email' => 'panel@haozi.net',
'password' => Hash::make(Str::random()),
]);
}
/**
* 更新面板
* @return void
*/
private function update(): void
{
/**
* 检查当前是否有任务正在运行
*/
if (Task::query()->where('status', '!=', 'finished')->count()) {
$this->error('当前有任务正在运行,请稍后再试');
$this->info('如需强制更新,请先执行:panel cleanRunningTask');
return;
}
$this->info('正在下载面板...');
shell_exec('wget -O /tmp/panel.zip https://api.panel.haozi.xyz/api/version/latest');
// 检查下载是否成功
if (!file_exists('/tmp/panel.zip') || filesize('/tmp/panel.zip') < 4096) {
$this->error('检测到面板新版本下载失败,已终止更新,请加QQ群:12370907 反馈处理');
return;
}
$this->info('正在备份数据库...');
shell_exec('rm -rf /tmp/database.sqlite');
if (!copy('/www/panel/database/database.sqlite', '/tmp/database.sqlite')) {
$this->error('备份数据库失败,已终止更新,请加QQ群:12370907 反馈处理');
return;
}
$this->info('正在备份插件...');
shell_exec('rm -rf /tmp/plugins');
shell_exec('\cp -rf /www/panel/plugins /tmp/plugins');
if (!is_dir('/tmp/plugins/Openresty')) {
$this->error('检测到面板插件备份失败,已终止更新,请加QQ群:12370907 反馈处理');
return;
}
$this->info('正在删除旧版本...');
shell_exec('rm -rf /www/panel');
shell_exec('mkdir /www/panel');
$this->info('正在解压新版本...');
shell_exec('unzip -o /tmp/panel.zip -d /www/panel');
if (!file_exists('/www/panel/artisan')) {
$this->error('检测到面板新版本解压失败,请加QQ群:12370907 反馈处理');
return;
}
$this->info('正在恢复数据库...');
shell_exec('rm -rf /www/panel/database/database.sqlite');
if (!copy('/tmp/database.sqlite', '/www/panel/database/database.sqlite')) {
$this->error('检测到面板数据库恢复失败,请加QQ群:12370907 反馈处理');
return;
}
$this->info('正在恢复插件...');
shell_exec('rm -rf /www/panel/plugins');
shell_exec('\cp -rf /tmp/plugins /www/panel/plugins');
if (!is_dir('/www/panel/plugins/Openresty')) {
$this->error('检测到面板插件恢复失败,请加QQ群:12370907 反馈处理');
return;
}
$this->info('正在更新面板数据库...');
shell_exec('cd /www/panel && php-panel artisan migrate');
$this->info('正在设置面板权限...');
shell_exec('chown -R root:root /www/panel');
shell_exec('chmod -R 600 /www/panel');
shell_exec('chmod 755 /www/panel');
shell_exec('chmod -R 755 /www/panel/public');
shell_exec('chown -R root:root /www/server/cron');
shell_exec('chmod -R 700 /www/server/cron');
shell_exec('chmod -R 600 /www/server/cron/logs');
shell_exec('chown -R root:root /www/server/vhost');
shell_exec('chmod -R 644 /www/server/vhost');
$this->info('正在重载面板服务...');
$reloadCheck = shell_exec('systemctl reload panel.service 2>&1');
// 检查重启是否成功
if (!empty($reloadCheck)) {
$this->error('检测到面板服务重载失败,请加QQ群:12370907 反馈处理');
} else {
$this->info('正在清理临时文件...');
shell_exec('rm -rf /tmp/panel.zip');
shell_exec('rm -rf /tmp/database.sqlite');
shell_exec('rm -rf /tmp/plugins');
$this->info('面板更新成功');
}
}
/**
* 获取面板信息
* @return void
*/
private function getInfo(): void
{
$user = User::query()->where('id', 1);
// 生成唯一信息
$username = Str::random(6);
$password = Str::random(12);
// 入库
$user->update([
'username' => $username,
'password' => Hash::make($password),
]);
// 从nginx配置文件中获取面板端口
$nginxConf = file_get_contents('/www/server/nginx/conf/nginx.conf');
preg_match('/listen\s+(\d+)/', $nginxConf, $matches);
if (!isset($matches[1])) {
$this->info('获取面板端口失败,请检查nginx主配置文件');
}
$this->info('面板用户名:'.$username);
$this->info('面板密码:'.$password);
$this->info('访问地址:http://IP:'.$matches[1]);
}
/**
* 获取端口
* @return void
*/
private function getPort(): void
{
// 从nginx配置文件中获取面板端口
$nginxConf = file_get_contents('/www/server/nginx/conf/nginx.conf');
preg_match('/listen\s+(\d+)/', $nginxConf, $matches);
if (isset($matches[1])) {
$this->info('面板访问端口为:'.$matches[1]);
} else {
$this->error('获取面板端口失败,请检查nginx主配置文件');
}
}
/**
* 写入插件安装状态
* @return void
*/
private function writePluginInstall(): void
{
$pluginSlug = $this->argument('a1');
// 判空
if (empty($pluginSlug)) {
$this->error('参数错误');
return;
}
// 入库
Plugin::query()->updateOrCreate(
['slug' => $pluginSlug],
['show' => 0]
);
$this->info('成功');
}
/**
* 写入插件卸载状态
* @return void
*/
private function writePluginUnInstall(): void
{
$pluginSlug = $this->argument('a1');
// 判空
if (empty($pluginSlug)) {
$this->error('参数错误');
return;
}
if ($pluginSlug == 'openresty') {
$this->error('耗子Linux面板:请不要花样作死!');
return;
}
// 入库
Plugin::query()->where('slug', $pluginSlug)->delete();
$this->info('成功');
}
/**
* 写入MySQL密码
* @return void
*/
private function writeMysqlPassword(): void
{
$password = $this->argument('a1');
// 判空
if (empty($password)) {
$this->error('参数错误');
return;
}
// 入库
Setting::query()->where('name', 'mysql_root_password')->updateOrCreate([
'name' => 'mysql_root_password',
], [
'value' => $password,
]);
$this->info('成功');
}
/**
* 清理所有运行中和等待中的任务
* @return void
*/
private function cleanRunningTask(): void
{
// 更新任务状态
Task::query()->update(['status' => 'finished']);
// 将所有队列任务清空
shell_exec('php-panel /www/panel/artisan queue:clear');
$this->info('成功');
}
/**
* 备份网站/MySQL数据库/PostgreSQL数据库到指定目录
* @return void
*/
private function backup(): void
{
$type = $this->argument('a1');
$name = $this->argument('a2');
$path = $this->argument('a3');
// 判空
if (empty($type) || empty($name) || empty($path)) {
$this->error('参数错误');
return;
}
// 判断目录是否存在
if (!is_dir($path)) {
$this->error('目录不存在');
return;
}
// 判断目录是否可写
if (!is_writable($path)) {
$this->error('目录不可写');
return;
}
// 判断备份目录是否以/结尾,有则去掉
if (str_ends_with($path, '/')) {
$path = substr($path, 0, -1);
}
// 判断类型
if ($type == 'website') {
// 备份网站
// 从数据库中获取网站目录
$sitePath = Website::query()->where('name', $name)->value('path');
if (empty($sitePath)) {
$this->error('网站不存在');
return;
}
$backupFile = $path.'/'.$name.'_'.date('YmdHis').'.zip';
shell_exec('zip -r '.$backupFile.' '.escapeshellarg($sitePath).' 2>&1');
$this->info('成功');
} elseif ($type == 'mysql') {
// 备份MySQL数据库
$password = Setting::query()->where('name', 'mysql_root_password')->value('value');
$backupFile = $path.'/'.$name.'_'.date('YmdHis').'.sql.zip';
$tempFile = $name.'_'.date('YmdHis').'.sql';
// 判断数据库是否存在
$name = escapeshellarg($name);
$check = shell_exec("mysql -u root -p".$password." -e 'use ".$name."' 2>&1");
if (str_contains($check, 'ERROR')) {
$this->error('数据库不存在');
return;
}
// 傻逼MySQL,瞎jb输出警告
//shell_exec("mysqldump -u root -p".$password." ".$name." 2> /dev/null > /tmp/".$tempFile);
putenv('MYSQL_PWD='.$password);
shell_exec("mysqldump -u root ".$name." > /tmp/".$tempFile);
// zip压缩
shell_exec('cd /tmp && zip -r '.$tempFile.'.zip '.escapeshellarg($tempFile).' 2>&1');
// 移动文件
if (file_exists($backupFile)) {
$this->error('检测到备份已存在,已跳过此次备份');
unlink('/tmp/'.$tempFile);
return;
}
rename('/tmp/'.$tempFile.'.zip', $backupFile);
// 删除临时文件
unlink('/tmp/'.$tempFile);
$this->info('成功');
} elseif ($type == 'postgresql') {
// 备份PostgreSQL数据库
$backupFile = $path.'/'.$name.'_'.date('YmdHis').'.sql.zip';
$tempFile = $name.'_'.date('YmdHis').'.sql';
// 判断数据库是否存在
$check = shell_exec('su - postgres -c "psql -l" 2>&1');
if (!str_contains($check, $name)) {
$this->error('数据库不存在');
return;
}
$name = escapeshellarg($name);
shell_exec('su - postgres -c "pg_dump '.$name.'" > /tmp/'.$tempFile.' 2>&1');
// zip压缩
shell_exec('cd /tmp && zip -r '.$tempFile.'.zip '.escapeshellarg($tempFile).' 2>&1');
// 移动文件
if (file_exists($backupFile)) {
$this->error('检测到备份已存在,已跳过此次备份');
unlink('/tmp/'.$tempFile);
return;
}
rename('/tmp/'.$tempFile.'.zip', $backupFile);
// 删除临时文件
unlink('/tmp/'.$tempFile);
$this->info('成功');
} else {
$this->error('参数错误');
}
}
/**
* 写入网站数据到面板
* @return void
*/
private function writeSite(): void
{
$name = $this->argument('a1');
$status = $this->argument('a2');
$path = $this->argument('a3');
$php = $this->argument('a4');
$ssl = $this->argument('a5');
// 判空
if (empty($name) || empty($status) || empty($path) || empty($php) || empty($ssl)) {
$this->error('参数错误');
return;
}
// 判断网站是否存在
if (Website::query()->where('name', $name)->exists()) {
$this->error('网站已存在');
return;
}
// 判断目录是否存在
if (!is_dir($path)) {
$this->error('目录不存在');
return;
}
// 写入网站
Website::query()->create([
'name' => $name,
'status' => $status,
'path' => $path,
'php' => $php,
'ssl' => $ssl,
]);
}
/**
* 删除面板网站数据
* @return void
*/
private function deleteSite(): void
{
$name = $this->argument('a1');
// 判空
if (empty($name)) {
$this->error('参数错误');
return;
}
// 判断网站是否存在
if (!Website::query()->where('name', $name)->exists()) {
$this->error('网站不存在');
return;
}
// 删除网站
Website::query()->where('name', $name)->delete();
}
/**
* 写入/更新面板设置数据
* @return void
*/
private function writeSetting(): void
{
$name = $this->argument('a1');
$value = $this->argument('a2');
// 判空
if (empty($name) || empty($value)) {
$this->error('参数错误');
return;
}
Setting::query()->updateOrCreate(['name' => $name], ['value' => $value]);
}
/**
* 删除面板设置数据
* @return void
*/
private function deleteSetting(): void
{
$name = $this->argument('a1');
// 判空
if (empty($name)) {
$this->error('参数错误');
return;
}
// 判断设置是否存在
if (!Setting::query()->where('name', $name)->exists()) {
$this->error('设置不存在');
return;
}
// 删除设置
Setting::query()->where('name', $name)->delete();
}
}
-59
View File
@@ -1,59 +0,0 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Models\Cron;
use Illuminate\Support\Carbon;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('monitor')->everyMinute();
// 查询所有计划任务
$crons = Cron::all();
foreach ($crons as $cron) {
$file = '/www/server/cron/'.$cron->shell;
// 检查文件是否存在,及所有者是否为root
if (!file_exists($file) || fileowner($file) != 0) {
file_put_contents('/www/server/cron/logs/'.$cron->id.'.log',
PHP_EOL.'耗子Linux面板:检测到脚本文件异常,为确保安全已终止运行,如果你不知道发生了什么,这通常意味着服务器已被入侵。'.PHP_EOL,
FILE_APPEND);
continue;
}
$schedule->exec('bash '.escapeshellarg($file))->withoutOverlapping()->cron($cron->time)->appendOutputTo('/www/server/cron/logs/'.$cron->id.'.log')->when(function (
) use ($cron) {
return (boolean) $cron->status;
})->after(function () use ($cron) {
$cron->updated_at = now();
$cron->save();
})->onSuccess(function () use ($cron) {
file_put_contents('/www/server/cron/logs/'.$cron->id.'.log',
PHP_EOL.Carbon::now()->toDateTimeString().' 任务执行成功'.PHP_EOL, FILE_APPEND);
})->onFailure(function () use ($cron) {
file_put_contents('/www/server/cron/logs/'.$cron->id.'.log',
PHP_EOL.Carbon::now()->toDateTimeString().' 任务执行失败'.PHP_EOL, FILE_APPEND);
});
}
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
-50
View File
@@ -1,50 +0,0 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<\Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
}
@@ -1,212 +0,0 @@
<?php
/**
* 耗子Linux面板 - 计划任务控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Cron;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
class CronsController extends Controller
{
/**
* 面板计划任务列表
*/
public function getList(Request $request): JsonResponse
{
$limit = $request->input('limit', 10);
$crons = Cron::query()->orderBy('id', 'desc')->paginate($limit);
$cronData = [];
foreach ($crons as $k => $v) {
// 格式化时间
$cronData[$k]['id'] = $v['id'];
$cronData[$k]['name'] = $v['name'];
$cronData[$k]['status'] = $v['status'];
$cronData[$k]['type'] = $v['type'];
$cronData[$k]['time'] = $v['time'];
$cronData[$k]['shell'] = $v['shell'];
$cronData[$k]['script'] = @file_get_contents('/www/server/cron/'.$v['shell']);
$cronData[$k]['created_at'] = Carbon::create($v['created_at'])->toDateTimeString();
$cronData[$k]['updated_at'] = Carbon::create($v['updated_at'])->toDateTimeString();
}
$data['code'] = 0;
$data['msg'] = 'success';
$data['count'] = $crons->total();
$data['data'] = $cronData;
return response()->json($data);
}
/**
* 添加计划任务
*/
public function add(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'name' => 'required|max:255',
'time' => [
'required',
'regex:/^((\*|\d+|\d+-\d+|\d+\/\d+|\d+-\d+\/\d+|\*\/\d+)(\,(\*|\d+|\d+-\d+|\d+\/\d+|\d+-\d+\/\d+|\*\/\d+))*\s?){5}$/'
],
'script' => 'required',
]);
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
// 将script写入shell文件
$shellDir = '/www/server/cron/';
$shellLogDir = '/www/server/cron/logs/';
if (!is_dir($shellDir)) {
mkdir($shellDir, 700, true);
}
if (!is_dir($shellLogDir)) {
mkdir($shellLogDir, 600, true);
}
$shellFile = uniqid().'.sh';
file_put_contents($shellDir.$shellFile, $credentials['script']);
$cron = new Cron();
$cron->name = $credentials['name'];
$cron->status = 1;
$cron->type = '脚本';
$cron->time = $credentials['time'];
$cron->shell = $shellFile;
$cron->save();
$data['code'] = 0;
$data['msg'] = 'success';
return response()->json($data);
}
/**
* 修改计划任务
*/
public function edit(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'id' => 'required|integer',
'name' => 'required|max:255',
'time' => ['required', 'regex:/^((\*|\d+|\d+-\d+|\d+\/\d+)(\,(\*|\d+|\d+-\d+|\d+\/\d+))*\s?){5}$/'],
'script' => 'required',
]);
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
$cron = Cron::query()->find($credentials['id']);
$cron->name = $credentials['name'];
$cron->time = $credentials['time'];
// 将script写入shell文件
$shellDir = '/www/server/cron/';
$shellLogDir = '/www/server/cron/logs/';
if (!is_dir($shellDir)) {
mkdir($shellDir, 700, true);
}
if (!is_dir($shellLogDir)) {
mkdir($shellLogDir, 600, true);
}
$shellFile = $cron->shell;
file_put_contents($shellDir.$shellFile, $credentials['script']);
// 将文件转为unix格式
exec('dos2unix '.$shellDir.$shellFile);
// 设置文件权限
exec('chmod 700 '.$shellDir.$shellFile);
$cron->save();
$data['code'] = 0;
$data['msg'] = 'success';
return response()->json($data);
}
/**
* 删除计划任务
*/
public function delete(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'id' => 'required|integer',
]);
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
$cron = Cron::query()->find($credentials['id']);
// 删除shell文件
$shellDir = '/www/server/cron/';
$shellFile = $cron->shell;
@unlink($shellDir.$shellFile);
// 删除日志文件
$shellLogDir = '/www/server/cron/logs/';
$shellLogFile = $shellFile.'.log';
@unlink($shellLogDir.$shellLogFile);
$cron->delete();
$data['code'] = 0;
$data['msg'] = 'success';
return response()->json($data);
}
/**
* 修改计划任务状态
*/
public function setStatus(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'id' => 'required|integer',
'status' => 'required|integer',
]);
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
$cron = Cron::query()->find($credentials['id']);
$cron->status = $credentials['status'];
$cron->save();
$data['code'] = 0;
$data['msg'] = 'success';
return response()->json($data);
}
/**
* 获取计划任务日志
*/
public function getLog(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'id' => 'required|integer',
]);
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
$log = @file_get_contents('/www/server/cron/logs/'.$credentials['id'].'.log');
if ($log === false) {
$log = '暂无日志';
}
$data['code'] = 0;
$data['msg'] = 'success';
$data['data'] = htmlspecialchars($log);
return response()->json($data);
}
}
@@ -1,504 +0,0 @@
<?php
/**
* 耗子Linux面板 - 文件控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class FilesController extends Controller
{
/**
* 获取某个目录下的文件(夹)列表
* @param Request $request
* @return JsonResponse
*/
public function getList(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'limit' => 'required|integer',
'page' => 'required|integer',
]);
$path = $credentials['path'];
$limit = $credentials['limit'];
$page = $credentials['page'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '目录不存在']);
}
$files = scandir($path);
$fileData = [];
foreach ($files as $k => $v) {
if ($v == '.' || $v == '..') {
continue;
}
$fileData[$k]['name'] = $v;
$fileData[$k]['path'] = $path.'/'.$v;
$fileData[$k]['type'] = filetype($path.'/'.$v);
$fileData[$k]['size'] = filesize($path.'/'.$v);
$fileData[$k]['mtime'] = Carbon::createFromTimestamp(filemtime($path.'/'.$v))->toDateTimeString();
}
// 分页
$total = count($fileData);
$filesArr = array_slice($fileData, ($page - 1) * $limit, $limit);
$data['code'] = 0;
$data['msg'] = 'success';
$data['count'] = $total;
$data['data'] = $filesArr;
return response()->json($data);
}
/**
* 获取文件内容
* @param Request $request
* @return JsonResponse
*/
public function getFileContent(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'file' => ['required', 'regex:/^\/.*$/'],
]);
$file = $credentials['file'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($file)) {
return response()->json(['code' => 1, 'msg' => '文件不存在']);
}
$content = @file_get_contents($file);
$data['code'] = 0;
$data['msg'] = 'success';
$data['data'] = $content;
return response()->json($data);
}
/**
* 保存文件内容
* @param Request $request
* @return JsonResponse
*/
public function saveFileContent(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'file' => ['required', 'regex:/^\/.*$/'],
'content' => 'required',
]);
$file = $credentials['file'];
$content = $credentials['content'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($file)) {
return response()->json(['code' => 1, 'msg' => '文件不存在']);
}
$res = @file_put_contents($file, $content);
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '保存失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 创建目录
* @param Request $request
* @return JsonResponse
*/
public function createDir(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'name' => 'required',
]);
$path = $credentials['path'];
$name = $credentials['name'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '目录不存在']);
}
$res = @mkdir($path.'/'.$name);
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '创建失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 重命名文件或目录
* @param Request $request
* @return JsonResponse
*/
public function rename(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'name' => 'required',
]);
$path = $credentials['path'];
$name = $credentials['name'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
$res = @rename($path, dirname($path).'/'.$name);
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '重命名失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 上传文件
* @param Request $request
* @return JsonResponse
*/
public function uploadFile(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'file' => 'required|file',
]);
$path = $credentials['path'];
$file = $credentials['file'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '目录不存在']);
}
$res = @move_uploaded_file($file->getRealPath(), $path.'/'.$file->getClientOriginalName());
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '上传失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 下载文件
* @param Request $request
* @return JsonResponse|BinaryFileResponse
*/
public function downloadFile(Request $request): BinaryFileResponse|JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
]);
$path = $credentials['path'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path)) {
return response()->json(['code' => 1, 'msg' => '文件不存在']);
}
return response()->download($path);
}
/**
* 创建文件
*/
public function createFile(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'name' => 'required',
]);
$path = $credentials['path'];
$name = $credentials['name'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '目录不存在']);
}
$res = @file_put_contents($path.'/'.$name, '');
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '创建失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 设置权限
* @param Request $request
* @return JsonResponse
*/
public function chmod(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'mode' => 'required',
]);
$path = $credentials['path'];
$mode = $credentials['mode'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
$res = @chmod($path, $mode);
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '设置失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 设置所有者
*/
public function chown(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'user' => 'required',
]);
$path = $credentials['path'];
$user = $credentials['user'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
$res = @chown($path, $user);
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '设置失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 设置所有者组
* @param Request $request
* @return JsonResponse
*/
public function chgrp(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'group' => 'required',
]);
$path = $credentials['path'];
$group = $credentials['group'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
$res = @chgrp($path, $group);
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '设置失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 复制文件/目录
* @param Request $request
* @return JsonResponse
*/
public function copy(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'dest' => ['required', 'regex:/^\/.*$/'],
]);
$path = $credentials['path'];
$dest = $credentials['dest'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
if (!is_dir($dest)) {
return response()->json(['code' => 1, 'msg' => '目标目录不存在']);
}
$res = @copy($path, $dest.'/'.basename($path));
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '复制失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 移动文件/目录
* @param Request $request
* @return JsonResponse
*/
public function move(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
'dest' => ['required', 'regex:/^\/.*$/'],
]);
$path = $credentials['path'];
$dest = $credentials['dest'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
if (!is_dir($dest)) {
return response()->json(['code' => 1, 'msg' => '目标目录不存在']);
}
$res = @rename($path, $dest.'/'.basename($path));
if ($res === false) {
return response()->json(['code' => 1, 'msg' => '移动失败']);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 删除文件/目录
* @param Request $request
* @return JsonResponse
*/
public function delete(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
]);
$path = $credentials['path'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
$res = @shell_exec('rm -rf '.escapeshellarg($path).' 2>&1');
if (!empty($res)) {
return response()->json(['code' => 1, 'msg' => '删除失败:'.$res]);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 压缩文件/目录
* @param Request $request
* @return JsonResponse
*/
public function zip(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
]);
$path = $credentials['path'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path) && !is_dir($path)) {
return response()->json(['code' => 1, 'msg' => '文件或目录不存在']);
}
$zipPath = dirname($path).'/'.basename($path).'.zip';
$res = @shell_exec('zip -r '.escapeshellarg($zipPath).' '.escapeshellarg($path).' 2>&1');
if (!empty($res)) {
return response()->json(['code' => 1, 'msg' => '压缩失败:'.$res]);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
/**
* 解压文件/目录
* @param Request $request
* @return JsonResponse
*/
public function unzip(Request $request): JsonResponse
{
try {
$credentials = $this->validate($request, [
'path' => ['required', 'regex:/^\/.*$/'],
]);
$path = $credentials['path'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
if (!is_file($path)) {
return response()->json(['code' => 1, 'msg' => '文件不存在']);
}
$res = @shell_exec('unzip -o '.escapeshellarg($path).' -d '.escapeshellarg(dirname($path)).' 2>&1');
if (!empty($res)) {
return response()->json(['code' => 1, 'msg' => '解压失败:'.$res]);
}
return response()->json(['code' => 0, 'msg' => 'success']);
}
}
@@ -1,326 +0,0 @@
<?php
/**
* 耗子Linux面板 - 信息控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Plugin;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class InfosController extends Controller
{
public function getMenu(): JsonResponse
{
$menu = array(
"code" => 0,
"msg" => "",
"data" => array(
array(
"name" => "home",
"title" => "主页",
"icon" => "layui-icon-home",
"jump" => "/"
),
array(
"name" => "website",
"title" => "网站管理",
"icon" => "layui-icon-website",
"jump" => "website/list"
),
array(
"name" => "monitor",
"title" => "资源监控",
"icon" => "layui-icon-chart-screen",
"jump" => "monitor"
),
array(
"name" => "safe",
"title" => "系统安全",
"icon" => "layui-icon-auz",
"jump" => "safe"
),
array(
"name" => "file",
"title" => "文件管理",
"icon" => "layui-icon-file",
"jump" => "file"
),
array(
"name" => "cron",
"title" => "计划任务",
"icon" => "layui-icon-date",
"jump" => "cron"
),
array(
"name" => "plugin",
"title" => "插件中心",
"icon" => "layui-icon-app",
"jump" => "plugin"
),
array(
"name" => "setting",
"title" => "面板设置",
"icon" => "layui-icon-set",
"jump" => "setting"
)
)
);
return response()->json($menu);
}
/**
* 系统资源统计
* @return JsonResponse
*/
public function getNowMonitor(): JsonResponse
{
// 第一次获取网络信息
$netInfo1 = getNetInfo();
// 卡它一秒钟
sleep(1);
// 第二次获取网络信息
$netInfo2 = getNetInfo();
// CPU统计信息及负载
$cpuInfoRaw = file_get_contents('/proc/cpuinfo');
$physicalArr = array();
$physicalSum = 0;
$coresSum = 0;
$siblingsSum = 0;
preg_match("/model name\s*:\s(.*)/", $cpuInfoRaw, $cpuName);
preg_match("/vendor_id\s*:\s(.*)/", $cpuInfoRaw, $cpuVendor);
preg_match("/cpu family\s*:\s(.*)/", $cpuInfoRaw, $cpuFamily);
preg_match("/cpu MHz\s*:\s(.*)/", $cpuInfoRaw, $cpuFreq);
preg_match("/cache size\s*:\s(.*)/", $cpuInfoRaw, $cpuCache);
preg_match("/(\d+\.\d+), (\d+\.\d+), (\d+\.\d+)/", exec('uptime'), $uptime);
$cpuName = $cpuName[1] ?? 'No';
$cpuVendor = $cpuVendor[1] ?? 'No';
$cpuFamily = $cpuFamily[1] ?? 'No';
$cpuFreq = isset($cpuFreq[1]) ? round($cpuFreq[1], 2) : 'No';
$cpuCache = $cpuCache[1] ?? 'No';
$uptime1 = $uptime[1] ?? 0;
$uptime5 = $uptime[2] ?? 0;
$uptime15 = $uptime[3] ?? 0;
$processorArr = explode("\nprocessor", $cpuInfoRaw);
foreach ($processorArr as $v) {
preg_match("/physical id\s*:\s(.*)/", $v, $physical);
preg_match("/cpu cores\s*:\s(.*)/", $v, $cores);
preg_match("/siblings\s*:\s(.*)/", $v, $siblings);
if (isset($physical[1])) {
if (!in_array($physical[1], $physicalArr)) {
$physicalSum += 1;
if (isset($cores[1])) {
$coresSum += $cores[1];
}
if (isset($siblings[1])) {
$siblingsSum += $siblings[1];
}
}
$physicalArr[] = $physical[1];
}
}
// CPU使用率
$cpuUse = 0.1;
$cpuRaw = explode("\n", shell_exec('ps aux'));
// 弹出第一项和最后一项
array_pop($cpuRaw);
array_shift($cpuRaw);
// 获取当前php进程的pid
$pid = getmypid();
foreach ($cpuRaw as $v) {
$v = preg_replace("/\s+/", " ", $v);
$v = (explode(' ', $v));
// 排除当前进程
if ($v[1] == $pid) {
continue;
}
$cpuUse += isset($v[2]) ? (float) $v[2] : 0;
}
$cpuUse = $siblingsSum > 0 ? ($cpuUse / $siblingsSum) : $cpuUse;
$cpuUse = round($cpuUse, 2);
$cpuUse = $cpuUse > 100 ? 100 .'%' : $cpuUse.'%';
// 内存使用率
$memRaw = explode("\n", shell_exec('free -m'));
foreach ($memRaw as $v) {
if (str_contains($v, 'Mem')) {
$memList = preg_replace("/\s+/", " ", $v);
}
}
$memArr = explode(' ', $memList);
// 内存大小MB
$memTotal = $memArr[1];
// 使用中MB
$memUse = (str_contains($memRaw[0], 'buff/cache')) ? $memArr[2] : ($memArr[2] - $memArr[5] - $memArr[6]);
// 使用中%
$memUseP = round($memUse / $memTotal, 2) * 100 .'%';
// 1分钟负载%
$uptime1P = $uptime1 * 10;
$uptime1P = $uptime1P > 100 ? 100 .'%' : $uptime1P.'%';
// 5分钟负载%
$uptime5P = $uptime5 * 10;
$uptime5P = $uptime5P > 100 ? 100 .'%' : $uptime5P.'%';
// 15分钟负载%
$uptime15P = $uptime15 * 10;
$uptime15P = $uptime15P > 100 ? 100 .'%' : $uptime15P.'%';
// 构建返回数组
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = [
'cpu_use' => $cpuUse,
'uptime_1' => $uptime1,
'uptime_1_p' => $uptime1P,
'uptime_5' => $uptime5,
'uptime_5_p' => $uptime5P,
'uptime_15' => $uptime15,
'uptime_15_p' => $uptime15P,
'mem_total' => $memTotal,
'mem_use' => $memUse,
'mem_use_p' => $memUseP,
'tx_total' => formatBytes($netInfo1['tx']),
'rx_total' => formatBytes($netInfo1['rx']),
'tx_now' => formatBytes($netInfo2['tx'] - $netInfo1['tx']),
'rx_now' => formatBytes($netInfo2['rx'] - $netInfo1['rx']),
'cpu_info' => [
'name' => $cpuName,
'cores' => $coresSum,
'physical' => $physicalSum,
'siblings' => $siblingsSum,
'vendor' => $cpuVendor,
'family' => $cpuFamily,
'freq' => $cpuFreq,
'cache' => $cpuCache,
],
];
return response()->json($res);
}
/**
* 获取系统信息
* @return JsonResponse
*/
public function getSystemInfo(): JsonResponse
{
$os_name = file_get_contents('/etc/redhat-release');
$uptime = file_get_contents('/proc/uptime');
$uptime = explode(' ', $uptime)[0];
$uptime = round($uptime / 86400, 1);
$panel_version = config('panel.version');
// 构建返回数组
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = [
'os_name' => $os_name,
'uptime' => $uptime,
'panel_version' => $panel_version,
];
return response()->json($res);
}
/**
* 获取首页插件列表
*/
public function getHomePlugins(): JsonResponse
{
$plugins = Plugin::query()->where('show', 1)->get();
// 判空
if ($plugins->isEmpty()) {
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = [];
} else {
$plugins = $plugins->toArray();
$plugins = array_map(function ($item) {
$item['name'] = PLUGINS[$item['slug']]['name'];
return $item;
}, $plugins);
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = $plugins;
}
return response()->json($res);
}
/**
* 获取已安装的数据库和PHP版本
*/
public function getInstalledDbAndPhp(): JsonResponse
{
$dbVersions = [];
// 判断mysql插件是否安装
if (isset(PLUGINS['mysql'])) {
$dbVersions['mysql'] = PLUGINS['mysql']['version'];
} else {
$dbVersions['mysql'] = false;
}
// 判断postgresql插件是否安装
if (isset(PLUGINS['postgresql'])) {
$dbVersions['postgresql'] = PLUGINS['postgresql']['version'];
} else {
$dbVersions['postgresql'] = false;
}
// 循环获取已安装的PHP版本
$php_versions = Plugin::query()->where('slug', 'like', 'php%')->get();
$php_versions = $php_versions->toArray();
$php_versions = array_column($php_versions, 'slug');
$php_versions = array_map(function ($item) {
return str_replace('php', '', $item);
}, $php_versions);
$php_version = shell_exec('ls /www/server/php');
$php_version = trim($php_version);
if (!empty($php_version)) {
$php_versions = explode("\n", $php_version);
}
$php_versions[] = '00';
unset($php_versions[array_search('panel', $php_versions)]);
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = array(
'db_version' => $dbVersions,
'php_version' => $php_versions
);
return response()->json($res);
}
/**
* 检查更新
*/
public function checkUpdate(): JsonResponse
{
$version = config('panel.version');
$remoteVersion = Http::get('https://api.panel.haozi.xyz/api/version/info')->json();
if ($remoteVersion['code'] != 0) {
$res['code'] = 1;
$res['msg'] = '获取远程版本信息失败';
$res['data'] = [];
return response()->json($res);
}
$res['code'] = 0;
$res['msg'] = 'success';
if (version_compare($version, $remoteVersion['data']['version'], '<')) {
$res['data'] = [
'version' => $remoteVersion['data']['version'],
'describe' => $remoteVersion['data']['describe'],
];
} else {
$res['data'] = [];
}
return response()->json($res);
}
}
@@ -1,109 +0,0 @@
<?php
/**
* 耗子Linux面板 - 监控控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Monitor;
use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
class MonitorsController extends Controller
{
/**
* 修改监控开关
*/
public function setMonitorSwitch(Request $request): JsonResponse
{
$switch = $request->input('switch');
if ($switch) {
$status = true;
} else {
$status = false;
}
Setting::query()->where('name', 'monitor')->update(['value' => $status]);
return response()->json(['code' => 0, 'msg' => '修改成功']);
}
/**
* 修改保存天数
*/
public function setMonitorSaveDays(Request $request): JsonResponse
{
$days = $request->input('days');
Setting::query()->where('name', 'monitor_days')->update(['value' => $days]);
return response()->json(['code' => 0, 'msg' => '修改成功']);
}
/**
* 清空监控数据
*/
public function clearMonitorData(): JsonResponse
{
Monitor::query()->truncate();
return response()->json(['code' => 0, 'msg' => '清空成功']);
}
/**
* 获取监控开关和保存天数
*/
public function getMonitorSwitchAndDays(): JsonResponse
{
$monitor = Setting::query()->where('name', 'monitor')->first();
$monitor_days = Setting::query()->where('name', 'monitor_days')->first();
return response()->json([
'code' => 0, 'msg' => '获取成功',
'data' => ['monitor' => $monitor->value, 'monitor_days' => $monitor_days->value]
]);
}
/**
* 获取监控数据
*/
public function getMonitorData(Request $request): JsonResponse
{
$start = $request->input('start') ?? now();
$end = $request->input('end') ?? now();
$start = Carbon::create($start);
$end = Carbon::create($end);
$data = Monitor::query()->where('created_at', '>=', $start)->where('created_at', '<=', $end)->get()->toArray();
$res['code'] = 0;
$res['msg'] = 'success';
if (empty($data)) {
$res['code'] = 1;
$res['msg'] = '暂无数据';
return response()->json($res);
}
foreach ($data as $key => $value) {
$info = json_decode($value['info'], true);
$res['data']['times'][] = Carbon::create($value['created_at'])->tz(config('app.timezone',
'PRC'))->isoFormat('MM-DD HH:mm');
$res['data']['uptime']['uptime'][] = round($info['uptime'], 2);
$res['data']['cpu']['use'][] = round($info['cpu_use'], 2);
$res['data']['memory']['mem_use'][] = round($info['mem_use'], 2);
$res['data']['memory']['mem_use_p'][] = round($info['mem_use_p'], 2);
$res['data']['memory']['swap_use'][] = round($info['swap_use'], 2);
$res['data']['memory']['swap_use_p'][] = round($info['swap_use_p'], 2);
$res['data']['network']['tx_now'][] = round($info['tx_now'] / 1024, 2);
$res['data']['network']['rx_now'][] = round($info['rx_now'] / 1024, 2);
}
// 插入总内存大小
$result = explode("\n", shell_exec('free -m'));
foreach ($result as $key => $val) {
if (str_contains($val, 'Mem')) {
$mem_list = preg_replace("/\s+/", " ", $val);
break;
}
}
$mem_arr = explode(' ', $mem_list);
// 内存大小MB
$mem_total = $mem_arr[1];
$res['data']['mem_total'] = round($mem_total, 2);
return response()->json($res);
}
}
@@ -1,323 +0,0 @@
<?php
/**
* 耗子Linux面板 - 插件控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Jobs\ProcessShell;
use App\Models\Plugin;
use App\Models\Task;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
class PluginsController extends Controller
{
/**
* 面板插件列表
* @return JsonResponse
*/
public function getList(): JsonResponse
{
$data['code'] = 0;
$data['msg'] = 'success';
$data['data'] = $this->pluginList();
// 获取首页显示状态
$shows = Plugin::query()->pluck('show', 'slug');
foreach ($data['data'] as $k => $v) {
// 如果本地已安装,则显示本地名称
$data['data'][$k]['name'] = PLUGINS[$v['slug']]['name'] ?? $data['data'][$k]['name'] ?? '无名';
// 作者名称
$data['data'][$k]['author'] = PLUGINS[$v['slug']]['author'] ?? $data['data'][$k]['author'] ?? '耗子';
// 已装版本
$data['data'][$k]['install_version'] = PLUGINS[$v['slug']]['version'] ?? '';
// 首页显示
$data['data'][$k]['show'] = $shows[$v['slug']] ?? 0;
// 去除不需要的字段
unset($data['data'][$k]['url']);
unset($data['data'][$k]['install']);
unset($data['data'][$k]['uninstall']);
unset($data['data'][$k]['update']);
if (isset(PLUGINS[$v['slug']])) {
$data['data'][$k]['control']['installed'] = true;
$data['data'][$k]['control']['allow_uninstall'] = true;
// 判断是否有更新
$data['data'][$k]['control']['update'] = version_compare($v['version'],
$data['data'][$k]['install_version'], '>');
if ($v['slug'] == 'openresty') {
$data['data'][$k]['control']['allow_uninstall'] = false;
}
} else {
$data['data'][$k]['control']['installed'] = false;
$data['data'][$k]['control']['allow_uninstall'] = false;
}
}
// 插入本地插件数据
$slugs = array_column($data['data'], 'slug');
foreach (PLUGINS as $v) {
// 如果本地已安装,则不显示
if (in_array($v['slug'], $slugs)) {
continue;
}
// 插入插件数据
$data['data'][] = [
'name' => $v['name'],
'author' => $v['author'],
'slug' => $v['slug'],
'version' => $v['version'],
'install_version' => $v['version'],
'describe' => $v['describe'],
'show' => $shows[$v['slug']] ?? 0,
'control' => [
'installed' => true,
'allow_uninstall' => false,
],
];
}
return response()->json($data);
}
/**
* 安装插件
* @param Request $request
* @return JsonResponse
*/
public function install(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'slug' => 'required|max:255',
]);
$slug = $credentials['slug'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
// 通过slug获取插件信息
$pluginList = $this->pluginList();
// 循环插件列表查找对应的插件信息
$pluginCheck = false;
$pluginData = [];
foreach ($pluginList as $v) {
if ($v['slug'] == $slug) {
$pluginData = $v;
$pluginCheck = true;
}
}
// 判断插件是否存在
if (!$pluginCheck) {
return response()->json(['code' => 1, 'msg' => '插件不存在']);
}
// 判断插件是否已经安装
$installed = isset(PLUGINS[$slug]);
if ($installed) {
$data['code'] = 1;
$data['msg'] = '请不要重复安装!';
return response()->json($data);
}
// 入库等待安装
$task = new Task();
$task->name = '安装 '.$pluginData['name'];
$task->shell = $pluginData['install'];
$task->status = 'waiting';
$task->log = '/tmp/'.$pluginData['slug'].'.log';
$task->save();
// 塞入队列
ProcessShell::dispatch($task->id)->delay(1);
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = '任务添加成功';
return response()->json($res);
}
/**
* 卸载插件
* @param Request $request
* @return JsonResponse
*/
public function uninstall(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'slug' => 'required|max:255',
]);
$slug = $credentials['slug'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
// 通过slug获取插件信息
$pluginList = $this->pluginList();
// 循环插件列表查找对应的插件信息
$pluginCheck = false;
$pluginData = [];
foreach ($pluginList as $v) {
if ($v['slug'] == $slug) {
$pluginData = $v;
$pluginCheck = true;
}
}
// 判断插件是否存在
if (!$pluginCheck) {
return response()->json(['code' => 1, 'msg' => '插件不存在']);
}
// 判断是否是操作openresty
if ($slug == 'openresty') {
$data['code'] = 1;
$data['msg'] = '请不要花样作死!';
return response()->json($data);
}
// 入库等待卸载
$task = new Task();
$task->name = '卸载 '.$pluginData['name'];
$task->shell = $pluginData['uninstall'];
$task->status = 'waiting';
$task->log = '/tmp/'.$pluginData['slug'].'.log';
$task->save();
// 塞入队列
ProcessShell::dispatch($task->id)->delay(1);
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = '任务添加成功';
return response()->json($res);
}
/**
* 更新插件
*/
public function update(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'slug' => 'required|max:255',
]);
$slug = $credentials['slug'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
// 通过slug获取插件信息
$pluginList = $this->pluginList();
// 循环插件列表查找对应的插件信息
$pluginCheck = false;
$pluginData = [];
foreach ($pluginList as $v) {
if ($v['slug'] == $slug) {
$pluginData = $v;
$pluginCheck = true;
break;
}
}
// 判断插件是否存在
if (!$pluginCheck) {
return response()->json(['code' => 1, 'msg' => '插件不存在']);
}
// 判断插件是否已经安装
$installed = isset(PLUGINS[$slug]);
if (!$installed) {
$data['code'] = 1;
$data['msg'] = '插件未安装!';
return response()->json($data);
}
// 入库等待更新
$task = new Task();
$task->name = '更新 '.$pluginData['name'];
$task->shell = $pluginData['update'];
$task->status = 'waiting';
$task->log = '/tmp/'.$pluginData['slug'].'.log';
$task->save();
// 塞入队列
ProcessShell::dispatch($task->id)->delay(1);
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = '任务添加成功';
return response()->json($res);
}
/**
* 读取插件列表
*/
public function pluginList($cache = true)
{
// 判断刷新缓存
if (!$cache) {
Cache::forget('pluginList');
}
if (!Cache::has('pluginList')) {
return Cache::remember('pluginList', 3600, function () {
$response = Http::get('https://api.panel.haozi.xyz/api/plugin/list');
// 判断请求是否成功,如果不成功则抛出异常
if ($response->failed()) {
throw new Exception('获取插件列表失败,请求错误');
}
// 判断返回的JSON数据中code是否为0,如果不为0则抛出异常
if (!$response->json('code') == 0) {
throw new Exception('获取插件列表失败,服务器未返回正确的状态码');
}
return $response->json('data');
});
} else {
// 从缓存中获取access_token
return Cache::get('pluginList');
}
}
/**
* 设置插件首页显示
*/
public function setShowHome(Request $request): JsonResponse
{
// 消毒
try {
$credentials = $this->validate($request, [
'slug' => 'required|max:255',
'show' => 'required|boolean',
]);
$slug = $credentials['slug'];
$show = $credentials['show'];
} catch (ValidationException $e) {
return response()->json(['code' => 1, 'msg' => $e->getMessage()]);
}
// 判断插件是否已经安装
$installed = isset(PLUGINS[$slug]);
if (!$installed) {
$data['code'] = 1;
$data['msg'] = '插件未安装!';
return response()->json($data);
}
Plugin::query()->where('slug', $slug)->updateOrInsert(
['slug' => $slug],
['show' => $show]
);
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = '设置成功';
return response()->json($res);
}
}
@@ -1,280 +0,0 @@
<?php
/**
* 耗子Linux面板 - 安全控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class SafesController extends Controller
{
/**
* 获取防火墙状态
* @return JsonResponse
*/
public function getFirewallStatus(): JsonResponse
{
$firewallStatus = trim(shell_exec("systemctl status firewalld | grep Active | awk '{print $3}'"));
$res['code'] = 0;
$res['msg'] = 'success';
if ($firewallStatus == '(running)') {
$res['data'] = 1;
} else {
$res['data'] = 0;
}
return response()->json($res);
}
/**
* 设置防火墙状态
* @param Request $request
* @return JsonResponse
*/
public function setFirewallStatus(Request $request): JsonResponse
{
$status = $request->input('status');
if ($status) {
shell_exec("systemctl enable firewalld");
shell_exec("systemctl start firewalld");
} else {
shell_exec("systemctl stop firewalld");
shell_exec("systemctl disable firewalld");
}
$res['code'] = 0;
$res['msg'] = 'success';
return response()->json($res);
}
/**
* 获取SSH状态
* @return JsonResponse
*/
public function getSshStatus(): JsonResponse
{
$sshStatus = trim(shell_exec("systemctl status sshd | grep Active | awk '{print $3}'"));
$res['code'] = 0;
$res['msg'] = 'success';
if ($sshStatus == '(running)') {
$res['data'] = 1;
} else {
$res['data'] = 0;
}
return response()->json($res);
}
/**
* 设置SSH状态
* @param Request $request
* @return JsonResponse
*/
public function setSshStatus(Request $request): JsonResponse
{
$status = $request->input('status');
if ($status) {
shell_exec("systemctl enable sshd");
shell_exec("systemctl start sshd");
} else {
shell_exec("systemctl stop sshd");
shell_exec("systemctl disable sshd");
}
$res['code'] = 0;
$res['msg'] = 'success';
return response()->json($res);
}
/**
* 获取SSH端口
* @return JsonResponse
*/
public function getSshPort(): JsonResponse
{
$sshPort = trim(shell_exec("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'"));
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = $sshPort;
return response()->json($res);
}
/**
* 设置SSH端口
* @param Request $request
* @return JsonResponse
*/
public function setSshPort(Request $request): JsonResponse
{
$port = $request->input('port');
// 只能是数字
if (!is_numeric($port)) {
$res['code'] = 1;
$res['msg'] = '端口只能是数字';
return response()->json($res);
}
$oldPort = trim(shell_exec("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'"));
shell_exec("sed -i 's/#Port ".$oldPort."/Port ".$port."/g' /etc/ssh/sshd_config");
shell_exec("sed -i 's/Port ".$oldPort."/Port ".$port."/g' /etc/ssh/sshd_config");
// 判断ssh是否开启
$sshStatus = trim(shell_exec("systemctl status sshd | grep Active | awk '{print $3}'"));
if ($sshStatus == '(running)') {
shell_exec("systemctl restart sshd");
}
$res['code'] = 0;
$res['msg'] = 'success';
return response()->json($res);
}
/**
* 获取ping状态
* @return JsonResponse
*/
public function getPingStatus(): JsonResponse
{
$pingStatus = trim(shell_exec("firewall-cmd --query-rich-rule='rule protocol value=icmp drop' 2>&1"));
$res['code'] = 0;
$res['msg'] = 'success';
if ($pingStatus == 'yes') {
$res['data'] = 0;
} else {
$res['data'] = 1;
}
return response()->json($res);
}
/**
* 设置ping状态
* @param Request $request
* @return JsonResponse
*/
public function setPingStatus(Request $request): JsonResponse
{
$status = $request->input('status');
if ($status) {
shell_exec("firewall-cmd --permanent --remove-rich-rule='rule protocol value=icmp drop' 2>&1");
} else {
shell_exec("firewall-cmd --permanent --add-rich-rule='rule protocol value=icmp drop' 2>&1");
}
shell_exec("firewall-cmd --reload");
$res['code'] = 0;
$res['msg'] = 'success';
return response()->json($res);
}
/**
* 获取防火墙规则
* @return JsonResponse
*/
public function getFirewallRules(): JsonResponse
{
$firewallRules = trim(shell_exec("firewall-cmd --list-all 2>&1"));
// 判断是否开启
if (str_contains($firewallRules, 'not running')) {
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = [];
return response()->json($res);
}
// 正则匹配出ports
preg_match('/ports: (.*)/', $firewallRules, $matches);
$rawPorts = $matches[1];
$ports = explode(' ', $rawPorts);
// 对ports进行分割为port=>protocol形式
$rules = [];
foreach ($ports as $port) {
$rule = explode('/', $port);
$rules[] = [
'port' => $rule[0],
'protocol' => $rule[1],
];
}
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = $rules;
return response()->json($res);
}
/**
* 添加防火墙规则
* @param Request $request
* @return JsonResponse
*/
public function addFirewallRule(Request $request): JsonResponse
{
// 消毒
try {
$input = $this->validate($request, [
'port' => ['required','regex:/^([0-9]+)(-([0-9]+))?$/'],
'protocol' => 'required|in:tcp,udp',
]);
$port = $input['port'];
$protocol = $input['protocol'];
} catch (ValidationException $e) {
return response()->json([
'code' => 1,
'msg' => '参数错误:'.$e->getMessage(),
'errors' => $e->errors()
], 200);
}
// 判断是否开启
$firewallStatus = trim(shell_exec("firewall-cmd --state 2>&1"));
if ($firewallStatus != 'running') {
$res['code'] = 1;
$res['msg'] = '防火墙未开启';
return response()->json($res);
}
// 清空当前规则
shell_exec("firewall-cmd --remove-port=".$port."/".$protocol." --permanent");
// 添加新的防火墙规则
shell_exec("firewall-cmd --add-port=".$port."/".$protocol." --permanent");
// 重启防火墙
shell_exec("firewall-cmd --reload");
$res['code'] = 0;
$res['msg'] = 'success';
return response()->json($res);
}
/**
* 删除防火墙规则
* @param Request $request
* @return JsonResponse
*/
public function deleteFirewallRule(Request $request): JsonResponse
{
// 消毒
try {
$input = $this->validate($request, [
'port' => ['required','regex:/^([0-9]+)(-([0-9]+))?$/'],
'protocol' => 'required|in:tcp,udp',
]);
$port = $input['port'];
$protocol = $input['protocol'];
} catch (ValidationException $e) {
return response()->json([
'code' => 1,
'msg' => '参数错误:'.$e->getMessage(),
'errors' => $e->errors()
], 200);
}
// 判断是否开启
$firewallStatus = trim(shell_exec("firewall-cmd --state 2>&1"));
if ($firewallStatus != 'running') {
$res['code'] = 1;
$res['msg'] = '防火墙未开启';
return response()->json($res);
}
// 清空当前规则
shell_exec("firewall-cmd --remove-port=".$port."/".$protocol." --permanent");
// 重启防火墙
shell_exec("firewall-cmd --reload");
$res['code'] = 0;
$res['msg'] = 'success';
return response()->json($res);
}
}
@@ -1,165 +0,0 @@
<?php
/**
* 耗子Linux面板 - 设置控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class SettingsController extends Controller
{
/**
* 获取面板设置
* @param Request $request
* @return JsonResponse
*/
public function get(Request $request): JsonResponse
{
$settings = Setting::all();
// 隐藏字段
$settings->makeHidden('id');
$settings->makeHidden('created_at');
$settings->makeHidden('updated_at');
$settingArr = $settings->pluck('value', 'name');
// 从nginx配置文件中获取面板端口
$nginxConf = file_get_contents('/www/server/nginx/conf/nginx.conf');
preg_match('/listen\s+(\d+)/', $nginxConf, $matches);
if (!isset($matches[1])) {
$res['code'] = 1;
$res['msg'] = '获取面板端口失败,请检查nginx主配置文件';
return response()->json($res);
}
// API
$api = 0;
$apiToken = '';
if (isset($settingArr['api']) && $settingArr['api'] == 1) {
$api = 1;
$apiToken = $settingArr['api_token'] ?? '';
}
// 多设备登录
$multiLogin = 0;
if (isset($settingArr['multi_login']) && $settingArr['multi_login'] == 1) {
$multiLogin = 1;
}
$data = [
'name' => $settingArr['name'],
'username' => $request->user()->username,
'email' => $request->user()->email,
'password' => '',
'port' => $matches[1],
'api' => $api,
'api_token' => $apiToken,
'multi_login' => $multiLogin,
];
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = $data;
return response()->json($res);
}
/**
* 保存面板设置
* @param Request $request
* @return JsonResponse
*/
public function save(Request $request): JsonResponse
{
// 获取前端传递过来的数据
$settings = $request->all();
// 将数据入库
foreach ($settings as $key => $value) {
if ($key == 'access_token' || $key == 'username' || $key == 'email' || $key == 'password' || $key == 'api_token' || $key == 'api' || $key == 'port') {
continue;
}
// 创建或更新
Setting::query()->updateOrCreate(['name' => $key], ['value' => $value]);
}
// 单独处理用户名、密码、邮箱
if ($request->input('username') != $request->user()->username) {
$request->user()->update(['username' => $request->input('username')]);
}
if ($request->input('password') != '') {
$request->user()->update(['password' => Hash::make($request->input('password'))]);
}
if ($request->input('email') != $request->user()->email) {
$request->user()->update(['email' => $request->input('email')]);
}
// 处理面板端口
$port = $request->input('port');
$nginxConf = file_get_contents('/www/server/nginx/conf/nginx.conf');
preg_match('/listen\s+(\d+)/', $nginxConf, $matches);
if (!isset($matches[1])) {
$res['code'] = 1;
$res['msg'] = '获取面板端口失败,请检查nginx主配置文件';
return response()->json($res);
}
if ($port != $matches[1]) {
$nginxConf = preg_replace('/listen\s+'.$matches[1].'/', 'listen '.$port, $nginxConf, 1);
file_put_contents('/www/server/nginx/conf/nginx.conf', $nginxConf);
// 重载nginx
shell_exec('systemctl reload nginx');
// 防火墙放行端口
$port = escapeshellarg($port);
shell_exec('firewall-cmd --permanent --zone=public --add-port='.$port.'/tcp >/dev/null 2>&1');
shell_exec('firewall-cmd --reload');
}
// 处理api
$api = $request->input('api', 0);
$apiCheck = Setting::query()->where('name', 'api')->value('value');
if (empty($apiCheck)) {
$apiCheck = 0;
}
if ($api != $apiCheck) {
if ($api) {
Setting::query()->insert([
'name' => 'api',
'value' => 1,
]);
// 生成api用户
$username = 'api_'.Str::random();
$apiUser = User::query()->create([
'username' => $username,
'password' => Hash::make(Str::random()),
'email' => 'panel_api@haozi.net',
]);
// 生成api token
$apiToken = $apiUser->createToken('api')->plainTextToken;
Setting::query()->insert([
'name' => 'api_user',
'value' => $username,
]);
Setting::query()->insert([
'name' => 'api_token',
'value' => $apiToken,
]);
} else {
Setting::query()->where('name', 'api')->delete();
Setting::query()->where('name', 'api_token')->delete();
$username = Setting::query()->where('name', 'api_user')->value('value');
Setting::query()->where('name', 'api_user')->delete();
Setting::query()->where('name', 'api')->delete();
$apiUser = User::query()->where('username', $username)->first();
// 删除api用户的所有token
$apiUser->tokens()->delete();
// 删除api用户
$apiUser->delete();
}
}
$res['code'] = 0;
$res['msg'] = 'success';
return response()->json($res);
}
}
@@ -1,120 +0,0 @@
<?php
/**
* 耗子Linux面板 - 任务控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Task;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class TasksController extends Controller
{
/**
* 获取是否有进行中/未完成的任务
* 前台会根据这个返回渲染顶部工具栏的图标
* @return JsonResponse
*/
public function getStatus(): JsonResponse
{
// 获取任务表中的等待中/进行中的任务
$task = Task::query()->where('status', 'running')->orWhere('status', 'waiting')->first();
$res['code'] = 0;
$res['msg'] = 'success';
if (empty($task)) {
$res['data'] = false;
} else {
$res['data'] = true;
}
return response()->json($res);
}
/**
* 获取进行中的那个任务
* @return JsonResponse
*/
public function getListRunning(): JsonResponse
{
// 获取进行中的任务列表
$task = Task::query()->where('status', 'running')->get()->toArray();
// 判断任务是否存在
if (empty($task)) {
$task[0] = "";
}
// 构建返回数据
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = $task[0];
return response()->json($res);
}
/**
* 获取等待中的任务列表
* @return JsonResponse
*/
public function getListWaiting(): JsonResponse
{
$task_list = Task::query()->where('status', 'waiting')->get()->toArray();
$res['code'] = 0;
$res['msg'] = 'success';
// 判断任务是否存在
if (empty($task_list)) {
$res['code'] = 1;
$res['msg'] = '无任务!';
}
$res['data'] = $task_list;
return response()->json($res);
}
/**
* 获取已完成的任务列表
* @return JsonResponse
*/
public function getListFinished(): JsonResponse
{
$task_list = Task::query()->where('status', 'finished')->get()->toArray();
$res['code'] = 0;
$res['msg'] = 'success';
if (empty($task_list)) {
$res['code'] = 1;
$res['msg'] = '无任务!';
}
$res['data'] = $task_list;
return response()->json($res);
}
/**
* 获取单个任务的log
* @param Request $request
* @return JsonResponse
*/
public function getTaskLog(Request $request): JsonResponse
{
$name = $request->get('name');
$log_file = Task::query()->where('name', $name)->value('log');
$log = shell_exec('tail -n 30 '.$log_file);
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = $log;
return response()->json($res);
}
/**
* 删除任务
* @param Request $request
* @return JsonResponse
*/
public function deleteTask(Request $request): JsonResponse
{
$name = $request->get('name');
$res['code'] = 0;
$res['msg'] = 'success';
$res['data'] = Task::query()->where('name', $name)->delete();
return response()->json($res);
}
}
@@ -1,62 +0,0 @@
<?php
/**
* 耗子Linux面板 - 用户控制器
* @author 耗子
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class UsersController extends Controller
{
/**
* 登录
*
* @param Request $request
* @return JsonResponse
*/
public function login(Request $request): JsonResponse
{
// 消毒数据
try {
$credentials = $this->validate($request, [
'username' => 'required|max:255',
'password' => 'required|max:255',
'remember' => 'required|boolean'
]);
} catch (ValidationException $e) {
return response()->json([
'code' => 1,
'msg' => '参数错误:'.$e->getMessage(),
'errors' => $e->errors()
], 422);
}
if (auth()->attempt(['username' => $credentials['username'], 'password' => $credentials['password']],
$credentials['remember'])) {
$user = auth()->user();
// 多设备登录
$multiLogin = Setting::query()->where('name', 'multi_login')->value('value');
if ($multiLogin != 1) {
$user->tokens()->delete();
}
$token = $user->createToken('token')->plainTextToken;
return response()->json(['code' => 0, 'msg' => '登录成功', 'data' => ['access_token' => $token]]);
} else {
return response()->json(['code' => 1, 'msg' => '登录失败,用户名或密码错误']);
}
}
public function getInfo(Request $request): JsonResponse
{
$user = $request->user();
$res['code'] = 0;
$res['msg'] = 'success';
$res['data']['username'] = $user->username;
return response()->json($res);
}
}
File diff suppressed because it is too large Load Diff
-13
View File
@@ -1,13 +0,0 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
-67
View File
@@ -1,67 +0,0 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\AddAccessToken::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
-21
View File
@@ -1,21 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
class AddAccessToken
{
/**
* Handle an incoming request.
*/
public function handle($request, Closure $next, ...$guards)
{
// 获取请求头中的token
$token = $request->header('access_token') ?? $request->input('access_token');
// 将token放入请求中
$request->headers->set('Authorization', 'Bearer '.$token);
return $next($request);
}
}
-27
View File
@@ -1,27 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
*
* @return string|null
*/
protected function redirectTo($request)
{
abort(response()->json([
'code' => 1001,
'msg' => '登录状态失效'
]));
}
}
-17
View File
@@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -1,32 +0,0 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @param string|null ...$guards
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
-19
View File
@@ -1,19 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
-20
View File
@@ -1,20 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}
-28
View File
@@ -1,28 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
-22
View File
@@ -1,22 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}
-17
View File
@@ -1,17 +0,0 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
-73
View File
@@ -1,73 +0,0 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Task;
class ProcessShell implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* 任务最大尝试次数
* @var int
*/
public int $tries = 1;
/**
* 任务运行的超时时间
* @var int
*/
public int $timeout = 7200;
/**
* 任务名
*/
public string $task_id;
/**
* 任务脚本
*/
public string $shell;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($task_id)
{
$this->task_id = $task_id;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(): void
{
// 检查当前是否有任务正在运行
$taskCheck = Task::query()->where('status', 'running')->get();
if ($taskCheck->isNotEmpty()) {
$this->release(10);
return;
}
// 查询任务
$task = Task::query()->where('id', $this->task_id)->first();
echo $task->name."开始执行".PHP_EOL;
// 更新任务状态为running
$task->job_id = $this->job->getJobId();
$task->status = 'running';
$task->save();
shell_exec($task->shell);
// 更新任务状态
$task->status = 'finished';
$task->save();
echo $task->name."执行完毕".PHP_EOL;
}
}
-22
View File
@@ -1,22 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Cron extends Model
{
use HasFactory;
// 白名单
protected $fillable = [
'name',
'status',
'type',
'time',
'shell',
'created_at',
'updated_at',
];
}
-11
View File
@@ -1,11 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Database extends Model
{
use HasFactory;
}
-18
View File
@@ -1,18 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Monitor extends Model
{
use HasFactory;
// 白名单
protected $fillable = [
'info',
'created_at',
'updated_at',
];
}
-14
View File
@@ -1,14 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Plugin extends Model
{
use HasFactory;
// 白名单
protected $fillable = ['slug', 'name', 'version', 'show', 'created_at', 'updated_at'];
}
-14
View File
@@ -1,14 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use HasFactory;
// 白名单
protected $fillable = ['name', 'value', 'created_at', 'updated_at'];
}
-22
View File
@@ -1,22 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
use HasFactory;
// 白名单
protected $fillable = [
'job_id',
'name',
'shell',
'log',
'status',
'created_at',
'updated_at',
];
}
-43
View File
@@ -1,43 +0,0 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'username',
'password',
'email'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
];
}
-14
View File
@@ -1,14 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Website extends Model
{
use HasFactory;
// 白名单
protected $fillable = ['name', 'status', 'path', 'php', 'ssl', 'ssl_date', 'note', 'created_at', 'updated_at'];
}
-28
View File
@@ -1,28 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
-30
View File
@@ -1,30 +0,0 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
@@ -1,21 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
-42
View File
@@ -1,42 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}
-69
View File
@@ -1,69 +0,0 @@
<?php
namespace App\Providers;
use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use App\Services\Plugin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class PluginServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @param Plugin $plugins
* @return void
* @throws BindingResolutionException
* @throws FileNotFoundException
*/
public function boot(Plugin $plugins): void
{
$loader = $this->app->make('translation.loader');
// Make view instead of view.finder since the finder is defined as not a singleton
$finder = $this->app->make('view');
foreach ($plugins->getPlugins() as $plugin) {
// 加载视图路径
$finder->addNamespace($plugin['slug'], $plugin['path']."/views");
// 加载语言包
$loader->addNamespace($plugin['slug'], $plugin['path']."/lang");
}
// 加载插件Composer装载文件
try {
foreach ($plugins->getComposerLoaders() as $autoloader) {
require $autoloader;
}
} catch (Exception $e) {
throw new BindingResolutionException($e->getMessage());
}
// 加载插件主文件
try {
foreach ($plugins->getPluginMainFiles() as $file) {
require_once $file;
}
} catch (Exception $e) {
throw new BindingResolutionException($e->getMessage());
}
}
/**
* 注册插件服务
*
* @return void
*/
public function register(): void
{
$this->app->singleton('plugins', Plugin::class);
// 设置面板名称
$name = @DB::table('settings')->where('name', 'name')->value('value');
$this->app['config']['panel.name'] = !empty($name) ? $name : config('panel.name');
}
}
-52
View File
@@ -1,52 +0,0 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}
-165
View File
@@ -1,165 +0,0 @@
<?php
namespace App\Services;
use Exception;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
class Plugin
{
/**
* @var Application
*/
protected Application $app;
/**
* @var Dispatcher
*/
protected Dispatcher $dispatcher;
/**
* @var Filesystem
*/
protected Filesystem $filesystem;
/**
* @var Collection|null
*/
protected ?Collection $plugins;
public function __construct(
Application $app,
Dispatcher $dispatcher,
Filesystem $filesystem,
Collection $plugins = new Collection()
) {
$this->app = $app;
$this->dispatcher = $dispatcher;
$this->filesystem = $filesystem;
$this->plugins = $plugins;
}
/**
* 读取所有插件
*
* @return Collection|null
* @throws FileNotFoundException
* @throws Exception
*/
public function getPlugins(): ?Collection
{
if ($this->plugins->isEmpty()) {
$plugins = new Collection();
$installed = [];
try {
$resource = opendir($this->getPluginsDir());
} catch (Exception $e) {
// 输出错误信息
throw new Exception($e->getMessage());
}
// 读取插件目录
while ($filename = @readdir($resource)) {
if ($filename == '.' || $filename == '..') {
continue;
}
$path = $this->getPluginsDir().DIRECTORY_SEPARATOR.$filename;
if (is_dir($path)) {
$pluginJsonPath = $path.DIRECTORY_SEPARATOR.'plugin.json';
if (file_exists($pluginJsonPath)) {
// 读取插件配置文件
$installed[$filename] = json_decode($this->filesystem->get($pluginJsonPath), true);
}
}
}
closedir($resource);
foreach ($installed as $dirname => $package) {
// 初始化插件信息
$plugin = [];
$plugin['name'] = (Arr::get($package, 'name'));
$plugin['author'] = (Arr::get($package, 'author'));
$plugin['describe'] = (Arr::get($package, 'describe'));
$plugin['slug'] = (Arr::get($package, 'slug'));
$plugin['version'] = (Arr::get($package, 'version'));
$plugin['path'] = $this->getPluginsDir().DIRECTORY_SEPARATOR.$dirname;
if ($plugins->has($plugin['slug'])) {
continue;
}
$plugins->put($plugin['slug'], $plugin);
}
define('PLUGINS', $plugins->toArray());
$this->plugins = $plugins;
}
return $this->plugins;
}
/**
* 获取全部插件的主文件
*
* @return Collection
* @throws Exception
*/
public function getPluginMainFiles(): Collection
{
$pluginMainFiles = new Collection;
try {
foreach ($this->getPlugins() as $plugin) {
if ($this->filesystem->exists($file = $plugin['path'].'/plugin.php')) {
$pluginMainFiles->push($file);
}
}
} catch (Exception $e) {
// 输出错误信息
throw new Exception($e->getMessage());
}
return $pluginMainFiles;
}
/**
* 获取全部插件的Composer装载文件
*
* @return Collection
* @throws Exception
*/
public function getComposerLoaders(): Collection
{
$composerLoaders = new Collection;
foreach ($this->getPlugins() as $plugin) {
if ($this->filesystem->exists($file = $plugin['path'].'/vendor/autoload.php')) {
$composerLoaders->push($file);
}
}
return $composerLoaders;
}
/**
* 插件目录
*
* @return string
*/
public function getPluginsDir(): string
{
return config('plugins.directory') ?: base_path('plugins');
}
}
+77
View File
@@ -0,0 +1,77 @@
package commands
import (
"strconv"
"github.com/gookit/color"
"github.com/goravel/framework/contracts/console"
"github.com/goravel/framework/contracts/console/command"
"github.com/goravel/framework/facades"
"github.com/goravel/framework/support/carbon"
"github.com/spf13/cast"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Monitoring struct {
}
// Signature The name and signature of the console command.
func (receiver *Monitoring) Signature() string {
return "panel:monitoring"
}
// Description The console command description.
func (receiver *Monitoring) Description() string {
return "[面板] 系统监控"
}
// Extend The console command extend.
func (receiver *Monitoring) Extend() command.Extend {
return command.Extend{
Category: "panel",
}
}
// Handle Execute the console command.
func (receiver *Monitoring) Handle(ctx console.Context) error {
var setting models.Setting
monitor := services.NewSettingImpl().Get(models.SettingKeyMonitor)
if !cast.ToBool(monitor) {
return nil
}
info := tools.GetMonitoringInfo()
err := facades.Orm().Query().Create(&models.Monitor{
Info: info,
})
if err != nil {
facades.Log().Errorf("[面板] 系统监控保存失败: %s", err.Error())
color.Redf("[面板] 系统监控保存失败: %s", err.Error())
return nil
}
// 删除过期数据
err = facades.Orm().Query().Where("key", "monitor_days").First(&setting)
if err != nil {
return nil
}
if setting.Value == "0" || len(setting.Value) == 0 {
return nil
}
days, err := strconv.Atoi(setting.Value)
if err != nil {
return nil
}
_, err = facades.Orm().Query().Where("created_at < ?", carbon.Now().SubDays(days).ToDateTimeString()).Delete(&models.Monitor{})
if err != nil {
facades.Log().Errorf("[面板] 系统监控删除过期数据失败: %s", err.Error())
return nil
}
return nil
}
+522
View File
@@ -0,0 +1,522 @@
package commands
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/gookit/color"
"github.com/goravel/framework/contracts/console"
"github.com/goravel/framework/contracts/console/command"
"github.com/goravel/framework/facades"
"github.com/goravel/framework/support/carbon"
"github.com/spf13/cast"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Panel struct {
}
// Signature The name and signature of the console command.
func (receiver *Panel) Signature() string {
return "panel"
}
// Description The console command description.
func (receiver *Panel) Description() string {
return "[面板] 命令行"
}
// Extend The console command extend.
func (receiver *Panel) Extend() command.Extend {
return command.Extend{
Category: "panel",
}
}
// Handle Execute the console command.
func (receiver *Panel) Handle(ctx console.Context) error {
action := ctx.Argument(0)
arg1 := ctx.Argument(1)
arg2 := ctx.Argument(2)
arg3 := ctx.Argument(3)
arg4 := ctx.Argument(4)
switch action {
case "init":
var check models.User
err := facades.Orm().Query().FirstOrFail(&check)
if err == nil {
color.Redln("面板已初始化")
return nil
}
settings := []models.Setting{{Key: models.SettingKeyName, Value: "耗子Linux面板"}, {Key: models.SettingKeyMonitor, Value: "1"}, {Key: models.SettingKeyMonitorDays, Value: "30"}, {Key: models.SettingKeyBackupPath, Value: "/www/backup"}, {Key: models.SettingKeyWebsitePath, Value: "/www/wwwroot"}, {Key: models.SettingKeyEntrance, Value: "/"}, {Key: models.SettingKeyVersion, Value: facades.Config().GetString("panel.version")}}
err = facades.Orm().Query().Create(&settings)
if err != nil {
color.Redln("初始化失败")
return nil
}
hash, err := facades.Hash().Make(tools.RandomString(32))
if err != nil {
color.Redln("初始化失败")
return nil
}
user := services.NewUserImpl()
_, err = user.Create("admin", hash)
if err != nil {
color.Redln("创建管理员失败")
return nil
}
color.Greenln("初始化成功")
case "update":
var task models.Task
err := facades.Orm().Query().Where("status", models.TaskStatusRunning).OrWhere("status", models.TaskStatusWaiting).FirstOrFail(&task)
if err == nil {
color.Redln("当前有任务正在执行,禁止更新")
return nil
}
panel, err := tools.GetLatestPanelVersion()
if err != nil {
color.Redln("获取最新版本失败")
return err
}
err = tools.UpdatePanel(panel)
if err != nil {
color.Redln("更新失败: " + err.Error())
return nil
}
color.Greenln("更新成功")
tools.RestartPanel()
case "getInfo":
var user models.User
err := facades.Orm().Query().Where("id", 1).FirstOrFail(&user)
if err != nil {
color.Redln("获取管理员信息失败")
return nil
}
password := tools.RandomString(16)
hash, err := facades.Hash().Make(password)
if err != nil {
color.Redln("生成密码失败")
return nil
}
user.Username = tools.RandomString(8)
user.Password = hash
err = facades.Orm().Query().Save(&user)
if err != nil {
color.Redln("保存管理员信息失败")
return nil
}
port := tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
color.Greenln("用户名: " + user.Username)
color.Greenln("密码: " + password)
color.Greenln("面板端口: " + port)
color.Greenln("面板入口: " + services.NewSettingImpl().Get(models.SettingKeyEntrance, "/"))
case "getPort":
port := tools.Exec("cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}'")
color.Greenln("面板端口: " + port)
case "getEntrance":
color.Greenln("面板入口: " + services.NewSettingImpl().Get(models.SettingKeyEntrance, "/"))
case "deleteEntrance":
err := services.NewSettingImpl().Set(models.SettingKeyEntrance, "/")
if err != nil {
color.Redln("删除面板入口失败")
return nil
}
color.Greenln("删除面板入口成功")
case "writePlugin":
slug := arg1
version := arg2
if len(slug) == 0 || len(version) == 0 {
color.Redln("参数错误")
return nil
}
var plugin models.Plugin
err := facades.Orm().Query().UpdateOrCreate(&plugin, models.Plugin{
Slug: slug,
}, models.Plugin{
Version: version,
})
if err != nil {
color.Redln("写入插件安装状态失败")
return nil
}
color.Greenln("写入插件安装状态成功")
case "deletePlugin":
slug := arg1
if len(slug) == 0 {
color.Redln("参数错误")
return nil
}
_, err := facades.Orm().Query().Where("slug", slug).Delete(&models.Plugin{})
if err != nil {
color.Redln("移除插件安装状态失败")
return nil
}
color.Greenln("移除插件安装状态成功")
case "writeMysqlPassword":
password := arg1
if len(password) == 0 {
color.Redln("参数错误")
return nil
}
var setting models.Setting
err := facades.Orm().Query().UpdateOrCreate(&setting, models.Setting{
Key: models.SettingKeyMysqlRootPassword,
}, models.Setting{
Value: password,
})
if err != nil {
color.Redln("写入MySQL root密码失败")
return nil
}
color.Greenln("写入MySQL root密码成功")
case "cleanTask":
_, err := facades.Orm().Query().Model(&models.Task{}).Where("status", models.TaskStatusRunning).OrWhere("status", models.TaskStatusWaiting).Update("status", models.TaskStatusFailed)
if err != nil {
color.Redln("清理任务失败")
return nil
}
color.Greenln("清理任务成功")
case "backup":
backupType := arg1
name := arg2
path := arg3
save := arg4
hr := `+----------------------------------------------------`
if len(backupType) == 0 || len(name) == 0 || len(path) == 0 || len(save) == 0 {
color.Redln("参数错误")
return nil
}
color.Greenln(hr)
color.Greenln("★ 开始备份 [" + carbon.Now().ToDateTimeString() + "]")
color.Greenln(hr)
if !tools.Exists(path) {
tools.Mkdir(path, 0644)
}
switch backupType {
case "website":
color.Yellowln("|-目标网站: " + name)
var website models.Website
if err := facades.Orm().Query().Where("name", name).FirstOrFail(&website); err != nil {
color.Redln("|-网站不存在")
color.Greenln(hr)
return nil
}
backupFile := path + "/" + website.Name + "_" + carbon.Now().ToShortDateTimeString() + ".zip"
tools.Exec(`cd '` + website.Path + `' && zip -r '` + backupFile + `' .`)
color.Greenln("|-备份成功")
case "mysql":
rootPassword := services.NewSettingImpl().Get(models.SettingKeyMysqlRootPassword)
backupFile := name + "_" + carbon.Now().ToShortDateTimeString() + ".sql"
err := os.Setenv("MYSQL_PWD", rootPassword)
if err != nil {
color.Redln("|-备份MySQL数据库失败: " + err.Error())
color.Greenln(hr)
return nil
}
color.Greenln("|-目标MySQL数据库: " + name)
color.Greenln("|-开始导出")
tools.Exec(`mysqldump -uroot ` + name + ` > /tmp/` + backupFile + ` 2>&1`)
color.Greenln("|-导出成功")
color.Greenln("|-开始压缩")
tools.Exec("cd /tmp && zip -r " + backupFile + ".zip " + backupFile)
tools.Remove("/tmp/" + backupFile)
color.Greenln("|-压缩成功")
color.Greenln("|-开始移动")
if _, err := tools.Mv("/tmp/"+backupFile+".zip", path+"/"+backupFile+".zip"); err != nil {
color.Redln("|-移动失败: " + err.Error())
return nil
}
color.Greenln("|-移动成功")
_ = os.Unsetenv("MYSQL_PWD")
color.Greenln("|-备份成功")
case "postgresql":
backupFile := name + "_" + carbon.Now().ToShortDateTimeString() + ".sql"
check := tools.Exec(`su - postgres -c "psql -l" 2>&1`)
if strings.Contains(check, name) {
color.Redln("|-数据库不存在")
color.Greenln(hr)
return nil
}
color.Greenln("|-目标PostgreSQL数据库: " + name)
color.Greenln("|-开始导出")
tools.Exec(`su - postgres -c "pg_dump '` + name + `'" > /tmp/` + backupFile + ` 2>&1`)
color.Greenln("|-导出成功")
color.Greenln("|-开始压缩")
tools.Exec("cd /tmp && zip -r " + backupFile + ".zip " + backupFile)
tools.Remove("/tmp/" + backupFile)
color.Greenln("|-压缩成功")
color.Greenln("|-开始移动")
if _, err := tools.Mv("/tmp/"+backupFile+".zip", path+"/"+backupFile+".zip"); err != nil {
color.Redln("|-移动失败: " + err.Error())
return nil
}
color.Greenln("|-移动成功")
color.Greenln("|-备份成功")
}
color.Greenln(hr)
files, err := os.ReadDir(path)
if err != nil {
color.Redln("|-清理失败: " + err.Error())
return nil
}
var filteredFiles []os.FileInfo
for _, file := range files {
if strings.HasPrefix(file.Name(), name) && strings.HasSuffix(file.Name(), ".zip") {
fileInfo, err := os.Stat(filepath.Join(path, file.Name()))
if err != nil {
continue
}
filteredFiles = append(filteredFiles, fileInfo)
}
}
sort.Slice(filteredFiles, func(i, j int) bool {
return filteredFiles[i].ModTime().After(filteredFiles[j].ModTime())
})
for i := cast.ToInt(save); i < len(filteredFiles); i++ {
fileToDelete := filepath.Join(path, filteredFiles[i].Name())
color.Yellowln("|-清理备份: " + fileToDelete)
tools.Remove(fileToDelete)
}
color.Greenln("|-清理完成")
color.Greenln(hr)
color.Greenln("☆ 备份完成 [" + carbon.Now().ToDateTimeString() + "]")
color.Greenln(hr)
case "cutoff":
name := arg1
save := arg2
hr := `+----------------------------------------------------`
if len(name) == 0 || len(save) == 0 {
color.Redln("参数错误")
return nil
}
color.Greenln(hr)
color.Greenln("★ 开始切割 [" + carbon.Now().ToDateTimeString() + "]")
color.Greenln(hr)
color.Yellowln("|-目标网站: " + name)
var website models.Website
if err := facades.Orm().Query().Where("name", name).FirstOrFail(&website); err != nil {
color.Redln("|-网站不存在")
color.Greenln(hr)
return nil
}
logPath := "/www/wwwlogs/" + website.Name + ".log"
if !tools.Exists(logPath) {
color.Redln("|-日志文件不存在")
color.Greenln(hr)
return nil
}
backupPath := "/www/wwwlogs/" + website.Name + "_" + carbon.Now().ToShortDateTimeString() + ".log.zip"
tools.Exec(`cd /www/wwwlogs && zip -r ` + backupPath + ` ` + website.Name + ".log")
tools.Exec(`echo "" > ` + logPath)
color.Greenln("|-切割成功")
color.Greenln(hr)
files, err := os.ReadDir("/www/wwwlogs")
if err != nil {
color.Redln("|-清理失败: " + err.Error())
return nil
}
var filteredFiles []os.FileInfo
for _, file := range files {
if strings.HasPrefix(file.Name(), website.Name) && strings.HasSuffix(file.Name(), ".log.zip") {
fileInfo, err := os.Stat(filepath.Join("/www/wwwlogs", file.Name()))
if err != nil {
continue
}
filteredFiles = append(filteredFiles, fileInfo)
}
}
sort.Slice(filteredFiles, func(i, j int) bool {
return filteredFiles[i].ModTime().After(filteredFiles[j].ModTime())
})
for i := cast.ToInt(save); i < len(filteredFiles); i++ {
fileToDelete := filepath.Join("/www/wwwlogs", filteredFiles[i].Name())
color.Yellowln("|-清理日志: " + fileToDelete)
tools.Remove(fileToDelete)
}
color.Greenln("|-清理完成")
color.Greenln(hr)
color.Greenln("☆ 切割完成 [" + carbon.Now().ToDateTimeString() + "]")
color.Greenln(hr)
case "writeSite":
name := arg1
status := cast.ToBool(arg2)
path := ctx.Argument(3)
php := cast.ToInt(ctx.Argument(4))
ssl := cast.ToBool(ctx.Argument(5))
if len(name) == 0 || len(path) == 0 {
color.Redln("参数错误")
return nil
}
var website models.Website
if err := facades.Orm().Query().Where("name", name).FirstOrFail(&website); err == nil {
color.Redln("网站已存在")
return nil
}
_, err := os.Stat(path)
if os.IsNotExist(err) {
color.Redln("网站目录不存在")
return nil
}
err = facades.Orm().Query().Create(&models.Website{
Name: name,
Status: status,
Path: path,
Php: php,
Ssl: ssl,
})
if err != nil {
color.Redln("写入网站失败")
return nil
}
color.Greenln("写入网站成功")
case "deleteSite":
name := arg1
if len(name) == 0 {
color.Redln("参数错误")
return nil
}
_, err := facades.Orm().Query().Where("name", name).Delete(&models.Website{})
if err != nil {
color.Redln("删除网站失败")
return nil
}
color.Greenln("删除网站成功")
case "writeSetting":
key := arg1
value := arg2
if len(key) == 0 || len(value) == 0 {
color.Redln("参数错误")
return nil
}
var setting models.Setting
err := facades.Orm().Query().UpdateOrCreate(&setting, models.Setting{
Key: key,
}, models.Setting{
Value: value,
})
if err != nil {
color.Redln("写入设置失败")
return nil
}
color.Greenln("写入设置成功")
case "getSetting":
key := arg1
if len(key) == 0 {
color.Redln("参数错误")
return nil
}
var setting models.Setting
if err := facades.Orm().Query().Where("key", key).FirstOrFail(&setting); err != nil {
return nil
}
fmt.Printf("%s", setting.Value)
case "deleteSetting":
key := arg1
if len(key) == 0 {
color.Redln("参数错误")
return nil
}
_, err := facades.Orm().Query().Where("key", key).Delete(&models.Setting{})
if err != nil {
color.Redln("删除设置失败")
return nil
}
color.Greenln("删除设置成功")
default:
color.Yellowln(facades.Config().GetString("panel.name") + "命令行工具 - " + facades.Config().GetString("panel.version"))
color.Greenln("请使用以下命令:")
color.Greenln("panel update 更新 / 修复面板到最新版本")
color.Greenln("panel getInfo 重新初始化面板账号信息")
color.Greenln("panel getPort 获取面板访问端口")
color.Greenln("panel getEntrance 获取面板访问入口")
color.Greenln("panel deleteEntrance 删除面板访问入口")
color.Greenln("panel cleanTask 清理面板运行中和等待中的任务[任务卡住时使用]")
color.Greenln("panel backup {website/mysql/postgresql} {name} {path} {save_copies} 备份网站 / MySQL数据库 / PostgreSQL数据库到指定目录并保留指定数量")
color.Greenln("panel cutoff {website_name} {save_copies} 切割网站日志并保留指定数量")
color.Redln("以下命令请在开发者指导下使用:")
color.Yellowln("panel init 初始化面板")
color.Yellowln("panel writePlugin {slug} {version} 写入插件安装状态")
color.Yellowln("panel deletePlugin {slug} 移除插件安装状态")
color.Yellowln("panel writeMysqlPassword {password} 写入MySQL root密码")
color.Yellowln("panel writeSite {name} {status} {path} {php} {ssl} 写入网站数据到面板")
color.Yellowln("panel deleteSite {name} 删除面板网站数据")
color.Yellowln("panel getSetting {name} 获取面板设置数据")
color.Yellowln("panel writeSetting {name} {value} 写入 / 更新面板设置数据")
color.Yellowln("panel deleteSetting {name} 删除面板设置数据")
}
return nil
}
+25
View File
@@ -0,0 +1,25 @@
package console
import (
"github.com/goravel/framework/contracts/console"
"github.com/goravel/framework/contracts/schedule"
"github.com/goravel/framework/facades"
"panel/app/console/commands"
)
type Kernel struct {
}
func (kernel *Kernel) Schedule() []schedule.Event {
return []schedule.Event{
facades.Schedule().Command("panel:monitoring").EveryMinute().SkipIfStillRunning(),
}
}
func (kernel *Kernel) Commands() []console.Command {
return []console.Command{
&commands.Panel{},
&commands.Monitoring{},
}
}
-70
View File
@@ -1,70 +0,0 @@
<?php
/**
* 耗子Linux面板 - 帮助函数
* @author 耗子
*/
/**
* 获取网络统计信息
* @return array
*/
function getNetInfo(): array
{
$networkRaw = file_get_contents('/proc/net/dev');
$networkArr = explode("\n", $networkRaw);
foreach ($networkArr as $key => $val) {
if ($key < 2) {
continue;
}
$val = str_replace(':', ' ', trim($val));
$val = preg_replace("/[ ]+/", " ", $val);
$arr = explode(' ', $val);
if (!empty($arr[0])) {
$arr = array($arr[0], $arr[1], $arr[9]);
$allRs[$arr[0].$key] = $arr;
}
}
ksort($allRs);
$tx = 0;
$rx = 0;
foreach ($allRs as $key => $val) {
// 排除本地lo
if (str_contains($key, 'lo')) {
continue;
}
$tx += $val[2];
$rx += $val[1];
}
$res['tx'] = $tx;
$res['rx'] = $rx;
return $res;
}
/**
* 格式化bytes
* @param $size
* @return string
*/
function formatBytes($size): string
{
$size = is_numeric($size) ? $size : 0;
$units = array(' B', ' KB', ' MB', ' GB', ' TB');
for ($i = 0; $size >= 1024 && $i < 4; $i++) {
$size /= 1024;
}
return round($size, 2).$units[$i];
}
/**
* 裁剪字符串
* @param $begin
* @param $end
* @param $str
* @return string
*/
function cut($begin, $end, $str): string
{
$b = mb_strpos($str, $begin) + mb_strlen($begin);
$e = mb_strpos($str, $end) - $b;
return mb_substr($str, $b, $e);
}
+277
View File
@@ -0,0 +1,277 @@
package controllers
import (
"regexp"
"strconv"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/goravel/framework/support/carbon"
"github.com/spf13/cast"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type CronController struct {
cron services.Cron
setting services.Setting
}
func NewCronController() *CronController {
return &CronController{
cron: services.NewCronImpl(),
setting: services.NewSettingImpl(),
}
}
// List 获取计划任务列表
func (c *CronController) List(ctx http.Context) http.Response {
limit := ctx.Request().QueryInt("limit", 10)
page := ctx.Request().QueryInt("page", 1)
var crons []models.Cron
var total int64
err := facades.Orm().Query().Paginate(page, limit, &crons, &total)
if err != nil {
facades.Log().Error("[面板][CronController] 查询计划任务列表失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, http.Json{
"total": total,
"items": crons,
})
}
// Add 添加计划任务
func (c *CronController) Add(ctx http.Context) http.Response {
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"time": "required",
"script": "required",
"type": "required|in:shell,backup,cutoff",
"backup_type": "required_if:type,backup|in:website,mysql,postgresql",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
// 单独验证时间格式
if !regexp.MustCompile(`^((\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+)(,(\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+))*\s?){5}$`).MatchString(ctx.Request().Input("time")) {
return Error(ctx, http.StatusBadRequest, "时间格式错误")
}
shell := ctx.Request().Input("script")
cronType := ctx.Request().Input("type")
if cronType == "backup" {
backupType := ctx.Request().Input("backup_type")
backupName := ctx.Request().Input("backup_database")
if backupType == "website" {
backupName = ctx.Request().Input("website")
}
backupPath := ctx.Request().Input("backup_path")
if len(backupPath) == 0 {
backupPath = c.setting.Get(models.SettingKeyBackupPath) + "/" + backupType
}
backupSave := ctx.Request().InputInt("save", 10)
shell = `#!/bin/bash
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:$PATH
# 耗子Linux面板 - 数据备份脚本
type=` + backupType + `
path=` + backupPath + `
name=` + backupName + `
save=` + cast.ToString(backupSave) + `
# 执行备份
panel backup ${type} ${name} ${path} ${save} 2>&1
`
}
if cronType == "cutoff" {
website := ctx.Request().Input("website")
save := ctx.Request().InputInt("save", 180)
shell = `#!/bin/bash
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:$PATH
# 耗子Linux面板 - 日志切割脚本
name=` + website + `
save=` + cast.ToString(save) + `
# 执行切割
panel cutoff ${name} ${save} 2>&1
`
}
shellDir := "/www/server/cron/"
shellLogDir := "/www/server/cron/logs/"
if !tools.Exists(shellDir) {
facades.Log().Error("[面板][CronController] 计划任务目录不存在")
return Error(ctx, http.StatusInternalServerError, "计划任务目录不存在")
}
if !tools.Exists(shellLogDir) {
facades.Log().Error("[面板][CronController] 计划任务日志目录不存在")
return Error(ctx, http.StatusInternalServerError, "计划任务日志目录不存在")
}
shellFile := strconv.Itoa(int(carbon.Now().Timestamp())) + tools.RandomString(16)
if !tools.Write(shellDir+shellFile+".sh", shell, 0700) {
facades.Log().Error("[面板][CronController] 创建计划任务脚本失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
tools.Exec("dos2unix " + shellDir + shellFile + ".sh")
var cron models.Cron
cron.Name = ctx.Request().Input("name")
cron.Type = ctx.Request().Input("type")
cron.Status = true
cron.Time = ctx.Request().Input("time")
cron.Shell = shellDir + shellFile + ".sh"
cron.Log = shellLogDir + shellFile + ".log"
err = facades.Orm().Query().Create(&cron)
if err != nil {
facades.Log().Error("[面板][CronController] 创建计划任务失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.cron.AddToSystem(cron)
return Success(ctx, http.Json{
"id": cron.ID,
})
}
// Script 获取脚本内容
func (c *CronController) Script(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
}
return Success(ctx, tools.Read(cron.Shell))
}
// Update 更新计划任务
func (c *CronController) Update(ctx http.Context) http.Response {
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"time": "required",
"script": "required",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
// 单独验证时间格式
if !regexp.MustCompile(`^((\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+)(,(\*|\d+|\d+-\d+|\d+/\d+|\d+-\d+/\d+|\*/\d+))*\s?){5}$`).MatchString(ctx.Request().Input("time")) {
return Error(ctx, http.StatusBadRequest, "时间格式错误")
}
var cron models.Cron
err = facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
}
if !cron.Status {
return Error(ctx, http.StatusBadRequest, "计划任务已禁用")
}
cron.Time = ctx.Request().Input("time")
cron.Name = ctx.Request().Input("name")
err = facades.Orm().Query().Save(&cron)
if err != nil {
facades.Log().Error("[面板][CronController] 更新计划任务失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if !tools.Write(cron.Shell, ctx.Request().Input("script"), 0644) {
facades.Log().Error("[面板][CronController] 更新计划任务脚本失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
tools.Exec("dos2unix " + cron.Shell)
c.cron.DeleteFromSystem(cron)
if cron.Status {
c.cron.AddToSystem(cron)
}
return Success(ctx, nil)
}
// Delete 删除计划任务
func (c *CronController) Delete(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
}
c.cron.DeleteFromSystem(cron)
tools.Remove(cron.Shell)
_, err = facades.Orm().Query().Delete(&cron)
if err != nil {
facades.Log().Error("[面板][CronController] 删除计划任务失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
// Status 更新计划任务状态
func (c *CronController) Status(ctx http.Context) http.Response {
validator, err := ctx.Request().Validate(map[string]string{
"status": "bool",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
var cron models.Cron
err = facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
}
cron.Status = ctx.Request().InputBool("status")
err = facades.Orm().Query().Save(&cron)
if err != nil {
facades.Log().Error("[面板][CronController] 更新计划任务状态失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.cron.DeleteFromSystem(cron)
if cron.Status {
c.cron.AddToSystem(cron)
}
return Success(ctx, nil)
}
// Log 获取计划任务日志
func (c *CronController) Log(ctx http.Context) http.Response {
var cron models.Cron
err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&cron)
if err != nil {
return Error(ctx, http.StatusBadRequest, "计划任务不存在")
}
if !tools.Exists(cron.Log) {
return Error(ctx, http.StatusBadRequest, "日志文件不存在")
}
return Success(ctx, tools.Read(cron.Log))
}
+11
View File
@@ -0,0 +1,11 @@
package controllers
type FileController struct {
// Dependent services
}
func NewFileController() *FileController {
return &FileController{
// Inject services
}
}
+69
View File
@@ -0,0 +1,69 @@
package controllers
import (
"sync"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/app/services"
)
func Success(ctx http.Context, data any) http.Response {
return ctx.Response().Success().Json(http.Json{
"code": 0,
"message": "success",
"data": data,
})
}
func Error(ctx http.Context, code int, message any) http.Response {
return ctx.Response().Json(http.StatusOK, http.Json{
"code": code,
"message": message,
})
}
// Check 检查插件是否可用
func Check(ctx http.Context, slug string) http.Response {
plugin := services.NewPluginImpl().GetBySlug(slug)
installedPlugin := services.NewPluginImpl().GetInstalledBySlug(slug)
installedPlugins, err := services.NewPluginImpl().AllInstalled()
if err != nil {
facades.Log().Error("[面板][插件] 获取已安装插件失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if installedPlugin.Version != plugin.Version || installedPlugin.Slug != plugin.Slug {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 需要更新至 "+plugin.Version+" 版本")
}
var lock sync.RWMutex
pluginsMap := make(map[string]bool)
for _, p := range installedPlugins {
lock.Lock()
pluginsMap[p.Slug] = true
lock.Unlock()
}
for _, require := range plugin.Requires {
lock.RLock()
_, requireFound := pluginsMap[require]
lock.RUnlock()
if !requireFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 需要依赖 "+require+" 插件")
}
}
for _, exclude := range plugin.Excludes {
lock.RLock()
_, excludeFound := pluginsMap[exclude]
lock.RUnlock()
if excludeFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 不兼容 "+exclude+" 插件")
}
}
return nil
}
+334
View File
@@ -0,0 +1,334 @@
package controllers
import (
"database/sql"
"fmt"
"regexp"
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type MenuItem struct {
Name string `json:"name"`
Title string `json:"title"`
Icon string `json:"icon"`
Jump string `json:"jump"`
}
type InfoController struct {
plugin services.Plugin
setting services.Setting
}
func NewInfoController() *InfoController {
return &InfoController{
plugin: services.NewPluginImpl(),
setting: services.NewSettingImpl(),
}
}
// Name 获取面板名称
func (c *InfoController) Name(ctx http.Context) http.Response {
var setting models.Setting
err := facades.Orm().Query().Where("key", "name").First(&setting)
if err != nil {
facades.Log().Error("[面板][InfoController] 查询面板名称失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, http.Json{
"name": setting.Value,
})
}
// HomePlugins 获取首页插件
func (c *InfoController) HomePlugins(ctx http.Context) http.Response {
var plugins []models.Plugin
err := facades.Orm().Query().Where("show", 1).Find(&plugins)
if err != nil {
facades.Log().Error("[面板][InfoController] 查询首页插件失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
type pluginsData struct {
models.Plugin
Name string `json:"name"`
}
var pluginsJson []pluginsData
for _, plugin := range plugins {
pluginsJson = append(pluginsJson, pluginsData{
Plugin: plugin,
Name: services.NewPluginImpl().GetBySlug(plugin.Slug).Name,
})
}
return Success(ctx, pluginsJson)
}
// NowMonitor 获取当前监控信息
func (c *InfoController) NowMonitor(ctx http.Context) http.Response {
return Success(ctx, tools.GetMonitoringInfo())
}
// SystemInfo 获取系统信息
func (c *InfoController) SystemInfo(ctx http.Context) http.Response {
monitorInfo := tools.GetMonitoringInfo()
return Success(ctx, http.Json{
"os_name": monitorInfo.Host.Platform + " " + monitorInfo.Host.PlatformVersion,
"uptime": fmt.Sprintf("%.2f", float64(monitorInfo.Host.Uptime)/86400),
"panel_version": facades.Config().GetString("panel.version"),
})
}
// CountInfo 获取面板统计信息
func (c *InfoController) CountInfo(ctx http.Context) http.Response {
var websiteCount int64
err := facades.Orm().Query().Model(models.Website{}).Count(&websiteCount)
if err != nil {
websiteCount = -1
}
var mysql models.Plugin
mysqlInstalled := true
err = facades.Orm().Query().Where("slug like ?", "mysql%").FirstOrFail(&mysql)
if err != nil {
mysqlInstalled = false
}
var postgresql models.Plugin
postgresqlInstalled := true
err = facades.Orm().Query().Where("slug like ?", "postgresql%").FirstOrFail(&postgresql)
if err != nil {
postgresqlInstalled = false
}
var databaseCount int64
if mysqlInstalled {
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if status == "active" {
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
type database struct {
Name string `json:"name"`
}
db, err := sql.Open("mysql", "root:"+rootPassword+"@unix(/tmp/mysql.sock)/")
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 获取数据库列表失败")
databaseCount = -1
} else {
defer db.Close()
rows, err := db.Query("SHOW DATABASES")
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 获取数据库列表失败")
databaseCount = -1
} else {
defer rows.Close()
var databases []database
for rows.Next() {
var d database
err := rows.Scan(&d.Name)
if err != nil {
continue
}
if d.Name == "information_schema" || d.Name == "performance_schema" || d.Name == "mysql" || d.Name == "sys" {
continue
}
databases = append(databases, d)
}
databaseCount = int64(len(databases))
}
}
}
}
if postgresqlInstalled {
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if status == "active" {
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
databases = databases[3 : len(databases)-1]
for _, db := range databases {
parts := strings.Split(db, "|")
if len(parts) != 9 || len(strings.TrimSpace(parts[0])) == 0 || strings.TrimSpace(parts[0]) == "template0" || strings.TrimSpace(parts[0]) == "template1" || strings.TrimSpace(parts[0]) == "postgres" {
continue
}
databaseCount++
}
}
}
var ftpCount int64
var ftpPlugin = c.plugin.GetInstalledBySlug("pureftpd")
if ftpPlugin.ID != 0 {
listRaw := tools.Exec("pure-pw list")
if len(listRaw) != 0 {
listArr := strings.Split(listRaw, "\n")
ftpCount = int64(len(listArr))
}
}
var cronCount int64
err = facades.Orm().Query().Model(models.Cron{}).Count(&cronCount)
if err != nil {
cronCount = -1
}
return Success(ctx, http.Json{
"website": websiteCount,
"database": databaseCount,
"ftp": ftpCount,
"cron": cronCount,
})
}
// InstalledDbAndPhp 获取已安装的数据库和 PHP 版本
func (c *InfoController) InstalledDbAndPhp(ctx http.Context) http.Response {
var php []models.Plugin
err := facades.Orm().Query().Where("slug like ?", "php%").Find(&php)
if err != nil {
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
var mysql models.Plugin
mysqlInstalled := true
err = facades.Orm().Query().Where("slug like ?", "mysql%").FirstOrFail(&mysql)
if err != nil {
mysqlInstalled = false
}
var postgresql models.Plugin
postgresqlInstalled := true
err = facades.Orm().Query().Where("slug like ?", "postgresql%").FirstOrFail(&postgresql)
if err != nil {
postgresqlInstalled = false
}
type data struct {
Label string `json:"label"`
Value string `json:"value"`
}
var phpData []data
var dbData []data
phpData = append(phpData, data{Value: "0", Label: "不使用"})
dbData = append(dbData, data{Value: "0", Label: "不使用"})
for _, p := range php {
match := regexp.MustCompile(`php(\d+)`).FindStringSubmatch(p.Slug)
if len(match) == 0 {
continue
}
phpData = append(phpData, data{Value: strings.ReplaceAll(p.Slug, "php", ""), Label: c.plugin.GetBySlug(p.Slug).Name})
}
if mysqlInstalled {
dbData = append(dbData, data{Value: "mysql", Label: "MySQL"})
}
if postgresqlInstalled {
dbData = append(dbData, data{Value: "postgresql", Label: "PostgreSQL"})
}
return Success(ctx, http.Json{
"php": phpData,
"db": dbData,
})
}
// CheckUpdate 检查面板更新
func (c *InfoController) CheckUpdate(ctx http.Context) http.Response {
version := facades.Config().GetString("panel.version")
remote, err := tools.GetLatestPanelVersion()
if err != nil {
return Error(ctx, http.StatusInternalServerError, "获取最新版本失败")
}
if tools.VersionCompare(version, remote.Version, ">=") {
return Success(ctx, http.Json{
"update": false,
})
}
return Success(ctx, http.Json{
"update": true,
})
}
// UpdateInfo 获取更新信息
func (c *InfoController) UpdateInfo(ctx http.Context) http.Response {
version := facades.Config().GetString("panel.version")
current, err := tools.GetLatestPanelVersion()
if err != nil {
return Error(ctx, http.StatusInternalServerError, "获取最新版本失败")
}
if tools.VersionCompare(version, current.Version, ">=") {
return Error(ctx, http.StatusInternalServerError, "当前版本已是最新版本")
}
versions, err := tools.GenerateVersions(version, current.Version)
if err != nil {
return Error(ctx, http.StatusInternalServerError, "获取更新信息失败")
}
var versionInfo []tools.PanelInfo
for _, v := range versions {
info, err := tools.GetPanelVersion(v)
if err != nil {
continue
}
versionInfo = append(versionInfo, info)
}
return Success(ctx, versionInfo)
}
// Update 更新面板
func (c *InfoController) Update(ctx http.Context) http.Response {
var task models.Task
err := facades.Orm().Query().Where("status", models.TaskStatusRunning).OrWhere("status", models.TaskStatusWaiting).FirstOrFail(&task)
if err == nil {
return Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止更新")
}
panel, err := tools.GetLatestPanelVersion()
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 获取最新版本失败")
return Error(ctx, http.StatusInternalServerError, "获取最新版本失败")
}
err = tools.UpdatePanel(panel)
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][InfoController] 更新面板失败")
return Error(ctx, http.StatusInternalServerError, "更新失败: "+err.Error())
}
tools.RestartPanel()
return Success(ctx, nil)
}
// Restart 重启面板
func (c *InfoController) Restart(ctx http.Context) http.Response {
var task models.Task
err := facades.Orm().Query().Where("status", models.TaskStatusRunning).OrWhere("status", models.TaskStatusWaiting).FirstOrFail(&task)
if err == nil {
return Error(ctx, http.StatusInternalServerError, "当前有任务正在执行,禁止重启")
}
tools.RestartPanel()
return Success(ctx, nil)
}
+171
View File
@@ -0,0 +1,171 @@
package controllers
import (
"fmt"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/goravel/framework/support/carbon"
"github.com/spf13/cast"
"panel/app/models"
"panel/app/services"
)
type MonitorController struct {
setting services.Setting
}
func NewMonitorController() *MonitorController {
return &MonitorController{
setting: services.NewSettingImpl(),
}
}
// Switch 监控开关
func (r *MonitorController) Switch(ctx http.Context) http.Response {
value := ctx.Request().InputBool("monitor")
err := r.setting.Set(models.SettingKeyMonitor, cast.ToString(value))
if err != nil {
facades.Log().Error("[面板][MonitorController] 更新监控开关失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
// SaveDays 保存监控天数
func (r *MonitorController) SaveDays(ctx http.Context) http.Response {
days := ctx.Request().Input("days")
err := r.setting.Set(models.SettingKeyMonitorDays, days)
if err != nil {
facades.Log().Error("[面板][MonitorController] 更新监控天数失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
// SwitchAndDays 监控开关和监控天数
func (r *MonitorController) SwitchAndDays(ctx http.Context) http.Response {
monitor := r.setting.Get(models.SettingKeyMonitor)
monitorDays := r.setting.Get(models.SettingKeyMonitorDays)
return Success(ctx, http.Json{
"switch": cast.ToBool(monitor),
"days": cast.ToInt(monitorDays),
})
}
// Clear 清空监控数据
func (r *MonitorController) Clear(ctx http.Context) http.Response {
_, err := facades.Orm().Query().Where("1 = 1").Delete(&models.Monitor{})
if err != nil {
facades.Log().Error("[面板][MonitorController] 清空监控数据失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
// List 监控数据列表
func (r *MonitorController) List(ctx http.Context) http.Response {
start := ctx.Request().InputInt64("start")
end := ctx.Request().InputInt64("end")
startTime := carbon.FromTimestampMilli(start)
endTime := carbon.FromTimestampMilli(end)
var monitors []models.Monitor
err := facades.Orm().Query().Where("created_at >= ?", startTime.ToDateTimeString()).Where("created_at <= ?", endTime.ToDateTimeString()).Get(&monitors)
if err != nil {
facades.Log().Error("[面板][MonitorController] 查询监控数据失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if len(monitors) == 0 {
return Error(ctx, http.StatusNotFound, "监控数据为空")
}
type load struct {
Load1 []float64 `json:"load1"`
Load5 []float64 `json:"load5"`
Load15 []float64 `json:"load15"`
}
type cpu struct {
Percent []string `json:"percent"`
}
type mem struct {
Total string `json:"total"`
Available []string `json:"available"`
Used []string `json:"used"`
}
type swap struct {
Total string `json:"total"`
Used []string `json:"used"`
Free []string `json:"free"`
}
type network struct {
Sent []string `json:"sent"`
Recv []string `json:"recv"`
Tx []string `json:"tx"`
Rx []string `json:"rx"`
}
type monitorData struct {
Times []string `json:"times"`
Load load `json:"load"`
Cpu cpu `json:"cpu"`
Mem mem `json:"mem"`
Swap swap `json:"swap"`
Net network `json:"net"`
}
var data monitorData
var bytesSent uint64
var bytesRecv uint64
var bytesSent2 uint64
var bytesRecv2 uint64
for _, net := range monitors[0].Info.Net {
if net.Name == "lo" {
continue
}
bytesSent += net.BytesSent
bytesRecv += net.BytesRecv
}
for i, monitor := range monitors {
// 跳过第一条数据,因为第一条数据的流量为 0
if i == 0 {
// MB
data.Mem.Total = fmt.Sprintf("%.2f", float64(monitor.Info.Mem.Total)/1024/1024)
data.Swap.Total = fmt.Sprintf("%.2f", float64(monitor.Info.Swap.Total)/1024/1024)
continue
}
for _, net := range monitor.Info.Net {
if net.Name == "lo" {
continue
}
bytesSent2 += net.BytesSent
bytesRecv2 += net.BytesRecv
}
data.Times = append(data.Times, monitor.CreatedAt.ToDateTimeString())
data.Load.Load1 = append(data.Load.Load1, monitor.Info.Load.Load1)
data.Load.Load5 = append(data.Load.Load5, monitor.Info.Load.Load5)
data.Load.Load15 = append(data.Load.Load15, monitor.Info.Load.Load15)
data.Cpu.Percent = append(data.Cpu.Percent, fmt.Sprintf("%.2f", monitor.Info.Percent[0]))
data.Mem.Available = append(data.Mem.Available, fmt.Sprintf("%.2f", float64(monitor.Info.Mem.Available)/1024/1024))
data.Mem.Used = append(data.Mem.Used, fmt.Sprintf("%.2f", float64(monitor.Info.Mem.Used)/1024/1024))
data.Swap.Used = append(data.Swap.Used, fmt.Sprintf("%.2f", float64(monitor.Info.Swap.Used)/1024/1024))
data.Swap.Free = append(data.Swap.Free, fmt.Sprintf("%.2f", float64(monitor.Info.Swap.Free)/1024/1024))
data.Net.Sent = append(data.Net.Sent, fmt.Sprintf("%.2f", float64(bytesSent2/1024/1024)))
data.Net.Recv = append(data.Net.Recv, fmt.Sprintf("%.2f", float64(bytesRecv2/1024/1024)))
// 监控频率为 1 分钟,所以这里除以 60 即可得到每秒的流量
data.Net.Tx = append(data.Net.Tx, fmt.Sprintf("%.2f", float64(bytesSent2-bytesSent)/60/1024/1024))
data.Net.Rx = append(data.Net.Rx, fmt.Sprintf("%.2f", float64(bytesRecv2-bytesRecv)/60/1024/1024))
bytesSent = bytesSent2
bytesRecv = bytesRecv2
bytesSent2 = 0
bytesRecv2 = 0
}
return Success(ctx, data)
}
+285
View File
@@ -0,0 +1,285 @@
package controllers
import (
"sync"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/app/models"
"panel/app/services"
)
type PluginController struct {
plugin services.Plugin
task services.Task
}
func NewPluginController() *PluginController {
return &PluginController{
plugin: services.NewPluginImpl(),
task: services.NewTaskImpl(),
}
}
// List 列出所有插件
func (r *PluginController) List(ctx http.Context) http.Response {
plugins := r.plugin.All()
installedPlugins, err := r.plugin.AllInstalled()
if err != nil {
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
var lock sync.RWMutex
installedPluginsMap := make(map[string]models.Plugin)
for _, p := range installedPlugins {
lock.Lock()
installedPluginsMap[p.Slug] = p
lock.Unlock()
}
type plugin struct {
Name string `json:"name"`
Description string `json:"description"`
Slug string `json:"slug"`
Version string `json:"version"`
Requires []string `json:"requires"`
Excludes []string `json:"excludes"`
Installed bool `json:"installed"`
InstalledVersion string `json:"installed_version"`
Show bool `json:"show"`
}
var pluginArr []plugin
for _, item := range plugins {
installed, installedVersion, show := false, "", false
if _, ok := installedPluginsMap[item.Slug]; ok {
installed = true
installedVersion = installedPluginsMap[item.Slug].Version
show = installedPluginsMap[item.Slug].Show
}
pluginArr = append(pluginArr, plugin{
Name: item.Name,
Description: item.Description,
Slug: item.Slug,
Version: item.Version,
Requires: item.Requires,
Excludes: item.Excludes,
Installed: installed,
InstalledVersion: installedVersion,
Show: show,
})
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(pluginArr) {
return Success(ctx, http.Json{
"total": 0,
"items": []plugin{},
})
}
if endIndex > len(pluginArr) {
endIndex = len(pluginArr)
}
pagedPlugins := pluginArr[startIndex:endIndex]
return Success(ctx, http.Json{
"total": len(pluginArr),
"items": pagedPlugins,
})
}
// Install 安装插件
func (r *PluginController) Install(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
plugin := r.plugin.GetBySlug(slug)
installedPlugin := r.plugin.GetInstalledBySlug(slug)
installedPlugins, err := r.plugin.AllInstalled()
if err != nil {
facades.Log().Error("[面板][PluginController] 获取已安装插件失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if installedPlugin.ID != 0 {
return Error(ctx, http.StatusBadRequest, "插件已安装")
}
var lock sync.RWMutex
pluginsMap := make(map[string]bool)
for _, p := range installedPlugins {
lock.Lock()
pluginsMap[p.Slug] = true
lock.Unlock()
}
for _, require := range plugin.Requires {
lock.RLock()
_, requireFound := pluginsMap[require]
lock.RUnlock()
if !requireFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 需要依赖 "+require+" 插件")
}
}
for _, exclude := range plugin.Excludes {
lock.RLock()
_, excludeFound := pluginsMap[exclude]
lock.RUnlock()
if excludeFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 不兼容 "+exclude+" 插件")
}
}
var task models.Task
task.Name = "安装插件 " + plugin.Name
task.Status = models.TaskStatusWaiting
task.Shell = plugin.Install + " >> /tmp/" + plugin.Slug + ".log 2>&1"
task.Log = "/tmp/" + plugin.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[面板][PluginController] 创建任务失败: " + err.Error())
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
r.task.Process(task.ID)
return Success(ctx, "任务已提交")
}
// Uninstall 卸载插件
func (r *PluginController) Uninstall(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
plugin := r.plugin.GetBySlug(slug)
installedPlugin := r.plugin.GetInstalledBySlug(slug)
installedPlugins, err := r.plugin.AllInstalled()
if err != nil {
facades.Log().Error("[面板][PluginController] 获取已安装插件失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if installedPlugin.ID == 0 {
return Error(ctx, http.StatusBadRequest, "插件未安装")
}
var lock sync.RWMutex
pluginsMap := make(map[string]bool)
for _, p := range installedPlugins {
lock.Lock()
pluginsMap[p.Slug] = true
lock.Unlock()
}
for _, require := range plugin.Requires {
lock.RLock()
_, requireFound := pluginsMap[require]
lock.RUnlock()
if !requireFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 需要依赖 "+require+" 插件")
}
}
for _, exclude := range plugin.Excludes {
lock.RLock()
_, excludeFound := pluginsMap[exclude]
lock.RUnlock()
if excludeFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 不兼容 "+exclude+" 插件")
}
}
var task models.Task
task.Name = "卸载插件 " + plugin.Name
task.Status = models.TaskStatusWaiting
task.Shell = plugin.Uninstall + " >> /tmp/" + plugin.Slug + ".log 2>&1"
task.Log = "/tmp/" + plugin.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[面板][PluginController] 创建任务失败: " + err.Error())
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
r.task.Process(task.ID)
return Success(ctx, "任务已提交")
}
// Update 更新插件
func (r *PluginController) Update(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
plugin := r.plugin.GetBySlug(slug)
installedPlugin := r.plugin.GetInstalledBySlug(slug)
installedPlugins, err := r.plugin.AllInstalled()
if err != nil {
facades.Log().Error("[面板][PluginController] 获取已安装插件失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if installedPlugin.ID == 0 {
return Error(ctx, http.StatusBadRequest, "插件未安装")
}
var lock sync.RWMutex
pluginsMap := make(map[string]bool)
for _, p := range installedPlugins {
lock.Lock()
pluginsMap[p.Slug] = true
lock.Unlock()
}
for _, require := range plugin.Requires {
lock.RLock()
_, requireFound := pluginsMap[require]
lock.RUnlock()
if !requireFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 需要依赖 "+require+" 插件")
}
}
for _, exclude := range plugin.Excludes {
lock.RLock()
_, excludeFound := pluginsMap[exclude]
lock.RUnlock()
if excludeFound {
return Error(ctx, http.StatusForbidden, "插件 "+slug+" 不兼容 "+exclude+" 插件")
}
}
var task models.Task
task.Name = "更新插件 " + plugin.Name
task.Status = models.TaskStatusWaiting
task.Shell = plugin.Update + " >> /tmp/" + plugin.Slug + ".log 2>&1"
task.Log = "/tmp/" + plugin.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[面板][PluginController] 创建任务失败: " + err.Error())
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
r.task.Process(task.ID)
return Success(ctx, "任务已提交")
}
// UpdateShow 更新插件首页显示状态
func (r *PluginController) UpdateShow(ctx http.Context) http.Response {
slug := ctx.Request().Input("slug")
show := ctx.Request().InputBool("show")
var plugin models.Plugin
if err := facades.Orm().Query().Where("slug", slug).First(&plugin); err != nil {
facades.Log().Error("[面板][PluginController] 查询插件失败: " + err.Error())
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if plugin.ID == 0 {
return Error(ctx, http.StatusBadRequest, "插件未安装")
}
plugin.Show = show
if err := facades.Orm().Query().Save(&plugin); err != nil {
facades.Log().Error("[面板][PluginController] 更新插件失败: " + err.Error())
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, "操作成功")
}
@@ -0,0 +1,451 @@
package fail2ban
import (
"regexp"
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Fail2banController struct {
website services.Website
}
func NewFail2banController() *Fail2banController {
return &Fail2banController{
website: services.NewWebsiteImpl(),
}
}
type Jail struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
LogPath string `json:"log_path"`
MaxRetry int `json:"max_retry"`
FindTime int `json:"find_time"`
BanTime int `json:"ban_time"`
}
// Status 获取运行状态
func (c *Fail2banController) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
status := tools.Exec("systemctl status fail2ban | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取服务运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *Fail2banController) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
tools.Exec("systemctl reload fail2ban")
status := tools.Exec("systemctl status fail2ban | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取服务运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *Fail2banController) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
tools.Exec("systemctl restart fail2ban")
status := tools.Exec("systemctl status fail2ban | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取服务运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动服务
func (c *Fail2banController) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
tools.Exec("systemctl start fail2ban")
status := tools.Exec("systemctl status fail2ban | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取服务运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止服务
func (c *Fail2banController) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
tools.Exec("systemctl stop fail2ban")
status := tools.Exec("systemctl status fail2ban | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取服务运行状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// List 所有 Fail2ban 规则
func (c *Fail2banController) List(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
raw := tools.Read("/etc/fail2ban/jail.local")
if len(raw) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "Fail2ban 规则为空")
}
jailList := regexp.MustCompile(`\[(.*?)]`).FindAllStringSubmatch(raw, -1)
if len(jailList) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "Fail2ban 规则为空")
}
var jails []Jail
for i, jail := range jailList {
if i == 0 {
continue
}
jailName := jail[1]
jailRaw := tools.Cut(raw, "# "+jailName+"-START", "# "+jailName+"-END")
if len(jailRaw) == 0 {
continue
}
jailEnabled := strings.Contains(jailRaw, "enabled = true")
jailLogPath := regexp.MustCompile(`logpath = (.*)`).FindStringSubmatch(jailRaw)
jailMaxRetry := regexp.MustCompile(`maxretry = (.*)`).FindStringSubmatch(jailRaw)
jailFindTime := regexp.MustCompile(`findtime = (.*)`).FindStringSubmatch(jailRaw)
jailBanTime := regexp.MustCompile(`bantime = (.*)`).FindStringSubmatch(jailRaw)
jails = append(jails, Jail{
Name: jailName,
Enabled: jailEnabled,
LogPath: jailLogPath[1],
MaxRetry: cast.ToInt(jailMaxRetry[1]),
FindTime: cast.ToInt(jailFindTime[1]),
BanTime: cast.ToInt(jailBanTime[1]),
})
}
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(jails) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []Jail{},
})
}
if endIndex > len(jails) {
endIndex = len(jails)
}
pagedJails := jails[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(jails),
"items": pagedJails,
})
}
// Add 添加 Fail2ban 规则
func (c *Fail2banController) Add(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required",
"type": "required|in:website,service",
"maxretry": "required",
"findtime": "required",
"bantime": "required",
"website_mode": "required_if:type,website",
"website_path": "required_if:type,website",
})
if err != nil {
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
jailName := ctx.Request().Input("name")
jailType := ctx.Request().Input("type")
jailMaxRetry := ctx.Request().Input("maxretry")
jailFindTime := ctx.Request().Input("findtime")
jailBanTime := ctx.Request().Input("bantime")
jailWebsiteMode := ctx.Request().Input("website_mode")
jailWebsitePath := ctx.Request().Input("website_path")
raw := tools.Read("/etc/fail2ban/jail.local")
if strings.Contains(raw, "["+jailName+"]") || (strings.Contains(raw, "["+jailName+"]"+"-cc") && jailWebsiteMode == "cc") || (strings.Contains(raw, "["+jailName+"]"+"-path") && jailWebsiteMode == "path") {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "规则已存在")
}
switch jailType {
case "website":
var website models.Website
err := facades.Orm().Query().Where("name", jailName).FirstOrFail(&website)
if err != nil {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "网站不存在")
}
config, err := c.website.GetConfig(int(website.ID))
if err != nil {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取网站配置失败")
}
var ports string
for _, port := range config.Ports {
if len(strings.Split(port, " ")) > 1 {
ports += strings.Split(port, " ")[0] + ","
} else {
ports += port + ","
}
}
rule := `
# ` + jailName + `-` + jailWebsiteMode + `-START
[` + jailName + `-` + jailWebsiteMode + `]
enabled = true
filter = haozi-` + jailName + `-` + jailWebsiteMode + `
port = ` + ports + `
maxretry = ` + jailMaxRetry + `
findtime = ` + jailFindTime + `
bantime = ` + jailBanTime + `
action = %(action_mwl)s
logpath = /www/wwwlogs/` + website.Name + `.log
# ` + jailName + `-` + jailWebsiteMode + `-END
`
raw += rule
tools.Write("/etc/fail2ban/jail.local", raw, 0644)
var filter string
if jailWebsiteMode == "cc" {
filter = `
[Definition]
failregex = ^<HOST>\s-.*HTTP/.*$
ignoreregex =
`
} else {
filter = `
[Definition]
failregex = ^<HOST>\s-.*\s` + jailWebsitePath + `.*HTTP/.*$
ignoreregex =
`
}
tools.Write("/etc/fail2ban/filter.d/haozi-"+jailName+"-"+jailWebsiteMode+".conf", filter, 0644)
case "service":
var logPath string
var filter string
var port string
switch jailName {
case "ssh":
if tools.IsDebian() {
logPath = "/var/log/auth.log"
} else {
logPath = "/var/log/secure"
}
filter = "sshd"
port = tools.Exec("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'")
case "mysql":
logPath = "/www/server/mysql/mysql-error.log"
filter = "mysqld-auth"
port = tools.Exec("cat /www/server/mysql/conf/my.cnf | grep 'port' | head -n 1 | awk '{print $3}'")
case "pure-ftpd":
logPath = "/var/log/messages"
filter = "pure-ftpd"
port = tools.Exec(`cat /www/server/pure-ftpd/etc/pure-ftpd.conf | grep "Bind" | awk '{print $2}' | awk -F "," '{print $2}'`)
default:
return controllers.Error(ctx, http.StatusUnprocessableEntity, "未知服务")
}
if len(port) == 0 {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "获取服务端口失败,请检查是否安装")
}
rule := `
# ` + jailName + `-START
[` + jailName + `]
enabled = true
filter = ` + filter + `
port = ` + port + `
maxretry = ` + jailMaxRetry + `
findtime = ` + jailFindTime + `
bantime = ` + jailBanTime + `
action = %(action_mwl)s
logpath = ` + logPath + `
# ` + jailName + `-END
`
raw += rule
tools.Write("/etc/fail2ban/jail.local", raw, 0644)
}
tools.Exec("fail2ban-client reload")
return controllers.Success(ctx, nil)
}
// Delete 删除规则
func (c *Fail2banController) Delete(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
jailName := ctx.Request().Input("name")
raw := tools.Read("/etc/fail2ban/jail.local")
if !strings.Contains(raw, "["+jailName+"]") {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "规则不存在")
}
rule := tools.Cut(raw, "# "+jailName+"-START", "# "+jailName+"-END")
raw = strings.Replace(raw, "\n# "+jailName+"-START"+rule+"# "+jailName+"-END", "", -1)
raw = strings.TrimSpace(raw)
tools.Write("/etc/fail2ban/jail.local", raw, 0644)
tools.Exec("fail2ban-client reload")
return controllers.Success(ctx, nil)
}
// BanList 获取封禁列表
func (c *Fail2banController) BanList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
name := ctx.Request().Query("name")
if len(name) == 0 {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "缺少参数")
}
currentlyBan := tools.Exec(`fail2ban-client status ` + name + ` | grep "Currently banned" | awk '{print $4}'`)
totalBan := tools.Exec(`fail2ban-client status ` + name + ` | grep "Total banned" | awk '{print $4}'`)
bannedIp := tools.Exec(`fail2ban-client status ` + name + ` | grep "Banned IP list" | awk -F ":" '{print $2}'`)
bannedIpList := strings.Split(bannedIp, " ")
var list []map[string]string
for _, ip := range bannedIpList {
if len(ip) > 0 {
list = append(list, map[string]string{
"name": name,
"ip": ip,
})
}
}
return controllers.Success(ctx, http.Json{
"currentlyBan": currentlyBan,
"totalBan": totalBan,
"bannedIpList": list,
})
}
// Unban 解封
func (c *Fail2banController) Unban(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
name := ctx.Request().Input("name")
ip := ctx.Request().Input("ip")
if len(name) == 0 || len(ip) == 0 {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "缺少参数")
}
tools.Exec("fail2ban-client set " + name + " unbanip " + ip)
return controllers.Success(ctx, nil)
}
// SetWhiteList 设置白名单
func (c *Fail2banController) SetWhiteList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
ip := ctx.Request().Input("ip")
if len(ip) == 0 {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "缺少参数")
}
raw := tools.Read("/etc/fail2ban/jail.local")
// 正则替换
reg := regexp.MustCompile(`ignoreip\s*=\s*.*\n`)
if reg.MatchString(raw) {
raw = reg.ReplaceAllString(raw, "ignoreip = "+ip+"\n")
} else {
return controllers.Error(ctx, http.StatusInternalServerError, "解析Fail2ban规则失败,Fail2ban可能已损坏")
}
tools.Write("/etc/fail2ban/jail.local", raw, 0644)
tools.Exec("fail2ban-client reload")
return controllers.Success(ctx, nil)
}
// GetWhiteList 获取白名单
func (c *Fail2banController) GetWhiteList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "fail2ban")
if check != nil {
return check
}
raw := tools.Read("/etc/fail2ban/jail.local")
reg := regexp.MustCompile(`ignoreip\s*=\s*(.*)\n`)
if reg.MatchString(raw) {
ignoreIp := reg.FindStringSubmatch(raw)[1]
return controllers.Success(ctx, ignoreIp)
} else {
return controllers.Error(ctx, http.StatusInternalServerError, "解析Fail2ban规则失败,Fail2ban可能已损坏")
}
}
@@ -0,0 +1,768 @@
package mysql57
import (
"database/sql"
"fmt"
"regexp"
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Mysql57Controller struct {
setting services.Setting
backup services.Backup
}
func NewMysql57Controller() *Mysql57Controller {
return &Mysql57Controller{
setting: services.NewSettingImpl(),
backup: services.NewBackupImpl(),
}
}
// Status 获取运行状态
func (c *Mysql57Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *Mysql57Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
tools.Exec("systemctl reload mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *Mysql57Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
tools.Exec("systemctl restart mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动服务
func (c *Mysql57Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
tools.Exec("systemctl start mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止服务
func (c *Mysql57Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
tools.Exec("systemctl stop mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// GetConfig 获取配置
func (c *Mysql57Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
// 获取配置
config := tools.Read("/www/server/mysql/conf/my.cnf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL配置失败")
}
return controllers.Success(ctx, config)
}
// SaveConfig 保存配置
func (c *Mysql57Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
}
if !tools.Write("/www/server/mysql/conf/my.cnf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "写入MySQL配置失败")
}
return c.Restart(ctx)
}
// Load 获取负载
func (c *Mysql57Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "MySQL 已停止运行")
}
raw := tools.Exec("/www/server/mysql/bin/mysqladmin -uroot -p" + rootPassword + " extended-status 2>&1")
if strings.Contains(raw, "Access denied for user") {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码错误")
}
if !strings.Contains(raw, "Uptime") {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL负载失败")
}
var data []map[string]string
expressions := []struct {
regex string
name string
}{
{`Uptime\s+\|\s+(\d+)\s+\|`, "运行时间"},
{`Queries\s+\|\s+(\d+)\s+\|`, "总查询次数"},
{`Connections\s+\|\s+(\d+)\s+\|`, "总连接次数"},
{`Com_commit\s+\|\s+(\d+)\s+\|`, "每秒事务"},
{`Com_rollback\s+\|\s+(\d+)\s+\|`, "每秒回滚"},
{`Bytes_sent\s+\|\s+(\d+)\s+\|`, "发送"},
{`Bytes_received\s+\|\s+(\d+)\s+\|`, "接收"},
{`Threads_connected\s+\|\s+(\d+)\s+\|`, "活动连接数"},
{`Max_used_connections\s+\|\s+(\d+)\s+\|`, "峰值连接数"},
{`Key_read_requests\s+\|\s+(\d+)\s+\|`, "索引命中率"},
{`Innodb_buffer_pool_reads\s+\|\s+(\d+)\s+\|`, "Innodb索引命中率"},
{`Created_tmp_disk_tables\s+\|\s+(\d+)\s+\|`, "创建临时表到磁盘"},
{`Open_tables\s+\|\s+(\d+)\s+\|`, "已打开的表"},
{`Select_full_join\s+\|\s+(\d+)\s+\|`, "没有使用索引的量"},
{`Select_full_range_join\s+\|\s+(\d+)\s+\|`, "没有索引的JOIN量"},
{`Select_range_check\s+\|\s+(\d+)\s+\|`, "没有索引的子查询量"},
{`Sort_merge_passes\s+\|\s+(\d+)\s+\|`, "排序后的合并次数"},
{`Table_locks_waited\s+\|\s+(\d+)\s+\|`, "锁表次数"},
}
for _, expression := range expressions {
re := regexp.MustCompile(expression.regex)
matches := re.FindStringSubmatch(raw)
if len(matches) > 1 {
d := make(map[string]string)
d = map[string]string{"name": expression.name, "value": matches[1]}
if expression.name == "发送" || expression.name == "接收" {
d["value"] = tools.FormatBytes(cast.ToFloat64(matches[1]))
}
data = append(data, d)
}
}
// 索引命中率
readRequests := cast.ToFloat64(data[9]["value"])
reads := cast.ToFloat64(data[10]["value"])
data[9]["value"] = fmt.Sprintf("%.2f%%", readRequests/(reads+readRequests)*100)
// Innodb 索引命中率
bufferPoolReads := cast.ToFloat64(data[11]["value"])
bufferPoolReadRequests := cast.ToFloat64(data[12]["value"])
data[10]["value"] = fmt.Sprintf("%.2f%%", bufferPoolReadRequests/(bufferPoolReads+bufferPoolReadRequests)*100)
return controllers.Success(ctx, data)
}
// ErrorLog 获取错误日志
func (c *Mysql57Controller) ErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/mysql/mysql-error.log"))
return controllers.Success(ctx, log)
}
// ClearErrorLog 清空错误日志
func (c *Mysql57Controller) ClearErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/mysql/mysql-error.log")
return controllers.Success(ctx, "清空错误日志成功")
}
// SlowLog 获取慢查询日志
func (c *Mysql57Controller) SlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/mysql/mysql-slow.log"))
return controllers.Success(ctx, log)
}
// ClearSlowLog 清空慢查询日志
func (c *Mysql57Controller) ClearSlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/mysql/mysql-slow.log")
return controllers.Success(ctx, "清空慢查询日志成功")
}
// GetRootPassword 获取root密码
func (c *Mysql57Controller) GetRootPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
}
return controllers.Success(ctx, rootPassword)
}
// SetRootPassword 设置root密码
func (c *Mysql57Controller) SetRootPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "MySQL 未运行")
}
rootPassword := ctx.Request().Input(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码不能为空")
}
oldRootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if oldRootPassword != rootPassword {
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + oldRootPassword + " -e \"ALTER USER 'root'@'localhost' IDENTIFIED BY '" + rootPassword + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + oldRootPassword + " -e \"FLUSH PRIVILEGES;\"")
err := c.setting.Set(models.SettingKeyMysqlRootPassword, rootPassword)
if err != nil {
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"ALTER USER 'root'@'localhost' IDENTIFIED BY '" + oldRootPassword + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Error(ctx, http.StatusInternalServerError, "设置root密码失败")
}
}
return controllers.Success(ctx, "设置root密码成功")
}
// DatabaseList 获取数据库列表
func (c *Mysql57Controller) DatabaseList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
type database struct {
Name string `json:"name"`
}
db, err := sql.Open("mysql", "root:"+rootPassword+"@unix(/tmp/mysql.sock)/")
if err != nil {
facades.Log().Error("[MySQL57] 连接数据库失败" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "连接数据库失败")
}
defer db.Close()
rows, err := db.Query("SHOW DATABASES")
if err != nil {
facades.Log().Error("[MySQL57] 获取数据库列表失败" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取数据库列表失败")
}
defer rows.Close()
var databases []database
for rows.Next() {
var d database
err := rows.Scan(&d.Name)
if err != nil {
continue
}
databases = append(databases, d)
}
if err := rows.Err(); err != nil {
facades.Log().Error("[MySQL57] 获取数据库列表失败" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取数据库列表失败")
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(databases) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []database{},
})
}
if endIndex > len(databases) {
endIndex = len(databases)
}
pagedDatabases := databases[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(databases),
"items": pagedDatabases,
})
}
// AddDatabase 添加数据库
func (c *Mysql57Controller) AddDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
database := ctx.Request().Input("database")
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"CREATE DATABASE IF NOT EXISTS " + database + " DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"CREATE USER '" + user + "'@'localhost' IDENTIFIED BY '" + password + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "添加数据库成功")
}
// DeleteDatabase 删除数据库
func (c *Mysql57Controller) DeleteDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
database := ctx.Request().Input("database")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"DROP DATABASE IF EXISTS " + database + ";\"")
return controllers.Success(ctx, "删除数据库成功")
}
// BackupList 获取备份列表
func (c *Mysql57Controller) BackupList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
backupList, err := c.backup.MysqlList()
if err != nil {
facades.Log().Error("[MySQL57] 获取备份列表失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
}
// UploadBackup 上传备份
func (c *Mysql57Controller) UploadBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
if !tools.Exists(backupPath) {
tools.Mkdir(backupPath, 0644)
}
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
return controllers.Success(ctx, "上传文件成功")
}
// CreateBackup 创建备份
func (c *Mysql57Controller) CreateBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
err = c.backup.MysqlBackup(database)
if err != nil {
facades.Log().Error("[MYSQL57] 创建备份失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "创建备份失败")
}
return controllers.Success(ctx, "备份成功")
}
// DeleteBackup 删除备份
func (c *Mysql57Controller) DeleteBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"backup": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
fileName := ctx.Request().Input("backup")
tools.Remove(backupPath + "/" + fileName)
return controllers.Success(ctx, "删除备份成功")
}
// RestoreBackup 还原备份
func (c *Mysql57Controller) RestoreBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"backup": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
err = c.backup.MysqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup"))
if err != nil {
facades.Log().Error("[MYSQL57] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
}
return controllers.Success(ctx, "还原成功")
}
// UserList 用户列表
func (c *Mysql57Controller) UserList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
type user struct {
User string `json:"user"`
Host string `json:"host"`
Grants []string `json:"grants"`
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
db, err := sql.Open("mysql", "root:"+rootPassword+"@unix(/tmp/mysql.sock)/")
if err != nil {
facades.Log().Error("[MYSQL57] 连接数据库失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "连接数据库失败")
}
defer db.Close()
rows, err := db.Query("SELECT user, host FROM mysql.user")
if err != nil {
facades.Log().Error("[MYSQL57] 查询数据库失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "查询数据库失败")
}
defer rows.Close()
var userGrants []user
for rows.Next() {
var u user
err := rows.Scan(&u.User, &u.Host)
if err != nil {
continue
}
// 查询用户权限
grantsRows, err := db.Query(fmt.Sprintf("SHOW GRANTS FOR '%s'@'%s'", u.User, u.Host))
if err != nil {
continue
}
defer grantsRows.Close()
for grantsRows.Next() {
var grant string
err := grantsRows.Scan(&grant)
if err != nil {
continue
}
u.Grants = append(u.Grants, grant)
}
if err := grantsRows.Err(); err != nil {
continue
}
userGrants = append(userGrants, u)
}
if err := rows.Err(); err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "获取用户列表失败")
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(userGrants) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []user{},
})
}
if endIndex > len(userGrants) {
endIndex = len(userGrants)
}
pagedUserGrants := userGrants[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(userGrants),
"items": pagedUserGrants,
})
}
// AddUser 添加用户
func (c *Mysql57Controller) AddUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
database := ctx.Request().Input("database")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"CREATE USER '" + user + "'@'localhost' IDENTIFIED BY '" + password + ";'\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "添加成功")
}
// DeleteUser 删除用户
func (c *Mysql57Controller) DeleteUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"DROP USER '" + user + "'@'localhost';\"")
return controllers.Success(ctx, "删除成功")
}
// SetUserPassword 设置用户密码
func (c *Mysql57Controller) SetUserPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"ALTER USER '" + user + "'@'localhost' IDENTIFIED BY '" + password + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "修改成功")
}
// SetUserPrivileges 设置用户权限
func (c *Mysql57Controller) SetUserPrivileges(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql57")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"database": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
database := ctx.Request().Input("database")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"REVOKE ALL PRIVILEGES ON *.* FROM '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "修改成功")
}
@@ -0,0 +1,768 @@
package mysql80
import (
"database/sql"
"fmt"
"regexp"
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Mysql80Controller struct {
setting services.Setting
backup services.Backup
}
func NewMysql80Controller() *Mysql80Controller {
return &Mysql80Controller{
setting: services.NewSettingImpl(),
backup: services.NewBackupImpl(),
}
}
// Status 获取运行状态
func (c *Mysql80Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *Mysql80Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
tools.Exec("systemctl reload mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *Mysql80Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
tools.Exec("systemctl restart mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动服务
func (c *Mysql80Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
tools.Exec("systemctl start mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止服务
func (c *Mysql80Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
tools.Exec("systemctl stop mysqld")
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// GetConfig 获取配置
func (c *Mysql80Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
// 获取配置
config := tools.Read("/www/server/mysql/conf/my.cnf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL配置失败")
}
return controllers.Success(ctx, config)
}
// SaveConfig 保存配置
func (c *Mysql80Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
}
if !tools.Write("/www/server/mysql/conf/my.cnf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "写入MySQL配置失败")
}
return c.Restart(ctx)
}
// Load 获取负载
func (c *Mysql80Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "MySQL 已停止运行")
}
raw := tools.Exec("/www/server/mysql/bin/mysqladmin -uroot -p" + rootPassword + " extended-status 2>&1")
if strings.Contains(raw, "Access denied for user") {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码错误")
}
if !strings.Contains(raw, "Uptime") {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL负载失败")
}
var data []map[string]string
expressions := []struct {
regex string
name string
}{
{`Uptime\s+\|\s+(\d+)\s+\|`, "运行时间"},
{`Queries\s+\|\s+(\d+)\s+\|`, "总查询次数"},
{`Connections\s+\|\s+(\d+)\s+\|`, "总连接次数"},
{`Com_commit\s+\|\s+(\d+)\s+\|`, "每秒事务"},
{`Com_rollback\s+\|\s+(\d+)\s+\|`, "每秒回滚"},
{`Bytes_sent\s+\|\s+(\d+)\s+\|`, "发送"},
{`Bytes_received\s+\|\s+(\d+)\s+\|`, "接收"},
{`Threads_connected\s+\|\s+(\d+)\s+\|`, "活动连接数"},
{`Max_used_connections\s+\|\s+(\d+)\s+\|`, "峰值连接数"},
{`Key_read_requests\s+\|\s+(\d+)\s+\|`, "索引命中率"},
{`Innodb_buffer_pool_reads\s+\|\s+(\d+)\s+\|`, "Innodb索引命中率"},
{`Created_tmp_disk_tables\s+\|\s+(\d+)\s+\|`, "创建临时表到磁盘"},
{`Open_tables\s+\|\s+(\d+)\s+\|`, "已打开的表"},
{`Select_full_join\s+\|\s+(\d+)\s+\|`, "没有使用索引的量"},
{`Select_full_range_join\s+\|\s+(\d+)\s+\|`, "没有索引的JOIN量"},
{`Select_range_check\s+\|\s+(\d+)\s+\|`, "没有索引的子查询量"},
{`Sort_merge_passes\s+\|\s+(\d+)\s+\|`, "排序后的合并次数"},
{`Table_locks_waited\s+\|\s+(\d+)\s+\|`, "锁表次数"},
}
for _, expression := range expressions {
re := regexp.MustCompile(expression.regex)
matches := re.FindStringSubmatch(raw)
if len(matches) > 1 {
d := make(map[string]string)
d = map[string]string{"name": expression.name, "value": matches[1]}
if expression.name == "发送" || expression.name == "接收" {
d["value"] = tools.FormatBytes(cast.ToFloat64(matches[1]))
}
data = append(data, d)
}
}
// 索引命中率
readRequests := cast.ToFloat64(data[9]["value"])
reads := cast.ToFloat64(data[10]["value"])
data[9]["value"] = fmt.Sprintf("%.2f%%", readRequests/(reads+readRequests)*100)
// Innodb 索引命中率
bufferPoolReads := cast.ToFloat64(data[11]["value"])
bufferPoolReadRequests := cast.ToFloat64(data[12]["value"])
data[10]["value"] = fmt.Sprintf("%.2f%%", bufferPoolReadRequests/(bufferPoolReads+bufferPoolReadRequests)*100)
return controllers.Success(ctx, data)
}
// ErrorLog 获取错误日志
func (c *Mysql80Controller) ErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/mysql/mysql-error.log"))
return controllers.Success(ctx, log)
}
// ClearErrorLog 清空错误日志
func (c *Mysql80Controller) ClearErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/mysql/mysql-error.log")
return controllers.Success(ctx, "清空错误日志成功")
}
// SlowLog 获取慢查询日志
func (c *Mysql80Controller) SlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/mysql/mysql-slow.log"))
return controllers.Success(ctx, log)
}
// ClearSlowLog 清空慢查询日志
func (c *Mysql80Controller) ClearSlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/mysql/mysql-slow.log")
return controllers.Success(ctx, "清空慢查询日志成功")
}
// GetRootPassword 获取root密码
func (c *Mysql80Controller) GetRootPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码为空")
}
return controllers.Success(ctx, rootPassword)
}
// SetRootPassword 设置root密码
func (c *Mysql80Controller) SetRootPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
status := tools.Exec("systemctl status mysqld | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取MySQL状态失败")
}
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "MySQL 未运行")
}
rootPassword := ctx.Request().Input(models.SettingKeyMysqlRootPassword)
if len(rootPassword) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "MySQL root密码不能为空")
}
oldRootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
if oldRootPassword != rootPassword {
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + oldRootPassword + " -e \"ALTER USER 'root'@'localhost' IDENTIFIED BY '" + rootPassword + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + oldRootPassword + " -e \"FLUSH PRIVILEGES;\"")
err := c.setting.Set(models.SettingKeyMysqlRootPassword, rootPassword)
if err != nil {
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"ALTER USER 'root'@'localhost' IDENTIFIED BY '" + oldRootPassword + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Error(ctx, http.StatusInternalServerError, "设置root密码失败")
}
}
return controllers.Success(ctx, "设置root密码成功")
}
// DatabaseList 获取数据库列表
func (c *Mysql80Controller) DatabaseList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
type database struct {
Name string `json:"name"`
}
db, err := sql.Open("mysql", "root:"+rootPassword+"@unix(/tmp/mysql.sock)/")
if err != nil {
facades.Log().Error("[MySQL80] 连接数据库失败" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "连接数据库失败")
}
defer db.Close()
rows, err := db.Query("SHOW DATABASES")
if err != nil {
facades.Log().Error("[MySQL80] 获取数据库列表失败" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取数据库列表失败")
}
defer rows.Close()
var databases []database
for rows.Next() {
var d database
err := rows.Scan(&d.Name)
if err != nil {
continue
}
databases = append(databases, d)
}
if err := rows.Err(); err != nil {
facades.Log().Error("[MySQL80] 获取数据库列表失败" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取数据库列表失败")
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(databases) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []database{},
})
}
if endIndex > len(databases) {
endIndex = len(databases)
}
pagedDatabases := databases[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(databases),
"items": pagedDatabases,
})
}
// AddDatabase 添加数据库
func (c *Mysql80Controller) AddDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
database := ctx.Request().Input("database")
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"CREATE DATABASE IF NOT EXISTS " + database + " DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"CREATE USER '" + user + "'@'localhost' IDENTIFIED BY '" + password + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "添加数据库成功")
}
// DeleteDatabase 删除数据库
func (c *Mysql80Controller) DeleteDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
database := ctx.Request().Input("database")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"DROP DATABASE IF EXISTS " + database + ";\"")
return controllers.Success(ctx, "删除数据库成功")
}
// BackupList 获取备份列表
func (c *Mysql80Controller) BackupList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
backupList, err := c.backup.MysqlList()
if err != nil {
facades.Log().Error("[MySQL80] 获取备份列表失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
}
// UploadBackup 上传备份
func (c *Mysql80Controller) UploadBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
if !tools.Exists(backupPath) {
tools.Mkdir(backupPath, 0644)
}
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
return controllers.Success(ctx, "上传文件成功")
}
// CreateBackup 创建备份
func (c *Mysql80Controller) CreateBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
err = c.backup.MysqlBackup(database)
if err != nil {
facades.Log().Error("[MYSQL80] 创建备份失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "创建备份失败")
}
return controllers.Success(ctx, "备份成功")
}
// DeleteBackup 删除备份
func (c *Mysql80Controller) DeleteBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"backup": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/mysql"
fileName := ctx.Request().Input("backup")
tools.Remove(backupPath + "/" + fileName)
return controllers.Success(ctx, "删除备份成功")
}
// RestoreBackup 还原备份
func (c *Mysql80Controller) RestoreBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"backup": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
err = c.backup.MysqlRestore(ctx.Request().Input("database"), ctx.Request().Input("backup"))
if err != nil {
facades.Log().Error("[MYSQL80] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
}
return controllers.Success(ctx, "还原成功")
}
// UserList 用户列表
func (c *Mysql80Controller) UserList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
type user struct {
User string `json:"user"`
Host string `json:"host"`
Grants []string `json:"grants"`
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
db, err := sql.Open("mysql", "root:"+rootPassword+"@unix(/tmp/mysql.sock)/")
if err != nil {
facades.Log().Error("[MYSQL80] 连接数据库失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "连接数据库失败")
}
defer db.Close()
rows, err := db.Query("SELECT user, host FROM mysql.user")
if err != nil {
facades.Log().Error("[MYSQL80] 查询数据库失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "查询数据库失败")
}
defer rows.Close()
var userGrants []user
for rows.Next() {
var u user
err := rows.Scan(&u.User, &u.Host)
if err != nil {
continue
}
// 查询用户权限
grantsRows, err := db.Query(fmt.Sprintf("SHOW GRANTS FOR '%s'@'%s'", u.User, u.Host))
if err != nil {
continue
}
defer grantsRows.Close()
for grantsRows.Next() {
var grant string
err := grantsRows.Scan(&grant)
if err != nil {
continue
}
u.Grants = append(u.Grants, grant)
}
if err := grantsRows.Err(); err != nil {
continue
}
userGrants = append(userGrants, u)
}
if err := rows.Err(); err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "获取用户列表失败")
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(userGrants) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []user{},
})
}
if endIndex > len(userGrants) {
endIndex = len(userGrants)
}
pagedUserGrants := userGrants[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(userGrants),
"items": pagedUserGrants,
})
}
// AddUser 添加用户
func (c *Mysql80Controller) AddUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
database := ctx.Request().Input("database")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"CREATE USER '" + user + "'@'localhost' IDENTIFIED BY '" + password + ";'\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "添加成功")
}
// DeleteUser 删除用户
func (c *Mysql80Controller) DeleteUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"DROP USER '" + user + "'@'localhost';\"")
return controllers.Success(ctx, "删除成功")
}
// SetUserPassword 设置用户密码
func (c *Mysql80Controller) SetUserPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"ALTER USER '" + user + "'@'localhost' IDENTIFIED BY '" + password + "';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "修改成功")
}
// SetUserPrivileges 设置用户权限
func (c *Mysql80Controller) SetUserPrivileges(ctx http.Context) http.Response {
check := controllers.Check(ctx, "mysql80")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"database": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
rootPassword := c.setting.Get(models.SettingKeyMysqlRootPassword)
user := ctx.Request().Input("user")
database := ctx.Request().Input("database")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"REVOKE ALL PRIVILEGES ON *.* FROM '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'@'localhost';\"")
tools.Exec("/www/server/mysql/bin/mysql -uroot -p" + rootPassword + " -e \"FLUSH PRIVILEGES;\"")
return controllers.Success(ctx, "修改成功")
}
@@ -0,0 +1,260 @@
package openresty
import (
"regexp"
"time"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/imroc/req/v3"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/pkg/tools"
)
type OpenRestyController struct {
// Dependent services
}
func NewOpenrestyController() *OpenRestyController {
return &OpenRestyController{
// Inject services
}
}
// Status 获取运行状态
func (c *OpenRestyController) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
status := tools.Exec("systemctl status openresty | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取OpenResty状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *OpenRestyController) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
tools.Exec("systemctl reload openresty")
status := tools.Exec("systemctl status openresty | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取OpenResty状态失败")
}
if status == "active" {
return controllers.Success(ctx, "重载OpenResty成功")
} else {
return controllers.Error(ctx, 1, "重载OpenResty失败: "+status)
}
}
// Start 启动OpenResty
func (c *OpenRestyController) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
tools.Exec("systemctl start openresty")
status := tools.Exec("systemctl status openresty | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取OpenResty状态失败")
}
if status == "active" {
return controllers.Success(ctx, "启动OpenResty成功")
} else {
return controllers.Error(ctx, 1, "启动OpenResty失败: "+status)
}
}
// Stop 停止OpenResty
func (c *OpenRestyController) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
tools.Exec("systemctl stop openresty")
status := tools.Exec("systemctl status openresty | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取OpenResty状态失败")
}
if status != "active" {
return controllers.Success(ctx, "停止OpenResty成功")
} else {
return controllers.Error(ctx, 1, "停止OpenResty失败: "+status)
}
}
// Restart 重启OpenResty
func (c *OpenRestyController) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
tools.Exec("systemctl restart openresty")
status := tools.Exec("systemctl status openresty | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取OpenResty状态失败")
}
if status == "active" {
return controllers.Success(ctx, "重启OpenResty成功")
} else {
return controllers.Error(ctx, 1, "重启OpenResty失败: "+status)
}
}
// GetConfig 获取配置
func (c *OpenRestyController) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
config := tools.Read("/www/server/openresty/conf/nginx.conf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取OpenResty配置失败")
}
return controllers.Success(ctx, config)
}
// SaveConfig 保存配置
func (c *OpenRestyController) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "配置不能为空")
}
if !tools.Write("/www/server/openresty/conf/nginx.conf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "保存OpenResty配置失败")
}
return c.Reload(ctx)
}
// ErrorLog 获取错误日志
func (c *OpenRestyController) ErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
if !tools.Exists("/www/wwwlogs/nginx_error.log") {
return controllers.Success(ctx, "")
}
out := tools.Exec("tail -n 100 /www/wwwlogs/nginx_error.log")
return controllers.Success(ctx, out)
}
// ClearErrorLog 清空错误日志
func (c *OpenRestyController) ClearErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
tools.Exec("echo '' > /www/wwwlogs/nginx_error.log")
return controllers.Success(ctx, "清空OpenResty错误日志成功")
}
// Load 获取负载
func (c *OpenRestyController) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "openresty")
if check != nil {
return check
}
client := req.C().SetTimeout(10 * time.Second)
resp, err := client.R().Get("http://127.0.0.1/nginx_status")
if err != nil || !resp.IsSuccessState() {
facades.Log().Error("[OpenResty] 获取OpenResty负载失败: " + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取OpenResty负载失败")
}
raw := resp.String()
type nginxStatus struct {
Name string `json:"name"`
Value string `json:"value"`
}
var data []nginxStatus
workers := tools.Exec("ps aux | grep nginx | grep 'worker process' | wc -l")
data = append(data, nginxStatus{
Name: "工作进程",
Value: workers,
})
out := tools.Exec("ps aux | grep nginx | grep 'worker process' | awk '{memsum+=$6};END {print memsum}'")
mem := tools.FormatBytes(cast.ToFloat64(out))
data = append(data, nginxStatus{
Name: "内存占用",
Value: mem,
})
match := regexp.MustCompile(`Active connections:\s+(\d+)`).FindStringSubmatch(raw)
if len(match) == 2 {
data = append(data, nginxStatus{
Name: "活跃连接数",
Value: match[1],
})
}
match = regexp.MustCompile(`server accepts handled requests\s+(\d+)\s+(\d+)\s+(\d+)`).FindStringSubmatch(raw)
if len(match) == 4 {
data = append(data, nginxStatus{
Name: "总连接次数",
Value: match[1],
})
data = append(data, nginxStatus{
Name: "总握手次数",
Value: match[2],
})
data = append(data, nginxStatus{
Name: "总请求次数",
Value: match[3],
})
}
match = regexp.MustCompile(`Reading:\s+(\d+)\s+Writing:\s+(\d+)\s+Waiting:\s+(\d+)`).FindStringSubmatch(raw)
if len(match) == 4 {
data = append(data, nginxStatus{
Name: "请求数",
Value: match[1],
})
data = append(data, nginxStatus{
Name: "响应数",
Value: match[2],
})
data = append(data, nginxStatus{
Name: "驻留进程",
Value: match[3],
})
}
return controllers.Success(ctx, data)
}
@@ -0,0 +1,372 @@
package php74
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/imroc/req/v3"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Php74Controller struct {
setting services.Setting
task services.Task
version string
}
func NewPhp74Controller() *Php74Controller {
return &Php74Controller{
setting: services.NewSettingImpl(),
task: services.NewTaskImpl(),
version: "74",
}
}
func (c *Php74Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
status := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php74Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl reload php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php74Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl start php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php74Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl stop php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php74Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl restart php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php74Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := tools.Read("/www/server/php/" + c.version + "/etc/php.ini")
return controllers.Success(ctx, config)
}
func (c *Php74Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := ctx.Request().Input("config")
tools.Write("/www/server/php/"+c.version+"/etc/php.ini", config, 0644)
return c.Reload(ctx)
}
func (c *Php74Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
client := req.C().SetTimeout(10 * time.Second)
resp, err := client.R().Get("http://127.0.0.1/phpfpm_status/" + c.version)
if err != nil || !resp.IsSuccessState() {
facades.Log().Error("获取PHP-" + c.version + "运行状态失败")
return controllers.Error(ctx, http.StatusInternalServerError, "[PHP-"+c.version+"] 获取运行状态失败")
}
raw := resp.String()
dataKeys := []string{"应用池", "工作模式", "启动时间", "接受连接", "监听队列", "最大监听队列", "监听队列长度", "空闲进程数量", "活动进程数量", "总进程数量", "最大活跃进程数量", "达到进程上限次数", "慢请求"}
regexKeys := []string{"pool", "process manager", "start time", "accepted conn", "listen queue", "max listen queue", "listen queue len", "idle processes", "active processes", "total processes", "max active processes", "max children reached", "slow requests"}
type Data struct {
Name string `json:"name"`
Value string `json:"value"`
}
data := make([]Data, len(dataKeys))
for i := range dataKeys {
data[i].Name = dataKeys[i]
r := regexp.MustCompile(fmt.Sprintf("%s:\\s+(.*)", regexKeys[i]))
match := r.FindStringSubmatch(raw)
if len(match) > 1 {
data[i].Value = strings.TrimSpace(match[1])
}
}
return controllers.Success(ctx, data)
}
func (c *Php74Controller) ErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/php-fpm.log"))
return controllers.Success(ctx, log)
}
func (c *Php74Controller) SlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/slow.log"))
return controllers.Success(ctx, log)
}
func (c *Php74Controller) ClearErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/php-fpm.log")
return controllers.Success(ctx, true)
}
func (c *Php74Controller) ClearSlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/slow.log")
return controllers.Success(ctx, true)
}
type Extension struct {
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
Installed bool `json:"installed"`
}
func (c *Php74Controller) GetExtensionList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
extensions := c.GetExtensions()
return controllers.Success(ctx, extensions)
}
func (c *Php74Controller) InstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
}
var task models.Task
task.Name = "安装PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' install ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建安装拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php74Controller) UninstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
}
var task models.Task
task.Name = "卸载PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' uninstall ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建卸载拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php74Controller) GetExtensions() []Extension {
var extensions []Extension
extensions = append(extensions, Extension{
Name: "OPcache",
Slug: "Zend OPcache",
Description: "OPcache 通过将 PHP 脚本预编译的字节码存储到共享内存中来提升 PHP 的性能,存储预编译字节码可以省去每次加载和解析 PHP 脚本的开销。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "PhpRedis",
Slug: "redis",
Description: "PhpRedis 是一个用C语言编写的PHP模块,用来连接并操作 Redis 数据库上的数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "ImageMagick",
Slug: "imagick",
Description: "ImageMagick 是一个免费的创建、编辑、合成图片的软件。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "Exif",
Slug: "exif",
Description: "通过 exif 扩展,你可以操作图像元数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "pdo_pgsql",
Slug: "pdo_pgsql",
Description: "(需先安装PostgreSQLpdo_pgsql 是一个驱动程序,它实现了 PHP 数据对象(PDO)接口以启用从 PHP 到 PostgreSQL 数据库的访问。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "ionCube",
Slug: "ionCube Loader",
Description: "ionCube 是一个专业级的PHP加密解密工具。",
Installed: false,
})
raw := tools.Exec("/www/server/php/" + c.version + "/bin/php -m")
rawExtensionList := strings.Split(raw, "\n")
for _, item := range rawExtensionList {
if !strings.Contains(item, "[") && item != "" {
for i := range extensions {
if extensions[i].Slug == item {
extensions[i].Installed = true
}
}
}
}
return extensions
}
@@ -0,0 +1,372 @@
package php80
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/imroc/req/v3"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Php80Controller struct {
setting services.Setting
task services.Task
version string
}
func NewPhp80Controller() *Php80Controller {
return &Php80Controller{
setting: services.NewSettingImpl(),
task: services.NewTaskImpl(),
version: "80",
}
}
func (c *Php80Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
status := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php80Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl reload php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php80Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl start php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php80Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl stop php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php80Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl restart php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php80Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := tools.Read("/www/server/php/" + c.version + "/etc/php.ini")
return controllers.Success(ctx, config)
}
func (c *Php80Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := ctx.Request().Input("config")
tools.Write("/www/server/php/"+c.version+"/etc/php.ini", config, 0644)
return c.Reload(ctx)
}
func (c *Php80Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
client := req.C().SetTimeout(10 * time.Second)
resp, err := client.R().Get("http://127.0.0.1/phpfpm_status/" + c.version)
if err != nil || !resp.IsSuccessState() {
facades.Log().Error("获取PHP-" + c.version + "运行状态失败")
return controllers.Error(ctx, http.StatusInternalServerError, "[PHP-"+c.version+"] 获取运行状态失败")
}
raw := resp.String()
dataKeys := []string{"应用池", "工作模式", "启动时间", "接受连接", "监听队列", "最大监听队列", "监听队列长度", "空闲进程数量", "活动进程数量", "总进程数量", "最大活跃进程数量", "达到进程上限次数", "慢请求"}
regexKeys := []string{"pool", "process manager", "start time", "accepted conn", "listen queue", "max listen queue", "listen queue len", "idle processes", "active processes", "total processes", "max active processes", "max children reached", "slow requests"}
type Data struct {
Name string `json:"name"`
Value string `json:"value"`
}
data := make([]Data, len(dataKeys))
for i := range dataKeys {
data[i].Name = dataKeys[i]
r := regexp.MustCompile(fmt.Sprintf("%s:\\s+(.*)", regexKeys[i]))
match := r.FindStringSubmatch(raw)
if len(match) > 1 {
data[i].Value = strings.TrimSpace(match[1])
}
}
return controllers.Success(ctx, data)
}
func (c *Php80Controller) ErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/php-fpm.log"))
return controllers.Success(ctx, log)
}
func (c *Php80Controller) SlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/slow.log"))
return controllers.Success(ctx, log)
}
func (c *Php80Controller) ClearErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/php-fpm.log")
return controllers.Success(ctx, true)
}
func (c *Php80Controller) ClearSlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/slow.log")
return controllers.Success(ctx, true)
}
type Extension struct {
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
Installed bool `json:"installed"`
}
func (c *Php80Controller) GetExtensionList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
extensions := c.GetExtensions()
return controllers.Success(ctx, extensions)
}
func (c *Php80Controller) InstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
}
var task models.Task
task.Name = "安装PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' install ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建安装拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php80Controller) UninstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
}
var task models.Task
task.Name = "卸载PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' uninstall ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建卸载拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php80Controller) GetExtensions() []Extension {
var extensions []Extension
extensions = append(extensions, Extension{
Name: "OPcache",
Slug: "Zend OPcache",
Description: "OPcache 通过将 PHP 脚本预编译的字节码存储到共享内存中来提升 PHP 的性能,存储预编译字节码可以省去每次加载和解析 PHP 脚本的开销。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "PhpRedis",
Slug: "redis",
Description: "PhpRedis 是一个用C语言编写的PHP模块,用来连接并操作 Redis 数据库上的数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "ImageMagick",
Slug: "imagick",
Description: "ImageMagick 是一个免费的创建、编辑、合成图片的软件。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "Exif",
Slug: "exif",
Description: "通过 exif 扩展,你可以操作图像元数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "pdo_pgsql",
Slug: "pdo_pgsql",
Description: "(需先安装PostgreSQLpdo_pgsql 是一个驱动程序,它实现了 PHP 数据对象(PDO)接口以启用从 PHP 到 PostgreSQL 数据库的访问。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "ionCube",
Slug: "ionCube Loader",
Description: "ionCube 是一个专业级的PHP加密解密工具。",
Installed: false,
})
raw := tools.Exec("/www/server/php/" + c.version + "/bin/php -m")
rawExtensionList := strings.Split(raw, "\n")
for _, item := range rawExtensionList {
if !strings.Contains(item, "[") && item != "" {
for i := range extensions {
if extensions[i].Slug == item {
extensions[i].Installed = true
}
}
}
}
return extensions
}
@@ -0,0 +1,372 @@
package php81
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/imroc/req/v3"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Php81Controller struct {
setting services.Setting
task services.Task
version string
}
func NewPhp81Controller() *Php81Controller {
return &Php81Controller{
setting: services.NewSettingImpl(),
task: services.NewTaskImpl(),
version: "81",
}
}
func (c *Php81Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
status := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php81Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl reload php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php81Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl start php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php81Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl stop php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php81Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl restart php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php81Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := tools.Read("/www/server/php/" + c.version + "/etc/php.ini")
return controllers.Success(ctx, config)
}
func (c *Php81Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := ctx.Request().Input("config")
tools.Write("/www/server/php/"+c.version+"/etc/php.ini", config, 0644)
return c.Reload(ctx)
}
func (c *Php81Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
client := req.C().SetTimeout(10 * time.Second)
resp, err := client.R().Get("http://127.0.0.1/phpfpm_status/" + c.version)
if err != nil || !resp.IsSuccessState() {
facades.Log().Error("获取PHP-" + c.version + "运行状态失败")
return controllers.Error(ctx, http.StatusInternalServerError, "[PHP-"+c.version+"] 获取运行状态失败")
}
raw := resp.String()
dataKeys := []string{"应用池", "工作模式", "启动时间", "接受连接", "监听队列", "最大监听队列", "监听队列长度", "空闲进程数量", "活动进程数量", "总进程数量", "最大活跃进程数量", "达到进程上限次数", "慢请求"}
regexKeys := []string{"pool", "process manager", "start time", "accepted conn", "listen queue", "max listen queue", "listen queue len", "idle processes", "active processes", "total processes", "max active processes", "max children reached", "slow requests"}
type Data struct {
Name string `json:"name"`
Value string `json:"value"`
}
data := make([]Data, len(dataKeys))
for i := range dataKeys {
data[i].Name = dataKeys[i]
r := regexp.MustCompile(fmt.Sprintf("%s:\\s+(.*)", regexKeys[i]))
match := r.FindStringSubmatch(raw)
if len(match) > 1 {
data[i].Value = strings.TrimSpace(match[1])
}
}
return controllers.Success(ctx, data)
}
func (c *Php81Controller) ErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/php-fpm.log"))
return controllers.Success(ctx, log)
}
func (c *Php81Controller) SlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/slow.log"))
return controllers.Success(ctx, log)
}
func (c *Php81Controller) ClearErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/php-fpm.log")
return controllers.Success(ctx, true)
}
func (c *Php81Controller) ClearSlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/slow.log")
return controllers.Success(ctx, true)
}
type Extension struct {
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
Installed bool `json:"installed"`
}
func (c *Php81Controller) GetExtensionList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
extensions := c.GetExtensions()
return controllers.Success(ctx, extensions)
}
func (c *Php81Controller) InstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
}
var task models.Task
task.Name = "安装PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' install ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建安装拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php81Controller) UninstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
}
var task models.Task
task.Name = "卸载PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' uninstall ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建卸载拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php81Controller) GetExtensions() []Extension {
var extensions []Extension
extensions = append(extensions, Extension{
Name: "OPcache",
Slug: "Zend OPcache",
Description: "OPcache 通过将 PHP 脚本预编译的字节码存储到共享内存中来提升 PHP 的性能,存储预编译字节码可以省去每次加载和解析 PHP 脚本的开销。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "PhpRedis",
Slug: "redis",
Description: "PhpRedis 是一个用C语言编写的PHP模块,用来连接并操作 Redis 数据库上的数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "ImageMagick",
Slug: "imagick",
Description: "ImageMagick 是一个免费的创建、编辑、合成图片的软件。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "Exif",
Slug: "exif",
Description: "通过 exif 扩展,你可以操作图像元数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "pdo_pgsql",
Slug: "pdo_pgsql",
Description: "(需先安装PostgreSQLpdo_pgsql 是一个驱动程序,它实现了 PHP 数据对象(PDO)接口以启用从 PHP 到 PostgreSQL 数据库的访问。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "ionCube",
Slug: "ionCube Loader",
Description: "ionCube 是一个专业级的PHP加密解密工具。",
Installed: false,
})
raw := tools.Exec("/www/server/php/" + c.version + "/bin/php -m")
rawExtensionList := strings.Split(raw, "\n")
for _, item := range rawExtensionList {
if !strings.Contains(item, "[") && item != "" {
for i := range extensions {
if extensions[i].Slug == item {
extensions[i].Installed = true
}
}
}
}
return extensions
}
@@ -0,0 +1,366 @@
package php82
import (
"fmt"
"regexp"
"strings"
"time"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/imroc/req/v3"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Php82Controller struct {
setting services.Setting
task services.Task
version string
}
func NewPhp82Controller() *Php82Controller {
return &Php82Controller{
setting: services.NewSettingImpl(),
task: services.NewTaskImpl(),
version: "82",
}
}
func (c *Php82Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
status := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php82Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl reload php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php82Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl start php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php82Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl stop php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php82Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("systemctl restart php-fpm-" + c.version)
out := tools.Exec("systemctl status php-fpm-" + c.version + " | grep Active | grep -v grep | awk '{print $2}'")
status := strings.TrimSpace(out)
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PHP-"+c.version+"运行状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
func (c *Php82Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := tools.Read("/www/server/php/" + c.version + "/etc/php.ini")
return controllers.Success(ctx, config)
}
func (c *Php82Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
config := ctx.Request().Input("config")
tools.Write("/www/server/php/"+c.version+"/etc/php.ini", config, 0644)
return c.Reload(ctx)
}
func (c *Php82Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
client := req.C().SetTimeout(10 * time.Second)
resp, err := client.R().Get("http://127.0.0.1/phpfpm_status/" + c.version)
if err != nil || !resp.IsSuccessState() {
facades.Log().Error("获取PHP-" + c.version + "运行状态失败")
return controllers.Error(ctx, http.StatusInternalServerError, "[PHP-"+c.version+"] 获取运行状态失败")
}
raw := resp.String()
dataKeys := []string{"应用池", "工作模式", "启动时间", "接受连接", "监听队列", "最大监听队列", "监听队列长度", "空闲进程数量", "活动进程数量", "总进程数量", "最大活跃进程数量", "达到进程上限次数", "慢请求"}
regexKeys := []string{"pool", "process manager", "start time", "accepted conn", "listen queue", "max listen queue", "listen queue len", "idle processes", "active processes", "total processes", "max active processes", "max children reached", "slow requests"}
type Data struct {
Name string `json:"name"`
Value string `json:"value"`
}
data := make([]Data, len(dataKeys))
for i := range dataKeys {
data[i].Name = dataKeys[i]
r := regexp.MustCompile(fmt.Sprintf("%s:\\s+(.*)", regexKeys[i]))
match := r.FindStringSubmatch(raw)
if len(match) > 1 {
data[i].Value = strings.TrimSpace(match[1])
}
}
return controllers.Success(ctx, data)
}
func (c *Php82Controller) ErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/php-fpm.log"))
return controllers.Success(ctx, log)
}
func (c *Php82Controller) SlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
log := tools.Escape(tools.Exec("tail -n 100 /www/server/php/" + c.version + "/var/log/slow.log"))
return controllers.Success(ctx, log)
}
func (c *Php82Controller) ClearErrorLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/php-fpm.log")
return controllers.Success(ctx, true)
}
func (c *Php82Controller) ClearSlowLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/php/" + c.version + "/var/log/slow.log")
return controllers.Success(ctx, true)
}
type Extension struct {
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
Installed bool `json:"installed"`
}
func (c *Php82Controller) GetExtensionList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
extensions := c.GetExtensions()
return controllers.Success(ctx, extensions)
}
func (c *Php82Controller) InstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展已安装")
}
var task models.Task
task.Name = "安装PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' install ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建安装拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php82Controller) UninstallExtension(ctx http.Context) http.Response {
check := controllers.Check(ctx, "php"+c.version)
if check != nil {
return check
}
slug := ctx.Request().Input("slug")
if len(slug) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "参数错误")
}
extensions := c.GetExtensions()
for _, item := range extensions {
if item.Slug == slug {
if !item.Installed {
return controllers.Error(ctx, http.StatusBadRequest, "扩展未安装")
}
var task models.Task
task.Name = "卸载PHP-" + c.version + "扩展-" + item.Name
task.Status = models.TaskStatusWaiting
task.Shell = `bash '/www/panel/scripts/php_extensions/` + item.Slug + `.sh' uninstall ` + c.version + ` >> /tmp/` + item.Slug + `.log 2>&1`
task.Log = "/tmp/" + item.Slug + ".log"
if err := facades.Orm().Query().Create(&task); err != nil {
facades.Log().Error("[PHP-" + c.version + "] 创建卸载拓展任务失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
c.task.Process(task.ID)
return controllers.Success(ctx, true)
}
}
return controllers.Error(ctx, http.StatusBadRequest, "扩展不存在")
}
func (c *Php82Controller) GetExtensions() []Extension {
var extensions []Extension
extensions = append(extensions, Extension{
Name: "OPcache",
Slug: "Zend OPcache",
Description: "OPcache 通过将 PHP 脚本预编译的字节码存储到共享内存中来提升 PHP 的性能,存储预编译字节码可以省去每次加载和解析 PHP 脚本的开销。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "PhpRedis",
Slug: "redis",
Description: "PhpRedis 是一个用C语言编写的PHP模块,用来连接并操作 Redis 数据库上的数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "ImageMagick",
Slug: "imagick",
Description: "ImageMagick 是一个免费的创建、编辑、合成图片的软件。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "Exif",
Slug: "exif",
Description: "通过 exif 扩展,你可以操作图像元数据。",
Installed: false,
})
extensions = append(extensions, Extension{
Name: "pdo_pgsql",
Slug: "pdo_pgsql",
Description: "(需先安装PostgreSQLpdo_pgsql 是一个驱动程序,它实现了 PHP 数据对象(PDO)接口以启用从 PHP 到 PostgreSQL 数据库的访问。",
Installed: false,
})
raw := tools.Exec("/www/server/php/" + c.version + "/bin/php -m")
rawExtensionList := strings.Split(raw, "\n")
for _, item := range rawExtensionList {
if !strings.Contains(item, "[") && item != "" {
for i := range extensions {
if extensions[i].Slug == item {
extensions[i].Installed = true
}
}
}
}
return extensions
}
@@ -0,0 +1,79 @@
package phpmyadmin
import (
"os"
"regexp"
"strings"
"github.com/goravel/framework/contracts/http"
"panel/app/http/controllers"
"panel/pkg/tools"
)
type PhpMyAdminController struct {
}
func NewPhpMyAdminController() *PhpMyAdminController {
return &PhpMyAdminController{}
}
func (c *PhpMyAdminController) Info(ctx http.Context) http.Response {
check := controllers.Check(ctx, "phpmyadmin")
if check != nil {
return check
}
files, err := os.ReadDir("/www/server/phpmyadmin")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 phpMyAdmin 目录")
}
var phpmyadmin string
for _, f := range files {
if strings.HasPrefix(f.Name(), "phpmyadmin_") {
phpmyadmin = f.Name()
}
}
if len(phpmyadmin) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 phpMyAdmin 目录")
}
conf := tools.Read("/www/server/vhost/phpmyadmin.conf")
match := regexp.MustCompile(`listen\s+(\d+);`).FindStringSubmatch(conf)
if len(match) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 phpMyAdmin 端口")
}
return controllers.Success(ctx, http.Json{
"phpmyadmin": phpmyadmin,
"port": match[1],
})
}
func (c *PhpMyAdminController) SetPort(ctx http.Context) http.Response {
check := controllers.Check(ctx, "phpmyadmin")
if check != nil {
return check
}
port := ctx.Request().Input("port")
if len(port) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "端口不能为空")
}
conf := tools.Read("/www/server/vhost/phpmyadmin.conf")
conf = regexp.MustCompile(`listen\s+(\d+);`).ReplaceAllString(conf, "listen "+port+";")
tools.Write("/www/server/vhost/phpmyadmin.conf", conf, 0644)
if tools.IsRHEL() {
tools.Exec("firewall-cmd --zone=public --add-port=" + port + "/tcp --permanent")
tools.Exec("firewall-cmd --reload")
} else {
tools.Exec("ufw allow " + port + "/tcp")
tools.Exec("ufw reload")
}
tools.Exec("systemctl reload openresty")
return controllers.Success(ctx, nil)
}
@@ -0,0 +1,612 @@
package postgresql15
import (
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/goravel/framework/support/carbon"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Postgresql15Controller struct {
setting services.Setting
backup services.Backup
}
type Info struct {
Name string `json:"name"`
Value string `json:"value"`
}
func NewPostgresql15Controller() *Postgresql15Controller {
return &Postgresql15Controller{
setting: services.NewSettingImpl(),
backup: services.NewBackupImpl(),
}
}
// Status 获取运行状态
func (c *Postgresql15Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *Postgresql15Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
tools.Exec("systemctl reload postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *Postgresql15Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
tools.Exec("systemctl restart postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动服务
func (c *Postgresql15Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
tools.Exec("systemctl start postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止服务
func (c *Postgresql15Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
tools.Exec("systemctl stop postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// GetConfig 获取配置
func (c *Postgresql15Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
// 获取配置
config := tools.Read("/www/server/postgresql/data/postgresql.conf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败")
}
return controllers.Success(ctx, config)
}
// GetUserConfig 获取用户配置
func (c *Postgresql15Controller) GetUserConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
// 获取配置
config := tools.Read("/www/server/postgresql/data/pg_hba.conf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败")
}
return controllers.Success(ctx, config)
}
// SaveConfig 保存配置
func (c *Postgresql15Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/postgresql.conf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败")
}
return c.Restart(ctx)
}
// SaveUserConfig 保存用户配置
func (c *Postgresql15Controller) SaveUserConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/pg_hba.conf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败")
}
return c.Restart(ctx)
}
// Load 获取负载
func (c *Postgresql15Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "PostgreSQL 已停止运行")
}
data := []Info{
{"启动时间", carbon.Parse(tools.Exec(`echo "select pg_postmaster_start_time();" | su - postgres -c "psql" | sed -n 3p | cut -d'.' -f1`)).ToDateTimeString()},
{"进程 PID", tools.Exec(`echo "select pg_backend_pid();" | su - postgres -c "psql" | sed -n 3p`)},
{"进程数", tools.Exec(`ps aux | grep postgres | grep -v grep | wc -l`)},
{"总连接数", tools.Exec(`echo "SELECT count(*) FROM pg_stat_activity WHERE NOT pid=pg_backend_pid();" | su - postgres -c "psql" | sed -n 3p`)},
{"空间占用", tools.Exec(`echo "select pg_size_pretty(pg_database_size('postgres'));" | su - postgres -c "psql" | sed -n 3p`)},
}
return controllers.Success(ctx, data)
}
// Log 获取日志
func (c *Postgresql15Controller) Log(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
log := tools.Exec("tail -n 100 /www/server/postgresql/logs/postgresql-" + carbon.Now().ToDateString() + ".log")
return controllers.Success(ctx, log)
}
// ClearLog 清空日志
func (c *Postgresql15Controller) ClearLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/postgresql/logs/postgresql-" + carbon.Now().ToDateString() + ".log")
return controllers.Success(ctx, nil)
}
// DatabaseList 获取数据库列表
func (c *Postgresql15Controller) DatabaseList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "PostgreSQL 已停止运行")
}
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
databases = databases[3 : len(databases)-1]
type database struct {
Name string `json:"name"`
Owner string `json:"owner"`
Encoding string `json:"encoding"`
}
var databaseList []database
for _, db := range databases {
parts := strings.Split(db, "|")
if len(parts) != 8 || len(strings.TrimSpace(parts[0])) == 0 {
continue
}
databaseList = append(databaseList, database{
Name: strings.TrimSpace(parts[0]),
Owner: strings.TrimSpace(parts[1]),
Encoding: strings.TrimSpace(parts[2]),
})
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(databaseList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []database{},
})
}
if endIndex > len(databaseList) {
endIndex = len(databaseList)
}
pagedDatabases := databaseList[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(databaseList),
"items": pagedDatabases,
})
}
// AddDatabase 添加数据库
func (c *Postgresql15Controller) AddDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec(`echo "CREATE DATABASE ` + database + `;" | su - postgres -c "psql"`)
tools.Exec(`echo "CREATE USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`)
tools.Exec(`echo "ALTER DATABASE ` + database + ` OWNER TO ` + user + `;" | su - postgres -c "psql"`)
tools.Exec(`echo "GRANT ALL PRIVILEGES ON DATABASE ` + database + ` TO ` + user + `;" | su - postgres -c "psql"`)
userConfig := "host " + database + " " + user + " 127.0.0.1/32 scram-sha-256"
tools.Exec(`echo "` + userConfig + `" >> /www/server/postgresql/data/pg_hba.conf`)
return c.Reload(ctx)
}
// DeleteDatabase 删除数据库
func (c *Postgresql15Controller) DeleteDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:postgres,template0,template1",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
tools.Exec(`echo "DROP DATABASE ` + database + `;" | su - postgres -c "psql"`)
return controllers.Success(ctx, nil)
}
// BackupList 获取备份列表
func (c *Postgresql15Controller) BackupList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
backupList, err := c.backup.PostgresqlList()
if err != nil {
facades.Log().Error("[PostgreSQL] 获取备份列表失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
}
// UploadBackup 上传备份
func (c *Postgresql15Controller) UploadBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
if !tools.Exists(backupPath) {
tools.Mkdir(backupPath, 0644)
}
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
return controllers.Success(ctx, nil)
}
// CreateBackup 创建备份
func (c *Postgresql15Controller) CreateBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
err = c.backup.PostgresqlBackup(database)
if err != nil {
facades.Log().Error("[PostgreSQL] 创建备份失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "创建备份失败")
}
return controllers.Success(ctx, nil)
}
// DeleteBackup 删除备份
func (c *Postgresql15Controller) DeleteBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
fileName := ctx.Request().Input("name")
tools.Remove(backupPath + "/" + fileName)
return controllers.Success(ctx, nil)
}
// RestoreBackup 还原备份
func (c *Postgresql15Controller) RestoreBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
err = c.backup.PostgresqlRestore(ctx.Request().Input("database"), ctx.Request().Input("name"))
if err != nil {
facades.Log().Error("[PostgreSQL] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
}
return controllers.Success(ctx, nil)
}
// UserList 用户列表
func (c *Postgresql15Controller) UserList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
type user struct {
User string `json:"user"`
Role string `json:"role"`
}
raw := tools.Exec(`echo "\du" | su - postgres -c "psql"`)
users := strings.Split(raw, "\n")
if len(users) < 4 {
return controllers.Error(ctx, http.StatusInternalServerError, "用户列表为空")
}
users = users[3:]
var userList []user
for _, u := range users {
userInfo := strings.Split(u, "|")
if len(userInfo) != 3 {
continue
}
userList = append(userList, user{
User: strings.TrimSpace(userInfo[0]),
Role: strings.TrimSpace(userInfo[1]),
})
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(userList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []user{},
})
}
if endIndex > len(userList) {
endIndex = len(userList)
}
pagedUsers := userList[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(userList),
"items": pagedUsers,
})
}
// AddUser 添加用户
func (c *Postgresql15Controller) AddUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
database := ctx.Request().Input("database")
tools.Exec(`echo "CREATE USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`)
tools.Exec(`echo "GRANT ALL PRIVILEGES ON DATABASE ` + database + ` TO ` + user + `;" | su - postgres -c "psql"`)
userConfig := "host " + database + " " + user + " 127.0.0.1/32 scram-sha-256"
tools.Exec(`echo "` + userConfig + `" >> /www/server/postgresql/data/pg_hba.conf`)
return c.Reload(ctx)
}
// DeleteUser 删除用户
func (c *Postgresql15Controller) DeleteUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
user := ctx.Request().Input("user")
tools.Exec(`echo "DROP USER ` + user + `;" | su - postgres -c "psql"`)
tools.Exec(`sed -i '/` + user + `/d' /www/server/postgresql/data/pg_hba.conf`)
return c.Reload(ctx)
}
// SetUserPassword 设置用户密码
func (c *Postgresql15Controller) SetUserPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql15")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec(`echo "ALTER USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`)
return controllers.Success(ctx, nil)
}
@@ -0,0 +1,612 @@
package postgresql16
import (
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/goravel/framework/support/carbon"
"panel/app/http/controllers"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type Postgresql16Controller struct {
setting services.Setting
backup services.Backup
}
type Info struct {
Name string `json:"name"`
Value string `json:"value"`
}
func NewPostgresql16Controller() *Postgresql16Controller {
return &Postgresql16Controller{
setting: services.NewSettingImpl(),
backup: services.NewBackupImpl(),
}
}
// Status 获取运行状态
func (c *Postgresql16Controller) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *Postgresql16Controller) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
tools.Exec("systemctl reload postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *Postgresql16Controller) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
tools.Exec("systemctl restart postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动服务
func (c *Postgresql16Controller) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
tools.Exec("systemctl start postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止服务
func (c *Postgresql16Controller) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
tools.Exec("systemctl stop postgresql")
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// GetConfig 获取配置
func (c *Postgresql16Controller) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
// 获取配置
config := tools.Read("/www/server/postgresql/data/postgresql.conf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败")
}
return controllers.Success(ctx, config)
}
// GetUserConfig 获取用户配置
func (c *Postgresql16Controller) GetUserConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
// 获取配置
config := tools.Read("/www/server/postgresql/data/pg_hba.conf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PostgreSQL配置失败")
}
return controllers.Success(ctx, config)
}
// SaveConfig 保存配置
func (c *Postgresql16Controller) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/postgresql.conf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败")
}
return c.Restart(ctx)
}
// SaveUserConfig 保存用户配置
func (c *Postgresql16Controller) SaveUserConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
}
if !tools.Write("/www/server/postgresql/data/pg_hba.conf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "写入PostgreSQL配置失败")
}
return c.Restart(ctx)
}
// Load 获取负载
func (c *Postgresql16Controller) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "PostgreSQL 已停止运行")
}
data := []Info{
{"启动时间", carbon.Parse(tools.Exec(`echo "select pg_postmaster_start_time();" | su - postgres -c "psql" | sed -n 3p | cut -d'.' -f1`)).ToDateTimeString()},
{"进程 PID", tools.Exec(`echo "select pg_backend_pid();" | su - postgres -c "psql" | sed -n 3p`)},
{"进程数", tools.Exec(`ps aux | grep postgres | grep -v grep | wc -l`)},
{"总连接数", tools.Exec(`echo "SELECT count(*) FROM pg_stat_activity WHERE NOT pid=pg_backend_pid();" | su - postgres -c "psql" | sed -n 3p`)},
{"空间占用", tools.Exec(`echo "select pg_size_pretty(pg_database_size('postgres'));" | su - postgres -c "psql" | sed -n 3p`)},
}
return controllers.Success(ctx, data)
}
// Log 获取日志
func (c *Postgresql16Controller) Log(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
log := tools.Exec("tail -n 100 /www/server/postgresql/logs/postgresql-" + carbon.Now().ToDateString() + ".log")
return controllers.Success(ctx, log)
}
// ClearLog 清空日志
func (c *Postgresql16Controller) ClearLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
tools.Exec("echo '' > /www/server/postgresql/logs/postgresql-" + carbon.Now().ToDateString() + ".log")
return controllers.Success(ctx, nil)
}
// DatabaseList 获取数据库列表
func (c *Postgresql16Controller) DatabaseList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
status := tools.Exec("systemctl status postgresql | grep Active | grep -v grep | awk '{print $2}'")
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "PostgreSQL 已停止运行")
}
raw := tools.Exec(`echo "\l" | su - postgres -c "psql"`)
databases := strings.Split(raw, "\n")
databases = databases[3 : len(databases)-1]
type database struct {
Name string `json:"name"`
Owner string `json:"owner"`
Encoding string `json:"encoding"`
}
var databaseList []database
for _, db := range databases {
parts := strings.Split(db, "|")
if len(parts) != 9 || len(strings.TrimSpace(parts[0])) == 0 {
continue
}
databaseList = append(databaseList, database{
Name: strings.TrimSpace(parts[0]),
Owner: strings.TrimSpace(parts[1]),
Encoding: strings.TrimSpace(parts[2]),
})
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(databaseList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []database{},
})
}
if endIndex > len(databaseList) {
endIndex = len(databaseList)
}
pagedDatabases := databaseList[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(databaseList),
"items": pagedDatabases,
})
}
// AddDatabase 添加数据库
func (c *Postgresql16Controller) AddDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec(`echo "CREATE DATABASE ` + database + `;" | su - postgres -c "psql"`)
tools.Exec(`echo "CREATE USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`)
tools.Exec(`echo "ALTER DATABASE ` + database + ` OWNER TO ` + user + `;" | su - postgres -c "psql"`)
tools.Exec(`echo "GRANT ALL PRIVILEGES ON DATABASE ` + database + ` TO ` + user + `;" | su - postgres -c "psql"`)
userConfig := "host " + database + " " + user + " 127.0.0.1/32 scram-sha-256"
tools.Exec(`echo "` + userConfig + `" >> /www/server/postgresql/data/pg_hba.conf`)
return c.Reload(ctx)
}
// DeleteDatabase 删除数据库
func (c *Postgresql16Controller) DeleteDatabase(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:postgres,template0,template1",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
tools.Exec(`echo "DROP DATABASE ` + database + `;" | su - postgres -c "psql"`)
return controllers.Success(ctx, nil)
}
// BackupList 获取备份列表
func (c *Postgresql16Controller) BackupList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
backupList, err := c.backup.PostgresqlList()
if err != nil {
facades.Log().Error("[PostgreSQL] 获取备份列表失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "获取备份列表失败")
}
return controllers.Success(ctx, backupList)
}
// UploadBackup 上传备份
func (c *Postgresql16Controller) UploadBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
file, err := ctx.Request().File("file")
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
if !tools.Exists(backupPath) {
tools.Mkdir(backupPath, 0644)
}
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "上传文件失败")
}
return controllers.Success(ctx, nil)
}
// CreateBackup 创建备份
func (c *Postgresql16Controller) CreateBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
database := ctx.Request().Input("database")
err = c.backup.PostgresqlBackup(database)
if err != nil {
facades.Log().Error("[PostgreSQL] 创建备份失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "创建备份失败")
}
return controllers.Success(ctx, nil)
}
// DeleteBackup 删除备份
func (c *Postgresql16Controller) DeleteBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/postgresql"
fileName := ctx.Request().Input("name")
tools.Remove(backupPath + "/" + fileName)
return controllers.Success(ctx, nil)
}
// RestoreBackup 还原备份
func (c *Postgresql16Controller) RestoreBackup(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|min_len:1|max_len:255",
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$|not_in:information_schema,mysql,performance_schema,sys",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
err = c.backup.PostgresqlRestore(ctx.Request().Input("database"), ctx.Request().Input("name"))
if err != nil {
facades.Log().Error("[PostgreSQL] 还原失败:" + err.Error())
return controllers.Error(ctx, http.StatusInternalServerError, "还原失败: "+err.Error())
}
return controllers.Success(ctx, nil)
}
// UserList 用户列表
func (c *Postgresql16Controller) UserList(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
type user struct {
User string `json:"user"`
Role string `json:"role"`
}
raw := tools.Exec(`echo "\du" | su - postgres -c "psql"`)
users := strings.Split(raw, "\n")
if len(users) < 4 {
return controllers.Error(ctx, http.StatusInternalServerError, "用户列表为空")
}
users = users[3:]
var userList []user
for _, u := range users {
userInfo := strings.Split(u, "|")
if len(userInfo) != 2 {
continue
}
userList = append(userList, user{
User: strings.TrimSpace(userInfo[0]),
Role: strings.TrimSpace(userInfo[1]),
})
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(userList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []user{},
})
}
if endIndex > len(userList) {
endIndex = len(userList)
}
pagedUsers := userList[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(userList),
"items": pagedUsers,
})
}
// AddUser 添加用户
func (c *Postgresql16Controller) AddUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"database": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
database := ctx.Request().Input("database")
tools.Exec(`echo "CREATE USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`)
tools.Exec(`echo "GRANT ALL PRIVILEGES ON DATABASE ` + database + ` TO ` + user + `;" | su - postgres -c "psql"`)
userConfig := "host " + database + " " + user + " 127.0.0.1/32 scram-sha-256"
tools.Exec(`echo "` + userConfig + `" >> /www/server/postgresql/data/pg_hba.conf`)
return c.Reload(ctx)
}
// DeleteUser 删除用户
func (c *Postgresql16Controller) DeleteUser(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
user := ctx.Request().Input("user")
tools.Exec(`echo "DROP USER ` + user + `;" | su - postgres -c "psql"`)
tools.Exec(`sed -i '/` + user + `/d' /www/server/postgresql/data/pg_hba.conf`)
return c.Reload(ctx)
}
// SetUserPassword 设置用户密码
func (c *Postgresql16Controller) SetUserPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "postgresql16")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"user": "required|min_len:1|max_len:255|regex:^[a-zA-Z][a-zA-Z0-9_]+$",
"password": "required|min_len:8|max_len:255",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
tools.Exec(`echo "ALTER USER ` + user + ` WITH PASSWORD '` + password + `';" | su - postgres -c "psql"`)
return controllers.Success(ctx, nil)
}
@@ -0,0 +1,308 @@
package pureftpd
import (
"regexp"
"strings"
"github.com/goravel/framework/contracts/http"
"panel/app/http/controllers"
"panel/pkg/tools"
)
type PureFtpdController struct {
}
type User struct {
Username string `json:"username"`
Path string `json:"path"`
}
func NewPureFtpdController() *PureFtpdController {
return &PureFtpdController{}
}
// Status 获取运行状态
func (c *PureFtpdController) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
status := tools.Exec("systemctl status pure-ftpd | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *PureFtpdController) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
tools.Exec("systemctl reload pure-ftpd")
status := tools.Exec("systemctl status pure-ftpd | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *PureFtpdController) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
tools.Exec("systemctl restart pure-ftpd")
status := tools.Exec("systemctl status pure-ftpd | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动服务
func (c *PureFtpdController) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
tools.Exec("systemctl start pure-ftpd")
status := tools.Exec("systemctl status pure-ftpd | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止服务
func (c *PureFtpdController) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
tools.Exec("systemctl stop pure-ftpd")
status := tools.Exec("systemctl status pure-ftpd | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// List 获取用户列表
func (c *PureFtpdController) List(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
listRaw := tools.Exec("pure-pw list")
if len(listRaw) == 0 {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []User{},
})
}
listArr := strings.Split(listRaw, "\n")
var users []User
for _, v := range listArr {
if len(v) == 0 {
continue
}
match := regexp.MustCompile(`(\S+)\s+(\S+)`).FindStringSubmatch(v)
users = append(users, User{
Username: match[1],
Path: strings.Replace(match[2], "/./", "/", 1),
})
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(users) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []User{},
})
}
if endIndex > len(users) {
endIndex = len(users)
}
pagedUsers := users[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(users),
"items": pagedUsers,
})
}
// Add 添加用户
func (c *PureFtpdController) Add(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"username": "required",
"password": "required|min_len:6",
"path": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
username := ctx.Request().Input("username")
password := ctx.Request().Input("password")
path := ctx.Request().Input("path")
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
if !tools.Exists(path) {
return controllers.Error(ctx, http.StatusBadRequest, "目录不存在")
}
tools.Chmod(path, 0755)
tools.Chown(path, "www", "www")
tools.Exec(`yes '` + password + `' | pure-pw useradd ` + username + ` -u www -g www -d ` + path)
tools.Exec("pure-pw mkdb")
return controllers.Success(ctx, nil)
}
// Delete 删除用户
func (c *PureFtpdController) Delete(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"username": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
username := ctx.Request().Input("username")
tools.Exec("pure-pw userdel " + username + " -m")
tools.Exec("pure-pw mkdb")
return controllers.Success(ctx, nil)
}
// ChangePassword 修改密码
func (c *PureFtpdController) ChangePassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"username": "required",
"password": "required|min_len:6",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
username := ctx.Request().Input("username")
password := ctx.Request().Input("password")
tools.Exec(`yes '` + password + `' | pure-pw passwd ` + username + ` -m`)
tools.Exec("pure-pw mkdb")
return controllers.Success(ctx, nil)
}
// GetPort 获取端口
func (c *PureFtpdController) GetPort(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
port := tools.Exec(`cat /www/server/pure-ftpd/etc/pure-ftpd.conf | grep "Bind" | awk '{print $2}' | awk -F "," '{print $2}'`)
if len(port) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取PureFtpd端口失败")
}
return controllers.Success(ctx, port)
}
// SetPort 设置端口
func (c *PureFtpdController) SetPort(ctx http.Context) http.Response {
check := controllers.Check(ctx, "pureftpd")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"port": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
port := ctx.Request().Input("port")
tools.Exec(`sed -i "s/Bind.*/Bind 0.0.0.0,` + port + `/g" /www/server/pure-ftpd/etc/pure-ftpd.conf`)
if tools.IsRHEL() {
tools.Exec("firewall-cmd --zone=public --add-port=" + port + "/tcp --permanent")
tools.Exec("firewall-cmd --reload")
} else {
tools.Exec("ufw allow " + port + "/tcp")
tools.Exec("ufw reload")
}
tools.Exec("systemctl restart pure-ftpd")
return controllers.Success(ctx, nil)
}
@@ -0,0 +1,202 @@
package redis
import (
"strings"
"github.com/goravel/framework/contracts/http"
"panel/app/http/controllers"
"panel/pkg/tools"
)
type RedisController struct {
}
type Info struct {
Name string `json:"name"`
Value string `json:"value"`
}
func NewRedisController() *RedisController {
return &RedisController{}
}
// Status 获取运行状态
func (c *RedisController) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
status := tools.Exec("systemctl status redis | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载配置
func (c *RedisController) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
tools.Exec("systemctl reload redis")
status := tools.Exec("systemctl status redis | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启服务
func (c *RedisController) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
tools.Exec("systemctl restart redis")
status := tools.Exec("systemctl status redis | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动服务
func (c *RedisController) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
tools.Exec("systemctl start redis")
status := tools.Exec("systemctl status redis | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败")
}
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止服务
func (c *RedisController) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
tools.Exec("systemctl stop redis")
status := tools.Exec("systemctl status redis | grep Active | grep -v grep | awk '{print $2}'")
if len(status) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis状态失败")
}
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// GetConfig 获取配置
func (c *RedisController) GetConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
// 获取配置
config := tools.Read("/www/server/redis/redis.conf")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis配置失败")
}
return controllers.Success(ctx, config)
}
// SaveConfig 保存配置
func (c *RedisController) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if len(config) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "配置不能为空")
}
if !tools.Write("/www/server/redis/redis.conf", config, 0644) {
return controllers.Error(ctx, http.StatusInternalServerError, "写入Redis配置失败")
}
return c.Restart(ctx)
}
// Load 获取负载
func (c *RedisController) Load(ctx http.Context) http.Response {
check := controllers.Check(ctx, "redis")
if check != nil {
return check
}
status := tools.Exec("systemctl status redis | grep Active | grep -v grep | awk '{print $2}'")
if status != "active" {
return controllers.Error(ctx, http.StatusInternalServerError, "Redis 已停止运行")
}
raw := tools.Exec("redis-cli info")
if len(raw) == 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "获取Redis负载失败")
}
infoLines := strings.Split(raw, "\n")
dataRaw := make(map[string]string)
for _, item := range infoLines {
parts := strings.Split(item, ":")
if len(parts) == 2 {
dataRaw[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
}
data := []Info{
{"TCP 端口", dataRaw["tcp_port"]},
{"已运行天数", dataRaw["uptime_in_days"]},
{"连接的客户端数", dataRaw["connected_clients"]},
{"已分配的内存总量", dataRaw["used_memory_human"]},
{"占用内存总量", dataRaw["used_memory_rss_human"]},
{"占用内存峰值", dataRaw["used_memory_peak_human"]},
{"内存碎片比率", dataRaw["mem_fragmentation_ratio"]},
{"运行以来连接过的客户端的总数", dataRaw["total_connections_received"]},
{"运行以来执行过的命令的总数", dataRaw["total_commands_processed"]},
{"每秒执行的命令数", dataRaw["instantaneous_ops_per_sec"]},
{"查找数据库键成功次数", dataRaw["keyspace_hits"]},
{"查找数据库键失败次数", dataRaw["keyspace_misses"]},
{"最近一次 fork() 操作耗费的毫秒数", dataRaw["latest_fork_usec"]},
}
return controllers.Success(ctx, data)
}
@@ -0,0 +1,207 @@
package s3fs
import (
"strings"
"github.com/bytedance/sonic"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/support/carbon"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/app/services"
"panel/pkg/tools"
)
type S3fsController struct {
setting services.Setting
}
type s3fs struct {
ID int64 `json:"id"`
Path string `json:"path"`
Bucket string `json:"bucket"`
Url string `json:"url"`
}
func NewS3fsController() *S3fsController {
return &S3fsController{
setting: services.NewSettingImpl(),
}
}
// List 所有 S3fs 挂载
func (c *S3fsController) List(ctx http.Context) http.Response {
check := controllers.Check(ctx, "s3fs")
if check != nil {
return check
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
var s3fsList []s3fs
err := sonic.UnmarshalString(c.setting.Get("s3fs", "[]"), &s3fsList)
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, "获取 S3fs 挂载失败")
}
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(s3fsList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []s3fs{},
})
}
if endIndex > len(s3fsList) {
endIndex = len(s3fsList)
}
pagedS3fsList := s3fsList[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(s3fsList),
"items": pagedS3fsList,
})
}
// Add 添加 S3fs 挂载
func (c *S3fsController) Add(ctx http.Context) http.Response {
check := controllers.Check(ctx, "s3fs")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"ak": "required|regex:^[a-zA-Z0-9]*$",
"sk": "required|regex:^[a-zA-Z0-9]*$",
"bucket": "required|regex:^[a-zA-Z0-9_-]*$",
"url": "required|full_url",
"path": "required|regex:^/[a-zA-Z0-9_-]+$",
})
if err != nil {
return controllers.Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusUnprocessableEntity, validator.Errors().One())
}
ak := ctx.Request().Input("ak")
sk := ctx.Request().Input("sk")
path := ctx.Request().Input("path")
bucket := ctx.Request().Input("bucket")
url := ctx.Request().Input("url")
// 检查下地域节点中是否包含bucket,如果包含了,肯定是错误的
if strings.Contains(url, bucket) {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "地域节点不能包含 Bucket 名称")
}
// 检查挂载目录是否存在且为空
if !tools.Exists(path) {
tools.Mkdir(path, 0755)
}
if !tools.Empty(path) {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "挂载目录必须为空")
}
var s3fsList []s3fs
err = sonic.UnmarshalString(c.setting.Get("s3fs", "[]"), &s3fsList)
if err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败")
}
for _, s := range s3fsList {
if s.Path == path {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "路径已存在")
}
}
id := carbon.Now().TimestampMilli()
password := ak + ":" + sk
tools.Write("/etc/passwd-s3fs-"+cast.ToString(id), password, 0600)
tools.Exec(`echo 's3fs#` + bucket + ` ` + path + ` fuse _netdev,allow_other,nonempty,url=` + url + `,passwd_file=/etc/passwd-s3fs-` + cast.ToString(id) + ` 0 0' >> /etc/fstab`)
mountCheck := tools.Exec("mount -a 2>&1")
if len(mountCheck) != 0 {
tools.Exec(`sed -i 's@^s3fs#` + bucket + `\s` + path + `.*$@@g' /etc/fstab`)
return controllers.Error(ctx, http.StatusInternalServerError, "检测到/etc/fstab有误: "+mountCheck)
}
dfCheck := tools.Exec("df -h | grep " + path + " 2>&1")
if len(dfCheck) == 0 {
tools.Exec(`sed -i 's@^s3fs#` + bucket + `\s` + path + `.*$@@g' /etc/fstab`)
return controllers.Error(ctx, http.StatusInternalServerError, "挂载失败,请检查配置是否正确")
}
s3fsList = append(s3fsList, s3fs{
ID: id,
Path: path,
Bucket: bucket,
Url: url,
})
json, err := sonic.MarshalString(s3fsList)
if err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "添加 S3fs 挂载失败")
}
err = c.setting.Set("s3fs", json)
if err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "添加 S3fs 挂载失败")
}
return controllers.Success(ctx, nil)
}
// Delete 删除 S3fs 挂载
func (c *S3fsController) Delete(ctx http.Context) http.Response {
check := controllers.Check(ctx, "s3fs")
if check != nil {
return check
}
id := ctx.Request().Input("id")
if len(id) == 0 {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "挂载ID不能为空")
}
var s3fsList []s3fs
err := sonic.UnmarshalString(c.setting.Get("s3fs", "[]"), &s3fsList)
if err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "获取 S3fs 挂载失败")
}
var mount s3fs
for _, s := range s3fsList {
if cast.ToString(s.ID) == id {
mount = s
break
}
}
if mount.ID == 0 {
return controllers.Error(ctx, http.StatusUnprocessableEntity, "挂载ID不存在")
}
tools.Exec(`fusermount -u '` + mount.Path + `' 2>&1`)
tools.Exec(`umount '` + mount.Path + `' 2>&1`)
tools.Exec(`sed -i 's@^s3fs#` + mount.Bucket + `\s` + mount.Path + `.*$@@g' /etc/fstab`)
mountCheck := tools.Exec("mount -a 2>&1")
if len(mountCheck) != 0 {
return controllers.Error(ctx, http.StatusInternalServerError, "检测到/etc/fstab有误: "+mountCheck)
}
tools.Remove("/etc/passwd-s3fs-" + cast.ToString(mount.ID))
var newS3fsList []s3fs
for _, s := range s3fsList {
if s.ID != mount.ID {
newS3fsList = append(newS3fsList, s)
}
}
json, err := sonic.MarshalString(newS3fsList)
if err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "删除 S3fs 挂载失败")
}
err = c.setting.Set("s3fs", json)
if err != nil {
return controllers.Error(ctx, http.StatusInternalServerError, "删除 S3fs 挂载失败")
}
return controllers.Success(ctx, nil)
}
@@ -0,0 +1,405 @@
package supervisor
import (
"strconv"
"strings"
"github.com/goravel/framework/contracts/http"
"panel/pkg/tools"
"panel/app/http/controllers"
)
type SupervisorController struct {
ServiceName string
}
func NewSupervisorController() *SupervisorController {
var serviceName string
if tools.IsRHEL() {
serviceName = "supervisord"
} else {
serviceName = "supervisor"
}
return &SupervisorController{
ServiceName: serviceName,
}
}
// Status 状态
func (c *SupervisorController) Status(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
status := tools.Exec(`systemctl status ` + c.ServiceName + ` | grep Active | grep -v grep | awk '{print $2}'`)
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Start 启动
func (c *SupervisorController) Start(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
tools.Exec(`systemctl start ` + c.ServiceName)
status := tools.Exec(`systemctl status ` + c.ServiceName + ` | grep Active | grep -v grep | awk '{print $2}'`)
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Stop 停止
func (c *SupervisorController) Stop(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
tools.Exec(`systemctl stop ` + c.ServiceName)
status := tools.Exec(`systemctl status ` + c.ServiceName + ` | grep Active | grep -v grep | awk '{print $2}'`)
if status != "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Restart 重启
func (c *SupervisorController) Restart(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
tools.Exec(`systemctl restart ` + c.ServiceName)
status := tools.Exec(`systemctl status ` + c.ServiceName + ` | grep Active | grep -v grep | awk '{print $2}'`)
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Reload 重载
func (c *SupervisorController) Reload(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
tools.Exec(`systemctl reload ` + c.ServiceName)
status := tools.Exec(`systemctl status ` + c.ServiceName + ` | grep Active | grep -v grep | awk '{print $2}'`)
if status == "active" {
return controllers.Success(ctx, true)
} else {
return controllers.Success(ctx, false)
}
}
// Log 日志
func (c *SupervisorController) Log(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
log := tools.Exec(`tail -n 200 /var/log/supervisor/supervisord.log`)
return controllers.Success(ctx, log)
}
// ClearLog 清空日志
func (c *SupervisorController) ClearLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
tools.Exec(`echo "" > /var/log/supervisor/supervisord.log`)
return controllers.Success(ctx, nil)
}
// Config 获取配置
func (c *SupervisorController) Config(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
var config string
if tools.IsRHEL() {
config = tools.Read(`/etc/supervisord.conf`)
} else {
config = tools.Read(`/etc/supervisor/supervisord.conf`)
}
return controllers.Success(ctx, config)
}
// SaveConfig 保存配置
func (c *SupervisorController) SaveConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
config := ctx.Request().Input("config")
if tools.IsRHEL() {
tools.Write(`/etc/supervisord.conf`, config, 0644)
} else {
tools.Write(`/etc/supervisor/supervisord.conf`, config, 0644)
}
return c.Restart(ctx)
}
// Processes 进程列表
func (c *SupervisorController) Processes(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
type process struct {
Name string `json:"name"`
Status string `json:"status"`
Pid string `json:"pid"`
Uptime string `json:"uptime"`
}
out := tools.Exec(`supervisorctl status | awk '{print $1}'`)
var processList []process
for _, line := range strings.Split(out, "\n") {
if len(line) == 0 {
continue
}
var p process
p.Name = line
p.Status = tools.Exec(`supervisorctl status ` + line + ` | awk '{print $2}'`)
if p.Status == "RUNNING" {
p.Pid = strings.ReplaceAll(tools.Exec(`supervisorctl status `+line+` | awk '{print $4}'`), ",", "")
p.Uptime = tools.Exec(`supervisorctl status ` + line + ` | awk '{print $6}'`)
} else {
p.Pid = "-"
p.Uptime = "-"
}
processList = append(processList, p)
}
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(processList) {
return controllers.Success(ctx, http.Json{
"total": 0,
"items": []process{},
})
}
if endIndex > len(processList) {
endIndex = len(processList)
}
pagedProcessList := processList[startIndex:endIndex]
return controllers.Success(ctx, http.Json{
"total": len(processList),
"items": pagedProcessList,
})
}
// StartProcess 启动进程
func (c *SupervisorController) StartProcess(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Input("process")
tools.Exec(`supervisorctl start ` + process)
return controllers.Success(ctx, nil)
}
// StopProcess 停止进程
func (c *SupervisorController) StopProcess(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Input("process")
tools.Exec(`supervisorctl stop ` + process)
return controllers.Success(ctx, nil)
}
// RestartProcess 重启进程
func (c *SupervisorController) RestartProcess(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Input("process")
tools.Exec(`supervisorctl restart ` + process)
return controllers.Success(ctx, nil)
}
// ProcessLog 进程日志
func (c *SupervisorController) ProcessLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Input("process")
var logPath string
if tools.IsRHEL() {
logPath = tools.Exec(`cat '/etc/supervisord.d/` + process + `.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`)
} else {
logPath = tools.Exec(`cat '/etc/supervisor/conf.d/` + process + `.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`)
}
log := tools.Exec(`tail -n 200 ` + logPath)
return controllers.Success(ctx, log)
}
// ClearProcessLog 清空进程日志
func (c *SupervisorController) ClearProcessLog(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Input("process")
var logPath string
if tools.IsRHEL() {
logPath = tools.Exec(`cat '/etc/supervisord.d/` + process + `.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`)
} else {
logPath = tools.Exec(`cat '/etc/supervisor/conf.d/` + process + `.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`)
}
tools.Exec(`echo "" > ` + logPath)
return controllers.Success(ctx, nil)
}
// ProcessConfig 获取进程配置
func (c *SupervisorController) ProcessConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Query("process")
var config string
if tools.IsRHEL() {
config = tools.Read(`/etc/supervisord.d/` + process + `.conf`)
} else {
config = tools.Read(`/etc/supervisor/conf.d/` + process + `.conf`)
}
return controllers.Success(ctx, config)
}
// SaveProcessConfig 保存进程配置
func (c *SupervisorController) SaveProcessConfig(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Input("process")
config := ctx.Request().Input("config")
if tools.IsRHEL() {
tools.Write(`/etc/supervisord.d/`+process+`.conf`, config, 0644)
} else {
tools.Write(`/etc/supervisor/conf.d/`+process+`.conf`, config, 0644)
}
tools.Exec(`supervisorctl reread`)
tools.Exec(`supervisorctl update`)
tools.Exec(`supervisorctl start ` + process)
return controllers.Success(ctx, nil)
}
// AddProcess 添加进程
func (c *SupervisorController) AddProcess(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|alpha_dash",
"user": "required|alpha_dash",
"path": "required",
"command": "required",
"num": "required",
})
if err != nil {
return controllers.Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return controllers.Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
name := ctx.Request().Input("name")
user := ctx.Request().Input("user")
path := ctx.Request().Input("path")
command := ctx.Request().Input("command")
num := ctx.Request().InputInt("num", 1)
config := `[program:` + name + `]
command=` + command + `
process_name=%(program_name)s
directory=` + path + `
autostart=true
autorestart=true
user=` + user + `
numprocs=` + strconv.Itoa(num) + `
redirect_stderr=true
stdout_logfile=/var/log/supervisor/` + name + `.log
stdout_logfile_maxbytes=2MB
`
if tools.IsRHEL() {
tools.Write(`/etc/supervisord.d/`+name+`.conf`, config, 0644)
} else {
tools.Write(`/etc/supervisor/conf.d/`+name+`.conf`, config, 0644)
}
tools.Exec(`supervisorctl reread`)
tools.Exec(`supervisorctl update`)
tools.Exec(`supervisorctl start ` + name)
return controllers.Success(ctx, nil)
}
// DeleteProcess 删除进程
func (c *SupervisorController) DeleteProcess(ctx http.Context) http.Response {
check := controllers.Check(ctx, "supervisor")
if check != nil {
return check
}
process := ctx.Request().Input("process")
tools.Exec(`supervisorctl stop ` + process)
var logPath string
if tools.IsRHEL() {
logPath = tools.Exec(`cat '/etc/supervisord.d/` + process + `.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`)
tools.Remove(`/etc/supervisord.d/` + process + `.conf`)
} else {
logPath = tools.Exec(`cat '/etc/supervisor/conf.d/` + process + `.conf' | grep stdout_logfile= | awk -F "=" '{print $2}'`)
tools.Remove(`/etc/supervisor/conf.d/` + process + `.conf`)
}
tools.Remove(logPath)
tools.Exec(`supervisorctl reread`)
tools.Exec(`supervisorctl update`)
return controllers.Success(ctx, nil)
}
@@ -0,0 +1,217 @@
package toolbox
import (
"regexp"
"strconv"
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/spf13/cast"
"panel/app/http/controllers"
"panel/pkg/tools"
)
type ToolBoxController struct {
}
func NewToolBoxController() *ToolBoxController {
return &ToolBoxController{}
}
// GetDNS 获取 DNS 信息
func (c *ToolBoxController) GetDNS(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
raw := tools.Read("/etc/resolv.conf")
match := regexp.MustCompile(`nameserver\s+(\S+)`).FindAllStringSubmatch(raw, -1)
if len(match) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到 DNS 信息")
}
var dns []string
for _, m := range match {
dns = append(dns, m[1])
}
return controllers.Success(ctx, dns)
}
// SetDNS 设置 DNS 信息
func (c *ToolBoxController) SetDNS(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
dns1 := ctx.Request().Input("dns1")
dns2 := ctx.Request().Input("dns2")
if len(dns1) == 0 || len(dns2) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "DNS 信息不能为空")
}
var dns string
dns += "nameserver " + dns1 + "\n"
dns += "nameserver " + dns2 + "\n"
tools.Write("/etc/resolv.conf", dns, 0644)
return controllers.Success(ctx, nil)
}
// GetSWAP 获取 SWAP 信息
func (c *ToolBoxController) GetSWAP(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
var total, size, used, free string
if tools.Exists("/www/swap") {
s, _ := tools.FileSize("/www/swap")
size = strconv.Itoa(int(s / 1024 / 1024))
total = tools.FormatBytes(float64(s))
} else {
size = "0.00 B"
total = "0.00 B"
}
raw := tools.Exec("LC_ALL=C free | grep Swap")
match := regexp.MustCompile(`Swap:\s+(\d+)\s+(\d+)\s+(\d+)`).FindStringSubmatch(raw)
if len(match) > 0 {
used = tools.FormatBytes(cast.ToFloat64(match[2]) * 1024)
free = tools.FormatBytes(cast.ToFloat64(match[3]) * 1024)
}
return controllers.Success(ctx, http.Json{
"total": total,
"size": size,
"used": used,
"free": free,
})
}
// SetSWAP 设置 SWAP 信息
func (c *ToolBoxController) SetSWAP(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
size := ctx.Request().InputInt("size")
if tools.Exists("/www/swap") {
tools.Exec("swapoff /www/swap")
tools.Exec("rm -f /www/swap")
tools.Exec("sed -i '/www\\/swap/d' /etc/fstab")
}
if size > 1 {
free := tools.Exec("df -k /www | awk '{print $4}' | tail -n 1")
if cast.ToInt64(free)*1024 < int64(size)*1024*1024 {
return controllers.Error(ctx, http.StatusBadRequest, "磁盘空间不足,当前剩余 "+tools.FormatBytes(cast.ToFloat64(free)))
}
if strings.Contains(tools.Exec("df -T /www | awk '{print $2}' | tail -n 1"), "btrfs") {
tools.Exec("btrfs filesystem mkswapfile --size " + cast.ToString(size) + "M --uuid clear /www/swap")
} else {
tools.Exec("dd if=/dev/zero of=/www/swap bs=1M count=" + cast.ToString(size))
tools.Exec("mkswap -f /www/swap")
tools.Chmod("/www/swap", 0600)
}
tools.Exec("swapon /www/swap")
tools.Exec("echo '/www/swap swap swap defaults 0 0' >> /etc/fstab")
}
return controllers.Success(ctx, nil)
}
// GetTimezone 获取时区
func (c *ToolBoxController) GetTimezone(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
raw := tools.Exec("LC_ALL=C timedatectl | grep zone")
match := regexp.MustCompile(`zone:\s+(\S+)`).FindStringSubmatch(raw)
if len(match) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "找不到时区信息")
}
zonesRaw := tools.Exec("LC_ALL=C timedatectl list-timezones")
zones := strings.Split(zonesRaw, "\n")
return controllers.Success(ctx, http.Json{
"zone": match[1],
"zones": zones,
})
}
// SetTimezone 设置时区
func (c *ToolBoxController) SetTimezone(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
timezone := ctx.Request().Input("timezone")
if len(timezone) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "时区不能为空")
}
tools.Exec("timedatectl set-timezone " + timezone)
return controllers.Success(ctx, nil)
}
// GetHosts 获取 hosts 信息
func (c *ToolBoxController) GetHosts(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
return controllers.Success(ctx, tools.Read("/etc/hosts"))
}
// SetHosts 设置 hosts 信息
func (c *ToolBoxController) SetHosts(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
hosts := ctx.Request().Input("hosts")
if len(hosts) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "hosts 信息不能为空")
}
tools.Write("/etc/hosts", hosts, 0644)
return controllers.Success(ctx, nil)
}
// SetRootPassword 设置 root 密码
func (c *ToolBoxController) SetRootPassword(ctx http.Context) http.Response {
check := controllers.Check(ctx, "toolbox")
if check != nil {
return check
}
password := ctx.Request().Input("password")
if len(password) == 0 {
return controllers.Error(ctx, http.StatusBadRequest, "密码不能为空")
}
if !regexp.MustCompile(`^[a-zA-Z0-9·~!@#$%^&*()_+-=\[\]{};:'",./<>?]{6,20}$`).MatchString(password) {
return controllers.Error(ctx, http.StatusBadRequest, "密码必须为 6-20 位字母、数字或特殊字符")
}
password = strings.ReplaceAll(password, `'`, `\'`)
tools.Exec(`yes '` + password + `' | passwd root`)
return controllers.Success(ctx, nil)
}
+320
View File
@@ -0,0 +1,320 @@
package controllers
import (
"regexp"
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/spf13/cast"
"panel/pkg/tools"
)
type SafeController struct {
// Dependent services
}
func NewSafeController() *SafeController {
return &SafeController{
// Inject services
}
}
// GetFirewallStatus 获取防火墙状态
func (r *SafeController) GetFirewallStatus(ctx http.Context) http.Response {
return Success(ctx, r.firewallStatus())
}
// SetFirewallStatus 设置防火墙状态
func (r *SafeController) SetFirewallStatus(ctx http.Context) http.Response {
var out string
if ctx.Request().InputBool("status") {
if tools.IsRHEL() {
out = tools.Exec("systemctl start firewalld")
} else {
out = tools.Exec("echo y | ufw enable")
}
} else {
if tools.IsRHEL() {
out = tools.Exec("systemctl stop firewalld")
} else {
out = tools.Exec("ufw disable")
}
}
return Success(ctx, out)
}
// GetFirewallRules 获取防火墙规则
func (r *SafeController) GetFirewallRules(ctx http.Context) http.Response {
if !r.firewallStatus() {
return Success(ctx, nil)
}
page := ctx.Request().QueryInt("page", 1)
limit := ctx.Request().QueryInt("limit", 10)
if tools.IsRHEL() {
out := tools.Exec("firewall-cmd --list-all 2>&1")
match := regexp.MustCompile(`ports: (.*)`).FindStringSubmatch(out)
if len(match) == 0 {
return Success(ctx, http.Json{
"total": 0,
"items": []map[string]string{},
})
}
ports := strings.Split(match[1], " ")
var rules []map[string]string
for _, port := range ports {
rule := strings.Split(port, "/")
rules = append(rules, map[string]string{
"port": rule[0],
"protocol": rule[1],
})
}
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(rules) {
return Success(ctx, http.Json{
"total": 0,
"items": []map[string]string{},
})
}
if endIndex > len(rules) {
endIndex = len(rules)
}
pagedRules := rules[startIndex:endIndex]
return Success(ctx, http.Json{
"total": len(rules),
"items": pagedRules,
})
} else {
out := tools.Exec("ufw status | grep -v '(v6)' | grep ALLOW | awk '{print $1}'")
if len(out) == 0 {
return Success(ctx, http.Json{
"total": 0,
"items": []map[string]string{},
})
}
var rules []map[string]string
for _, port := range strings.Split(out, "\n") {
rule := strings.Split(port, "/")
rules = append(rules, map[string]string{
"port": rule[0],
"protocol": rule[1],
})
}
startIndex := (page - 1) * limit
endIndex := page * limit
if startIndex > len(rules) {
return Success(ctx, http.Json{
"total": 0,
"items": []map[string]string{},
})
}
if endIndex > len(rules) {
endIndex = len(rules)
}
pagedRules := rules[startIndex:endIndex]
return Success(ctx, http.Json{
"total": len(rules),
"items": pagedRules,
})
}
}
// AddFirewallRule 添加防火墙规则
func (r *SafeController) AddFirewallRule(ctx http.Context) http.Response {
if !r.firewallStatus() {
return Error(ctx, http.StatusBadRequest, "防火墙未启动")
}
port := ctx.Request().Input("port")
protocol := ctx.Request().Input("protocol")
if port == "" || protocol == "" || (protocol != "tcp" && protocol != "udp") {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
// 端口有 2 种写法,一种是 80-443,一种是 80
if strings.Contains(port, "-") {
ports := strings.Split(port, "-")
startPort := cast.ToInt(ports[0])
endPort := cast.ToInt(ports[1])
if startPort < 1 || startPort > 65535 || endPort < 1 || endPort > 65535 || startPort > endPort {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
} else {
port := cast.ToInt(port)
if port < 1 || port > 65535 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
}
if tools.IsRHEL() {
tools.Exec("firewall-cmd --remove-port=" + cast.ToString(port) + "/" + protocol + " --permanent 2>&1")
tools.Exec("firewall-cmd --add-port=" + cast.ToString(port) + "/" + protocol + " --permanent 2>&1")
tools.Exec("firewall-cmd --reload")
} else {
// ufw 需要替换 - 为 : 添加
if strings.Contains(port, "-") {
port = strings.ReplaceAll(port, "-", ":")
}
tools.Exec("ufw delete allow " + cast.ToString(port) + "/" + protocol)
tools.Exec("ufw allow " + cast.ToString(port) + "/" + protocol)
tools.Exec("ufw reload")
}
return Success(ctx, nil)
}
// DeleteFirewallRule 删除防火墙规则
func (r *SafeController) DeleteFirewallRule(ctx http.Context) http.Response {
if !r.firewallStatus() {
return Error(ctx, http.StatusBadRequest, "防火墙未启动")
}
port := ctx.Request().InputInt("port", 0)
protocol := ctx.Request().Input("protocol", "")
if port == 0 || protocol == "" {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
if tools.IsRHEL() {
tools.Exec("firewall-cmd --remove-port=" + cast.ToString(port) + "/" + protocol + " --permanent 2>&1")
tools.Exec("firewall-cmd --reload")
} else {
tools.Exec("ufw delete allow " + cast.ToString(port) + "/" + protocol)
tools.Exec("ufw reload")
}
return Success(ctx, nil)
}
// firewallStatus 获取防火墙状态
func (r *SafeController) firewallStatus() bool {
var out string
var running bool
if tools.IsRHEL() {
out = tools.Exec("systemctl status firewalld | grep Active | awk '{print $3}'")
if out == "(running)" {
running = true
} else {
running = false
}
} else {
out = tools.Exec("ufw status | grep Status | awk '{print $2}'")
if out == "active" {
running = true
} else {
running = false
}
}
return running
}
// GetSshStatus 获取 SSH 状态
func (r *SafeController) GetSshStatus(ctx http.Context) http.Response {
var out string
if tools.IsRHEL() {
out = tools.Exec("systemctl status sshd | grep Active | awk '{print $3}'")
} else {
out = tools.Exec("systemctl status ssh | grep Active | awk '{print $3}'")
}
running := false
if out == "(running)" {
running = true
}
return Success(ctx, running)
}
// SetSshStatus 设置 SSH 状态
func (r *SafeController) SetSshStatus(ctx http.Context) http.Response {
if ctx.Request().InputBool("status") {
if tools.IsRHEL() {
tools.Exec("systemctl enable sshd")
tools.Exec("systemctl start sshd")
} else {
tools.Exec("systemctl enable ssh")
tools.Exec("systemctl start ssh")
}
} else {
if tools.IsRHEL() {
tools.Exec("systemctl stop sshd")
tools.Exec("systemctl disable sshd")
} else {
tools.Exec("systemctl stop ssh")
tools.Exec("systemctl disable ssh")
}
}
return Success(ctx, nil)
}
// GetSshPort 获取 SSH 端口
func (r *SafeController) GetSshPort(ctx http.Context) http.Response {
out := tools.Exec("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'")
return Success(ctx, out)
}
// SetSshPort 设置 SSH 端口
func (r *SafeController) SetSshPort(ctx http.Context) http.Response {
port := ctx.Request().InputInt("port", 0)
if port == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
oldPort := tools.Exec("cat /etc/ssh/sshd_config | grep 'Port ' | awk '{print $2}'")
tools.Exec("sed -i 's/#Port " + oldPort + "/Port " + cast.ToString(port) + "/g' /etc/ssh/sshd_config")
tools.Exec("sed -i 's/Port " + oldPort + "/Port " + cast.ToString(port) + "/g' /etc/ssh/sshd_config")
if status := tools.Exec("systemctl status sshd | grep Active | awk '{print $3}'"); status == "(running)" {
tools.Exec("systemctl restart sshd")
}
return Success(ctx, nil)
}
// GetPingStatus 获取 Ping 状态
func (r *SafeController) GetPingStatus(ctx http.Context) http.Response {
if tools.IsRHEL() {
out := tools.Exec(`firewall-cmd --list-all 2>&1`)
if !strings.Contains(out, `rule protocol value="icmp" drop`) {
return Success(ctx, true)
} else {
return Success(ctx, false)
}
} else {
config := tools.Read("/etc/ufw/before.rules")
if strings.Contains(config, "-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT") {
return Success(ctx, true)
} else {
return Success(ctx, false)
}
}
}
// SetPingStatus 设置 Ping 状态
func (r *SafeController) SetPingStatus(ctx http.Context) http.Response {
if tools.IsRHEL() {
if ctx.Request().InputBool("status") {
tools.Exec(`firewall-cmd --permanent --remove-rich-rule='rule protocol value=icmp drop'`)
} else {
tools.Exec(`firewall-cmd --permanent --add-rich-rule='rule protocol value=icmp drop'`)
}
tools.Exec(`firewall-cmd --reload`)
} else {
if ctx.Request().InputBool("status") {
tools.Exec(`sed -i 's/-A ufw-before-input -p icmp --icmp-type echo-request -j DROP/-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT/g' /etc/ufw/before.rules`)
} else {
tools.Exec(`sed -i 's/-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT/-A ufw-before-input -p icmp --icmp-type echo-request -j DROP/g' /etc/ufw/before.rules`)
}
tools.Exec(`ufw reload`)
}
return Success(ctx, nil)
}
+139
View File
@@ -0,0 +1,139 @@
package controllers
import (
"regexp"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/pkg/tools"
"panel/app/models"
"panel/app/services"
)
type SettingController struct {
setting services.Setting
}
func NewSettingController() *SettingController {
return &SettingController{
setting: services.NewSettingImpl(),
}
}
// List 获取设置列表
func (r *SettingController) List(ctx http.Context) http.Response {
var settings []models.Setting
err := facades.Orm().Query().Get(&settings)
if err != nil {
facades.Log().Error("[面板][SettingController] 查询设置列表失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
type data struct {
Name string `json:"name"`
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
Port string `json:"port"`
Entrance string `json:"entrance"`
WebsitePath string `json:"website_path"`
BackupPath string `json:"backup_path"`
}
var result data
result.Name = r.setting.Get(models.SettingKeyName)
result.Entrance = r.setting.Get(models.SettingKeyEntrance)
result.WebsitePath = r.setting.Get(models.SettingKeyWebsitePath)
result.BackupPath = r.setting.Get(models.SettingKeyBackupPath)
var user models.User
err = facades.Auth().User(ctx, &user)
if err != nil {
facades.Log().Error("[面板][SettingController] 获取用户失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
result.Username = user.Username
result.Email = user.Email
result.Port = tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
return Success(ctx, result)
}
// Save 保存设置
func (r *SettingController) Save(ctx http.Context) http.Response {
name := ctx.Request().Input("name")
port := ctx.Request().Input("port")
backupPath := ctx.Request().Input("backup_path")
websitePath := ctx.Request().Input("website_path")
entrance := ctx.Request().Input("entrance")
username := ctx.Request().Input("username")
email := ctx.Request().Input("email")
password := ctx.Request().Input("password")
if !regexp.MustCompile(`^/[^/]*[^/]$`).MatchString(entrance) || entrance == "/api" {
return Error(ctx, http.StatusUnprocessableEntity, "入口格式错误")
}
err := r.setting.Set(models.SettingKeyName, name)
if err != nil {
facades.Log().Error("[面板][SettingController] 保存设置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
oldPort := tools.Exec(`cat /www/panel/panel.conf | grep APP_PORT | awk -F '=' '{print $2}' | tr -d '\n'`)
if oldPort != port {
tools.Exec("sed -i 's/APP_PORT=" + oldPort + "/APP_PORT=" + port + "/g' /www/panel/panel.conf")
}
if !tools.Exists(backupPath) {
tools.Mkdir(backupPath, 0644)
}
err = r.setting.Set(models.SettingKeyBackupPath, backupPath)
if err != nil {
facades.Log().Error("[面板][SettingController] 保存设置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if !tools.Exists(websitePath) {
tools.Mkdir(websitePath, 0755)
tools.Chown(websitePath, "www", "www")
}
err = r.setting.Set(models.SettingKeyWebsitePath, websitePath)
if err != nil {
facades.Log().Error("[面板][SettingController] 保存设置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
err = r.setting.Set(models.SettingKeyEntrance, entrance)
if err != nil {
facades.Log().Error("[面板][SettingController] 保存设置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
var user models.User
err = facades.Auth().User(ctx, &user)
if err != nil {
facades.Log().Error("[面板][SettingController] 获取用户失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if len(username) > 0 {
user.Username = username
}
if len(email) > 0 {
user.Email = email
}
if len(password) > 0 {
hash, err := facades.Hash().Make(password)
if err != nil {
facades.Log().Error("[面板][SettingController] 保存设置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
user.Password = hash
}
if err = facades.Orm().Query().Save(&user); err != nil {
facades.Log().Error("[面板][SettingController] 保存设置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
+162
View File
@@ -0,0 +1,162 @@
package controllers
import (
"bytes"
"context"
nethttp "net/http"
"sync"
"time"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"github.com/gorilla/websocket"
"github.com/spf13/cast"
"panel/app/models"
"panel/app/services"
"panel/pkg/ssh"
)
type SshController struct {
AuthMethod ssh.AuthMethod
setting services.Setting
}
func NewSshController() *SshController {
return &SshController{
AuthMethod: ssh.PASSWORD,
setting: services.NewSettingImpl(),
}
}
// GetInfo 获取 SSH 配置
func (r *SshController) GetInfo(ctx http.Context) http.Response {
host := r.setting.Get(models.SettingKeySshHost)
port := r.setting.Get(models.SettingKeySshPort)
user := r.setting.Get(models.SettingKeySshUser)
password := r.setting.Get(models.SettingKeySshPassword)
if len(host) == 0 || len(user) == 0 || len(password) == 0 {
return Error(ctx, http.StatusInternalServerError, "SSH 配置不完整")
}
return Success(ctx, http.Json{
"host": host,
"port": cast.ToInt(port),
"user": user,
"password": password,
})
}
// UpdateInfo 更新 SSH 配置
func (r *SshController) UpdateInfo(ctx http.Context) http.Response {
validator, err := ctx.Request().Validate(map[string]string{
"host": "required",
"port": "required",
"user": "required",
"password": "required",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
host := ctx.Request().Input("host")
port := ctx.Request().Input("port")
user := ctx.Request().Input("user")
password := ctx.Request().Input("password")
err = r.setting.Set(models.SettingKeySshHost, host)
if err != nil {
facades.Log().Error("[面板][SSH] 更新配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
err = r.setting.Set(models.SettingKeySshPort, port)
if err != nil {
facades.Log().Error("[面板][SSH] 更新配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
err = r.setting.Set(models.SettingKeySshUser, user)
if err != nil {
facades.Log().Error("[面板][SSH] 更新配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
err = r.setting.Set(models.SettingKeySshPassword, password)
if err != nil {
facades.Log().Error("[面板][SSH] 更新配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
// Session SSH 会话
func (r *SshController) Session(ctx http.Context) http.Response {
upGrader := websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(r *nethttp.Request) bool {
return true
},
Subprotocols: []string{ctx.Request().Header("Sec-WebSocket-Protocol")},
}
ws, err := upGrader.Upgrade(ctx.Response().Writer(), ctx.Request().Origin(), nil)
if err != nil {
facades.Log().Error("[面板][SSH] 建立连接失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
defer ws.Close()
config := ssh.SSHClientConfigPassword(
r.setting.Get(models.SettingKeySshHost)+":"+r.setting.Get(models.SettingKeySshPort),
r.setting.Get(models.SettingKeySshUser),
r.setting.Get(models.SettingKeySshPassword),
)
client, err := ssh.NewSSHClient(config)
if err != nil {
_ = ws.WriteControl(websocket.CloseMessage,
[]byte(err.Error()), time.Now().Add(time.Second))
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
defer client.Close()
turn, err := ssh.NewTurn(ws, client)
if err != nil {
_ = ws.WriteControl(websocket.CloseMessage,
[]byte(err.Error()), time.Now().Add(time.Second))
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
defer turn.Close()
var bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
var logBuff = bufPool.Get().(*bytes.Buffer)
logBuff.Reset()
defer bufPool.Put(logBuff)
ctx2, cancel := context.WithCancel(context.Background())
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
err := turn.LoopRead(logBuff, ctx2)
if err != nil {
facades.Log().Error("[面板][SSH] 读取数据失败 ", err.Error())
}
}()
go func() {
defer wg.Done()
err := turn.SessionWait()
if err != nil {
facades.Log().Error("[面板][SSH] 会话失败 ", err.Error())
}
cancel()
}()
wg.Wait()
return Success(ctx, logBuff.String())
}
+83
View File
@@ -0,0 +1,83 @@
package controllers
import (
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/app/models"
"panel/pkg/tools"
)
type TaskController struct {
// Dependent services
}
func NewTaskController() *TaskController {
return &TaskController{
// Inject services
}
}
// Status 获取当前任务状态
func (r *TaskController) Status(ctx http.Context) http.Response {
var task models.Task
err := facades.Orm().Query().Where("status", models.TaskStatusWaiting).OrWhere("status", models.TaskStatusRunning).FirstOrFail(&task)
if err == nil {
return Success(ctx, http.Json{
"task": true,
})
}
return Success(ctx, http.Json{
"task": false,
})
}
// List 获取任务列表
func (r *TaskController) List(ctx http.Context) http.Response {
var tasks []models.Task
var total int64
err := facades.Orm().Query().Paginate(ctx.Request().QueryInt("page", 1), ctx.Request().QueryInt("limit", 10), &tasks, &total)
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][TaskController] 查询任务列表失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, http.Json{
"total": total,
"items": tasks,
})
}
// Log 获取任务日志
func (r *TaskController) Log(ctx http.Context) http.Response {
var task models.Task
err := facades.Orm().Query().Where("id", ctx.Request().QueryInt("id")).FirstOrFail(&task)
if err != nil {
facades.Log().With(map[string]any{
"id": ctx.Request().QueryInt("id"),
"error": err.Error(),
}).Error("[面板][TaskController] 查询任务失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
log := tools.Read(task.Log)
return Success(ctx, log)
}
// Delete 删除任务
func (r *TaskController) Delete(ctx http.Context) http.Response {
var task models.Task
_, err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).Delete(&task)
if err != nil {
facades.Log().With(map[string]any{
"id": ctx.Request().QueryInt("id"),
"error": err.Error(),
}).Error("[面板][TaskController] 删除任务失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
+79
View File
@@ -0,0 +1,79 @@
package controllers
import (
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/app/http/requests"
"panel/app/models"
)
type UserController struct {
// Dependent services
}
func NewUserController() *UserController {
return &UserController{
// Inject services
}
}
// Login 用户登录
func (r *UserController) Login(ctx http.Context) http.Response {
var loginRequest requests.LoginRequest
errors, err := ctx.Request().ValidateRequest(&loginRequest)
if err != nil {
return Error(ctx, http.StatusUnprocessableEntity, err.Error())
}
if errors != nil {
return Error(ctx, http.StatusUnprocessableEntity, errors.One())
}
var user models.User
err = facades.Orm().Query().Where("username", loginRequest.Username).First(&user)
if err != nil {
facades.Log().Error("[面板][UserController] 查询用户失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if user.ID == 0 || !facades.Hash().Check(loginRequest.Password, user.Password) {
return Error(ctx, http.StatusForbidden, "用户名或密码错误")
}
if facades.Hash().NeedsRehash(user.Password) {
user.Password, err = facades.Hash().Make(loginRequest.Password)
if err != nil {
facades.Log().Error("[面板][UserController] 更新密码失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
}
token, loginErr := facades.Auth().LoginUsingID(ctx, user.ID)
if loginErr != nil {
facades.Log().Error("[面板][UserController] 登录失败 ", loginErr)
return Error(ctx, http.StatusInternalServerError, loginErr.Error())
}
return Success(ctx, http.Json{
"access_token": token,
})
}
// Info 用户信息
func (r *UserController) Info(ctx http.Context) http.Response {
var user models.User
err := facades.Auth().User(ctx, &user)
if err != nil {
facades.Log().With(map[string]any{
"error": err.Error(),
}).Error("[面板][UserController] 查询用户信息失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, http.Json{
"id": user.ID,
"role": []string{"admin"},
"username": user.Username,
"email": user.Email,
})
}
+682
View File
@@ -0,0 +1,682 @@
package controllers
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
"panel/app/models"
"panel/app/services"
"panel/pkg/tools"
)
type WebsiteController struct {
website services.Website
setting services.Setting
backup services.Backup
}
func NewWebsiteController() *WebsiteController {
return &WebsiteController{
website: services.NewWebsiteImpl(),
setting: services.NewSettingImpl(),
backup: services.NewBackupImpl(),
}
}
// List 网站列表
func (c *WebsiteController) List(ctx http.Context) http.Response {
limit := ctx.Request().QueryInt("limit", 10)
page := ctx.Request().QueryInt("page", 1)
total, websites, err := c.website.List(page, limit)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站列表失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, http.Json{
"total": total,
"items": websites,
})
}
// Add 添加网站
func (c *WebsiteController) Add(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"name": "required|regex:^[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)*$|not_exists:websites,name",
"domains": "required|slice",
"ports": "required|slice",
"php": "required",
"db": "bool",
"db_type": "required_if:db,true",
"db_name": "required_if:db,true",
"db_user": "required_if:db,true",
"db_password": "required_if:db,true",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
var website services.PanelWebsite
website.Name = ctx.Request().Input("name")
website.Domains = ctx.Request().InputArray("domains")
website.Ports = ctx.Request().InputArray("ports")
website.Php = ctx.Request().InputInt("php")
website.Db = ctx.Request().InputBool("db")
website.DbType = ctx.Request().Input("db_type")
website.DbName = ctx.Request().Input("db_name")
website.DbUser = ctx.Request().Input("db_user")
website.DbPassword = ctx.Request().Input("db_password")
newSite, err := c.website.Add(website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 添加网站失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, newSite)
}
// Delete 删除网站
func (c *WebsiteController) Delete(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
id := ctx.Request().InputInt("id")
err := c.website.Delete(id)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 删除网站失败 ", err)
return Error(ctx, http.StatusInternalServerError, "删除网站失败: "+err.Error())
}
return Success(ctx, nil)
}
// GetDefaultConfig 获取默认配置
func (c *WebsiteController) GetDefaultConfig(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
index := tools.Read("/www/server/openresty/html/index.html")
stop := tools.Read("/www/server/openresty/html/stop.html")
return Success(ctx, http.Json{
"index": index,
"stop": stop,
})
}
// SaveDefaultConfig 保存默认配置
func (c *WebsiteController) SaveDefaultConfig(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
index := ctx.Request().Input("index")
stop := ctx.Request().Input("stop")
if !tools.Write("/www/server/openresty/html/index.html", index, 0644) {
facades.Log().Error("[面板][WebsiteController] 保存默认配置失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
if !tools.Write("/www/server/openresty/html/stop.html", stop, 0644) {
facades.Log().Error("[面板][WebsiteController] 保存默认配置失败")
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
// GetConfig 获取配置
func (c *WebsiteController) GetConfig(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
config, err := c.website.GetConfig(id)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, config)
}
// SaveConfig 保存配置
func (c *WebsiteController) SaveConfig(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
validator, err := ctx.Request().Validate(map[string]string{
"domains": "required|slice",
"ports": "required|slice",
"hsts": "bool",
"ssl": "bool",
"http_redirect": "bool",
"open_basedir": "bool",
"waf": "bool",
"waf_cache": "required",
"waf_mode": "required",
"waf_cc_deny": "required",
"index": "required",
"path": "required",
"root": "required",
"raw": "required",
"php": "required",
"ssl_certificate": "required_if:ssl,true",
"ssl_certificate_key": "required_if:ssl,true",
})
if err != nil {
return Error(ctx, http.StatusBadRequest, err.Error())
}
if validator.Fails() {
return Error(ctx, http.StatusBadRequest, validator.Errors().One())
}
var website models.Website
if facades.Orm().Query().Where("id", ctx.Request().Input("id")).FirstOrFail(&website) != nil {
return Error(ctx, http.StatusBadRequest, "网站不存在")
}
if !website.Status {
return Error(ctx, http.StatusBadRequest, "网站已停用,请先启用")
}
// 原文
raw := tools.Read("/www/server/vhost/" + website.Name + ".conf")
if strings.TrimSpace(raw) != strings.TrimSpace(ctx.Request().Input("raw")) {
tools.Write("/www/server/vhost/"+website.Name+".conf", ctx.Request().Input("raw"), 0644)
tools.Exec("systemctl reload openresty")
return Success(ctx, nil)
}
// 目录
path := ctx.Request().Input("path")
if !tools.Exists(path) {
return Error(ctx, http.StatusBadRequest, "网站目录不存在")
}
website.Path = path
// 域名
domain := "server_name"
domains := ctx.Request().InputArray("domains")
if len(domains) == 0 {
return Error(ctx, http.StatusBadRequest, "域名不能为空")
}
for _, v := range domains {
if v == "" {
continue
}
domain += " " + v
}
domain += ";"
domainConfigOld := tools.Cut(raw, "# server_name标记位开始", "# server_name标记位结束")
if len(strings.TrimSpace(domainConfigOld)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少server_name标记位")
}
raw = strings.Replace(raw, domainConfigOld, "\n "+domain+"\n ", -1)
// 端口
var port strings.Builder
ports := ctx.Request().InputArray("ports")
if len(ports) == 0 {
return Error(ctx, http.StatusBadRequest, "端口不能为空")
}
for i, v := range ports {
if _, err := strconv.Atoi(v); err != nil && v != "443 ssl http2" {
return Error(ctx, http.StatusBadRequest, "端口格式错误")
}
if v == "443" && ctx.Request().InputBool("ssl") {
v = "443 ssl http2"
}
if i != len(ports)-1 {
port.WriteString(" listen " + v + ";\n")
} else {
port.WriteString(" listen " + v + ";")
}
}
portConfigOld := tools.Cut(raw, "# port标记位开始", "# port标记位结束")
if len(strings.TrimSpace(portConfigOld)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少port标记位")
}
raw = strings.Replace(raw, portConfigOld, "\n"+port.String()+"\n ", -1)
// 运行目录
root := tools.Cut(raw, "# root标记位开始", "# root标记位结束")
if len(strings.TrimSpace(root)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少root标记位")
}
match := regexp.MustCompile(`root\s+(.+);`).FindStringSubmatch(root)
if len(match) != 2 {
return Error(ctx, http.StatusBadRequest, "配置文件中root标记位格式错误")
}
rootNew := strings.Replace(root, match[1], ctx.Request().Input("root"), -1)
raw = strings.Replace(raw, root, rootNew, -1)
// 默认文件
index := tools.Cut(raw, "# index标记位开始", "# index标记位结束")
if len(strings.TrimSpace(index)) == 0 {
return Error(ctx, http.StatusBadRequest, "配置文件中缺少index标记位")
}
match = regexp.MustCompile(`index\s+(.+);`).FindStringSubmatch(index)
if len(match) != 2 {
return Error(ctx, http.StatusBadRequest, "配置文件中index标记位格式错误")
}
indexNew := strings.Replace(index, match[1], ctx.Request().Input("index"), -1)
raw = strings.Replace(raw, index, indexNew, -1)
// 防跨站
root = ctx.Request().Input("root")
if !strings.HasSuffix(root, "/") {
root += "/"
}
if ctx.Request().InputBool("open_basedir") {
tools.Write(root+".user.ini", "open_basedir="+path+":/tmp/", 0644)
} else {
if tools.Exists(root + ".user.ini") {
tools.Remove(root + ".user.ini")
}
}
// WAF
waf := ctx.Request().InputBool("waf")
wafStr := "off"
if waf {
wafStr = "on"
}
wafMode := ctx.Request().Input("waf_mode", "DYNAMIC")
wafCcDeny := ctx.Request().Input("waf_cc_deny", "rate=1000r/m duration=60m")
wafCache := ctx.Request().Input("waf_cache", "capacity=50")
wafConfig := `# waf标记位开始
waf ` + wafStr + `;
waf_rule_path /www/server/openresty/ngx_waf/assets/rules/;
waf_mode ` + wafMode + `;
waf_cc_deny ` + wafCcDeny + `;
waf_cache ` + wafCache + `;
`
wafConfigOld := tools.Cut(raw, "# waf标记位开始", "# waf标记位结束")
if len(strings.TrimSpace(wafConfigOld)) != 0 {
raw = strings.Replace(raw, wafConfigOld, "", -1)
}
raw = strings.Replace(raw, "# waf标记位开始", wafConfig, -1)
// SSL
ssl := ctx.Request().InputBool("ssl")
website.Ssl = ssl
tools.Write("/www/server/vhost/ssl/"+website.Name+".pem", ctx.Request().Input("ssl_certificate"), 0644)
tools.Write("/www/server/vhost/ssl/"+website.Name+".key", ctx.Request().Input("ssl_certificate_key"), 0644)
if ssl {
sslConfig := `# ssl标记位开始
ssl_certificate /www/server/vhost/ssl/` + website.Name + `.pem;
ssl_certificate_key /www/server/vhost/ssl/` + website.Name + `.key;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
`
if ctx.Request().InputBool("http_redirect") {
sslConfig += `# http重定向标记位开始
if ($server_port !~ 443){
return 301 https://$host$request_uri;
}
error_page 497 https://$host$request_uri;
# http重定向标记位结束
`
}
if ctx.Request().InputBool("hsts") {
sslConfig += `# hsts标记位开始
add_header Strict-Transport-Security "max-age=63072000" always;
# hsts标记位结束
`
}
sslConfigOld := tools.Cut(raw, "# ssl标记位开始", "# ssl标记位结束")
if len(strings.TrimSpace(sslConfigOld)) != 0 {
raw = strings.Replace(raw, sslConfigOld, "", -1)
}
raw = strings.Replace(raw, "# ssl标记位开始", sslConfig, -1)
} else {
sslConfigOld := tools.Cut(raw, "# ssl标记位开始", "# ssl标记位结束")
if len(strings.TrimSpace(sslConfigOld)) != 0 {
raw = strings.Replace(raw, sslConfigOld, "\n ", -1)
}
}
if website.Php != ctx.Request().InputInt("php") {
website.Php = ctx.Request().InputInt("php")
phpConfigOld := tools.Cut(raw, "# php标记位开始", "# php标记位结束")
phpConfig := `
include enable-php-` + strconv.Itoa(website.Php) + `.conf;
`
if len(strings.TrimSpace(phpConfigOld)) != 0 {
raw = strings.Replace(raw, phpConfigOld, phpConfig, -1)
}
}
err = facades.Orm().Query().Save(&website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 保存网站配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
tools.Write("/www/server/vhost/"+website.Name+".conf", raw, 0644)
tools.Write("/www/server/vhost/rewrite/"+website.Name+".conf", ctx.Request().Input("rewrite"), 0644)
tools.Exec("systemctl reload openresty")
return Success(ctx, nil)
}
// ClearLog 清空日志
func (c *WebsiteController) ClearLog(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
website := models.Website{}
err := facades.Orm().Query().Where("id", id).Get(&website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站信息失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
tools.Remove("/www/wwwlogs/" + website.Name + ".log")
return Success(ctx, nil)
}
// UpdateRemark 更新备注
func (c *WebsiteController) UpdateRemark(ctx http.Context) http.Response {
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
website := models.Website{}
err := facades.Orm().Query().Where("id", id).Get(&website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站信息失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
website.Remark = ctx.Request().Input("remark")
err = facades.Orm().Query().Save(&website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 保存网站备注失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, nil)
}
// BackupList 备份列表
func (c *WebsiteController) BackupList(ctx http.Context) http.Response {
backupList, err := c.backup.WebsiteList()
if err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站备份列表失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
return Success(ctx, backupList)
}
// CreateBackup 创建备份
func (c *WebsiteController) CreateBackup(ctx http.Context) http.Response {
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
website := models.Website{}
err := facades.Orm().Query().Where("id", id).Get(&website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站信息失败 ", err)
return Error(ctx, http.StatusInternalServerError, "获取网站信息失败: "+err.Error())
}
err = c.backup.WebSiteBackup(website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 备份网站失败 ", err)
return Error(ctx, http.StatusInternalServerError, "备份网站失败: "+err.Error())
}
return Success(ctx, nil)
}
// UploadBackup 上传备份
func (c *WebsiteController) UploadBackup(ctx http.Context) http.Response {
file, err := ctx.Request().File("file")
if err != nil {
return Error(ctx, http.StatusBadRequest, "上传文件失败")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/website"
if !tools.Exists(backupPath) {
tools.Mkdir(backupPath, 0644)
}
name := file.GetClientOriginalName()
_, err = file.StoreAs(backupPath, name)
if err != nil {
return Error(ctx, http.StatusBadRequest, "上传文件失败")
}
return Success(ctx, "上传文件成功")
}
// RestoreBackup 还原备份
func (c *WebsiteController) RestoreBackup(ctx http.Context) http.Response {
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
fileName := ctx.Request().Input("name")
if len(fileName) == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
website := models.Website{}
err := facades.Orm().Query().Where("id", id).Get(&website)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站信息失败 ", err)
return Error(ctx, http.StatusInternalServerError, "获取网站信息失败: "+err.Error())
}
err = c.backup.WebsiteRestore(website, fileName)
if err != nil {
facades.Log().Error("[面板][WebsiteController] 还原网站失败 ", err)
return Error(ctx, http.StatusInternalServerError, "还原网站失败: "+err.Error())
}
return Success(ctx, nil)
}
// DeleteBackup 删除备份
func (c *WebsiteController) DeleteBackup(ctx http.Context) http.Response {
fileName := ctx.Request().Input("name")
if len(fileName) == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
backupPath := c.setting.Get(models.SettingKeyBackupPath) + "/website"
if !tools.Exists(backupPath) {
tools.Mkdir(backupPath, 0644)
}
if !tools.Remove(backupPath + "/" + fileName) {
return Error(ctx, http.StatusInternalServerError, "删除备份失败")
}
return Success(ctx, nil)
}
// ResetConfig 重置配置
func (c *WebsiteController) ResetConfig(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
website := models.Website{}
if err := facades.Orm().Query().Where("id", id).Get(&website); err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站信息失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
website.Status = true
website.Ssl = false
if err := facades.Orm().Query().Save(&website); err != nil {
facades.Log().Error("[面板][WebsiteController] 保存网站配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
raw := fmt.Sprintf(`
# 配置文件中的标记位请勿随意修改,改错将导致面板无法识别!
# 有自定义配置需求的,请将自定义的配置写在各标记位下方。
server
{
# port标记位开始
listen 80;
# port标记位结束
# server_name标记位开始
server_name localhost;
# server_name标记位结束
# index标记位开始
index index.php index.html;
# index标记位结束
# root标记位开始
root %s;
# root标记位结束
# ssl标记位开始
# ssl标记位结束
# php标记位开始
include enable-php-%d.conf;
# php标记位结束
# waf标记位开始
waf on;
waf_rule_path /www/server/openresty/ngx_waf/assets/rules/;
waf_mode DYNAMIC;
waf_cc_deny rate=1000r/m duration=60m;
waf_cache capacity=50;
# waf标记位结束
# 错误页配置,可自行设置
#error_page 404 /404.html;
#error_page 502 /502.html;
# 伪静态规则引入,修改后将导致面板设置的伪静态规则失效
include /www/server/vhost/rewrite/%s.conf;
# 面板默认禁止访问部分敏感目录,可自行修改
location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn)
{
return 404;
}
# 面板默认不记录静态资源的访问日志并开启1小时浏览器缓存,可自行修改
location ~ .*\.(js|css)$
{
expires 1h;
error_log /dev/null;
access_log /dev/null;
}
access_log /www/wwwlogs/%s.log;
error_log /www/wwwlogs/%s.log;
}
`, website.Path, website.Php, website.Name, website.Name, website.Name)
tools.Write("/www/server/vhost/"+website.Name+".conf", raw, 0644)
tools.Write("/www/server/vhost/rewrite"+website.Name+".conf", "", 0644)
tools.Exec("systemctl reload openresty")
return Success(ctx, nil)
}
// Status 网站状态
func (c *WebsiteController) Status(ctx http.Context) http.Response {
check := Check(ctx, "openresty")
if check != nil {
return check
}
id := ctx.Request().InputInt("id")
if id == 0 {
return Error(ctx, http.StatusBadRequest, "参数错误")
}
website := models.Website{}
if err := facades.Orm().Query().Where("id", id).Get(&website); err != nil {
facades.Log().Error("[面板][WebsiteController] 获取网站信息失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
website.Status = ctx.Request().InputBool("status")
if err := facades.Orm().Query().Save(&website); err != nil {
facades.Log().Error("[面板][WebsiteController] 保存网站配置失败 ", err)
return Error(ctx, http.StatusInternalServerError, "系统内部错误")
}
raw := tools.Read("/www/server/vhost/" + website.Name + ".conf")
// 运行目录
rootConfig := tools.Cut(raw, "# root标记位开始\n", "# root标记位结束")
match := regexp.MustCompile(`root\s+(.+);`).FindStringSubmatch(rootConfig)
if len(match) == 2 {
if website.Status {
root := regexp.MustCompile(`# root\s+(.+);`).FindStringSubmatch(rootConfig)
raw = strings.ReplaceAll(raw, rootConfig, " root "+root[1]+";\n ")
} else {
raw = strings.ReplaceAll(raw, rootConfig, " root /www/server/openresty/html;\n # root "+match[1]+";\n ")
}
}
// 默认文件
indexConfig := tools.Cut(raw, "# index标记位开始\n", "# index标记位结束")
match = regexp.MustCompile(`index\s+(.+);`).FindStringSubmatch(indexConfig)
if len(match) == 2 {
if website.Status {
index := regexp.MustCompile(`# index\s+(.+);`).FindStringSubmatch(indexConfig)
raw = strings.ReplaceAll(raw, indexConfig, " index "+index[1]+";\n ")
} else {
raw = strings.ReplaceAll(raw, indexConfig, " index stop.html;\n # index "+match[1]+";\n ")
}
}
tools.Write("/www/server/vhost/"+website.Name+".conf", raw, 0644)
tools.Exec("systemctl reload openresty")
return Success(ctx, nil)
}
+18
View File
@@ -0,0 +1,18 @@
package http
import (
"github.com/goravel/framework/contracts/http"
"panel/app/http/middleware"
)
type Kernel struct {
}
// The application's global HTTP middleware stack.
// These middleware are run during every request to your application.
func (kernel Kernel) Middleware() []http.Middleware {
return []http.Middleware{
middleware.Static(),
}
}
+49
View File
@@ -0,0 +1,49 @@
package middleware
import (
"errors"
"github.com/goravel/framework/auth"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/facades"
)
// Jwt 确保通过 JWT 鉴权
func Jwt() http.Middleware {
return func(ctx http.Context) {
token := ctx.Request().Header("Authorization", ctx.Request().Header("Sec-WebSocket-Protocol"))
if len(token) == 0 {
ctx.Request().AbortWithStatusJson(http.StatusOK, http.Json{
"code": 401,
"message": "未登录",
})
return
}
// JWT 鉴权
if _, err := facades.Auth().Parse(ctx, token); err != nil {
if errors.Is(err, auth.ErrorTokenExpired) {
token, err = facades.Auth().Refresh(ctx)
if err != nil {
// 到达刷新时间上限
ctx.Request().AbortWithStatusJson(http.StatusOK, http.Json{
"code": 401,
"message": "登录已过期",
})
return
}
token = "Bearer " + token
} else {
ctx.Request().AbortWithStatusJson(http.StatusOK, http.Json{
"code": 401,
"message": "登录已过期",
})
return
}
}
ctx.Response().Header("Authorization", token)
ctx.Request().Next()
}
}
+30
View File
@@ -0,0 +1,30 @@
package middleware
import (
"fmt"
"github.com/gin-contrib/static"
"github.com/goravel/framework/contracts/http"
"github.com/goravel/gin"
"panel/app/services"
)
func Static() http.Middleware {
return func(ctx http.Context) {
// 自动纠正 URL 格式
if ctx.Request().Path() == services.NewSettingImpl().Get("entrance", "/") && ctx.Request().Path() != "/" {
// ctx.Response().Redirect(http.StatusFound, ctx.Request().Path()+"/")
ctx.Response().Writer().WriteHeader(http.StatusFound)
_, err := ctx.Response().Writer().Write([]byte(fmt.Sprintf(`<html><head><meta http-equiv="refresh" content="0;url=%s/"></head></html>`, ctx.Request().Path())))
if err != nil {
return
}
ctx.Response().Flush()
return
}
static.Serve(services.NewSettingImpl().Get("entrance", "/"), static.LocalFile("public", false))(ctx.(*gin.Context).Instance())
ctx.Request().Next()
}
}
+43
View File
@@ -0,0 +1,43 @@
package requests
import (
"github.com/goravel/framework/contracts/http"
"github.com/goravel/framework/contracts/validation"
)
type LoginRequest struct {
Username string `json:"username" form:"username"`
Password string `json:"password" form:"password"`
CaptchaID string `json:"captcha_id" form:"captcha_id"`
Captcha string `json:"captcha" form:"captcha"`
}
func (r *LoginRequest) Authorize(ctx http.Context) error {
return nil
}
func (r *LoginRequest) Rules(ctx http.Context) map[string]string {
return map[string]string{
"username": "required",
"password": "required|min_len:8",
"captcha": "captcha:true",
}
}
func (r *LoginRequest) Messages(ctx http.Context) map[string]string {
return map[string]string{
"username.required": "登录名不能为空",
"password.required": "密码不能为空",
"password.min_len": "密码长度不能小于 8 位",
"captcha.captcha": "验证码错误",
}
}
func (r *LoginRequest) Attributes(ctx http.Context) map[string]string {
return map[string]string{}
}
func (r *LoginRequest) PrepareForValidation(ctx http.Context, data validation.Data) error {
return nil
}

Some files were not shown because too many files have changed in this diff Show More