feat: add panel update functionality via web GUI (#4117)

* feat: add panel update functionality via web GUI

* feat: enhance panel update notifications in web GUI

* feat: implement panel update modal and enhance translation strings

* fix design
This commit is contained in:
Farhad H. P. Shirvan
2026-04-28 18:46:55 +02:00
committed by GitHub
parent 22de983752
commit f21ed92296
7 changed files with 367 additions and 10 deletions

View File

@@ -22,6 +22,7 @@ type ServerController struct {
serverService service.ServerService
settingService service.SettingService
panelService service.PanelService
lastStatus *service.Status
@@ -43,6 +44,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) {
g.GET("/status", a.status)
g.GET("/cpuHistory/:bucket", a.getCpuHistoryBucket)
g.GET("/getXrayVersion", a.getXrayVersion)
g.GET("/getPanelUpdateInfo", a.getPanelUpdateInfo)
g.GET("/getConfigJson", a.getConfigJson)
g.GET("/getDb", a.getDb)
g.GET("/getNewUUID", a.getNewUUID)
@@ -54,6 +56,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) {
g.POST("/stopXrayService", a.stopXrayService)
g.POST("/restartXrayService", a.restartXrayService)
g.POST("/installXray/:version", a.installXray)
g.POST("/updatePanel", a.updatePanel)
g.POST("/updateGeofile", a.updateGeofile)
g.POST("/updateGeofile/:fileName", a.updateGeofile)
g.POST("/logs/:count", a.getLogs)
@@ -131,6 +134,16 @@ func (a *ServerController) getXrayVersion(c *gin.Context) {
jsonObj(c, versions, nil)
}
// getPanelUpdateInfo retrieves the current and latest panel version.
func (a *ServerController) getPanelUpdateInfo(c *gin.Context) {
info, err := a.panelService.GetUpdateInfo()
if err != nil {
jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateCheckPopover"), err)
return
}
jsonObj(c, info, nil)
}
// installXray installs or updates Xray to the specified version.
func (a *ServerController) installXray(c *gin.Context) {
version := c.Param("version")
@@ -138,6 +151,12 @@ func (a *ServerController) installXray(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "pages.index.xraySwitchVersionPopover"), err)
}
// updatePanel starts a panel self-update to the latest release.
func (a *ServerController) updatePanel(c *gin.Context) {
err := a.panelService.StartUpdate()
jsonMsg(c, I18nWeb(c, "pages.index.panelUpdateStartedPopover"), err)
}
// updateGeofile updates the specified geo file for Xray.
func (a *ServerController) updateGeofile(c *gin.Context) {
fileName := c.Param("fileName")

View File

@@ -139,7 +139,7 @@
<a-icon type="reload"></a-icon>
<span v-if="!isMobile">{{ i18n "pages.index.restartXray" }}</span>
</a-space>
<a-space direction="horizontal" @click="openSelectV2rayVersion" class="jc-center">
<a-space direction="horizontal" @click="openSelectV2rayVersion()" class="jc-center">
<a-icon type="tool"></a-icon>
<span v-if="!isMobile">
[[ status.xray.version != 'Unknown' ? `v${status.xray.version}` : '{{ i18n
@@ -169,6 +169,14 @@
</a-col>
<a-col :sm="24" :lg="12">
<a-card title='3X-UI' hoverable>
<template v-if="panelUpdateModal.info.updateAvailable" #extra>
<a-tooltip :overlay-class-name="themeSwitcher.currentTheme" :title='`{{ i18n "pages.index.updatePanel" }}: ${panelUpdateModal.info.latestVersion}`'>
<a-tag color="orange" style="cursor:pointer;margin:0" @click="openPanelUpdate">
<a-icon type="cloud-download"></a-icon>[[ panelUpdateModal.info.latestVersion ]]
<span v-if="!isMobile">{{ i18n "pages.index.updatePanel" }}</span>
</a-tag>
</a-tooltip>
</template>
<a rel="noopener" href="https://github.com/MHSanaei/3x-ui/releases" target="_blank">
<a-tag color="green">
<span>v{{ .cur_ver }}</span>
@@ -317,9 +325,36 @@
</a-spin>
</a-layout-content>
</a-layout>
<a-modal id="version-modal" v-model="versionModal.visible" title='{{ i18n "pages.index.xraySwitch" }}'
<a-modal id="panel-update-modal" v-model="panelUpdateModal.visible" title='{{ i18n "pages.index.updatePanel" }}'
:closable="true" @ok="() => panelUpdateModal.visible = false" :class="themeSwitcher.currentTheme" footer="">
<a-alert type="warning" class="mb-12 w-100" message='{{ i18n "pages.index.panelUpdateDesc" }}'
show-icon></a-alert>
<a-list class="ant-version-list w-100" bordered>
<a-list-item class="ant-version-list-item">
<span>{{ i18n "pages.index.currentPanelVersion" }}</span>
<a-tag color="green">v[[ panelUpdateModal.info.currentVersion || '{{ .cur_ver }}' ]]</a-tag>
</a-list-item>
<a-list-item class="ant-version-list-item" v-if="panelUpdateModal.info.updateAvailable">
<span>{{ i18n "pages.index.latestPanelVersion" }}</span>
<a-tag color="purple">
[[ panelUpdateModal.info.latestVersion || '-' ]]
</a-tag>
</a-list-item>
<a-list-item class="ant-version-list-item" v-else>
<span>{{ i18n "pages.index.panelUpToDate" }}</span>
<a-tag color="green">{{ i18n "pages.index.upToDate" }}</a-tag>
</a-list-item>
</a-list>
<div class="mt-5 d-flex justify-end">
<a-button type="primary" icon="cloud-download" :disabled="!panelUpdateModal.info.updateAvailable"
@click="updatePanel">
{{ i18n "pages.index.updatePanel" }}
</a-button>
</div>
</a-modal>
<a-modal id="version-modal" v-model="versionModal.visible" title='{{ i18n "pages.index.xrayUpdates" }}'
:closable="true" @ok="() => versionModal.visible = false" :class="themeSwitcher.currentTheme" footer="">
<a-collapse default-active-key="1">
<a-collapse accordion :active-key="versionModal.activeKey" @change="key => versionModal.activeKey = key">
<a-collapse-panel key="1" header='Xray'>
<a-alert type="warning" class="mb-12 w-100" message='{{ i18n "pages.index.xraySwitchClickDesk" }}'
show-icon></a-alert>
@@ -799,9 +834,11 @@
const versionModal = {
visible: false,
activeKey: '1',
versions: [],
show(versions) {
show(versions, activeKey = '1') {
this.visible = true;
this.activeKey = activeKey;
this.versions = versions;
},
hide() {
@@ -809,6 +846,24 @@
},
};
const panelUpdateModal = {
visible: false,
info: {
currentVersion: '{{ .cur_ver }}',
latestVersion: '',
updateAvailable: false,
},
show(info) {
this.visible = true;
if (info) {
this.info = info;
}
},
hide() {
this.visible = false;
},
};
const logModal = {
visible: false,
logs: [],
@@ -958,11 +1013,12 @@
spinning: false
},
status: new Status(),
cpuHistory: [], // small live widget history
cpuHistoryLong: [], // aggregated points from backend
cpuHistoryLabels: [],
cpuHistoryModal: { visible: false, bucket: 2 },
cpuHistory: [], // small live widget history
cpuHistoryLong: [], // aggregated points from backend
cpuHistoryLabels: [],
cpuHistoryModal: { visible: false, bucket: 2 },
versionModal,
panelUpdateModal,
logModal,
xraylogModal,
backupModal,
@@ -1049,16 +1105,25 @@
console.error('Failed to fetch bucketed cpu history', e)
}
},
async openSelectV2rayVersion() {
async openSelectV2rayVersion(activeKey = '1') {
this.loading(true);
const msg = await HttpUtil.get('/panel/api/server/getXrayVersion');
this.loading(false);
if (!msg.success) {
return;
}
versionModal.show(msg.obj);
versionModal.show(msg.obj, activeKey);
this.loadCustomGeo();
},
async openPanelUpdate() {
this.loading(true);
const msg = await HttpUtil.get('/panel/api/server/getPanelUpdateInfo');
this.loading(false);
if (!msg.success) {
return;
}
panelUpdateModal.show(msg.obj);
},
customGeoFormatTime(ts) {
if (!ts) return '';
return typeof moment !== 'undefined' ? moment(ts * 1000).format('YYYY-MM-DD HH:mm') : String(ts);
@@ -1195,6 +1260,27 @@
},
});
},
updatePanel() {
this.$confirm({
title: '{{ i18n "pages.index.panelUpdateDialog" }}',
content: '{{ i18n "pages.index.panelUpdateDialogDesc" }}'
.replace('#version#', panelUpdateModal.info.latestVersion || ''),
okText: '{{ i18n "confirm"}}',
class: themeSwitcher.currentTheme,
cancelText: '{{ i18n "cancel"}}',
onOk: async () => {
panelUpdateModal.hide();
this.loading(true, '{{ i18n "pages.index.dontRefresh"}}');
const msg = await HttpUtil.post('/panel/api/server/updatePanel');
if (!msg.success) {
this.loading(false);
return;
}
await PromiseUtil.sleep(15000);
window.location.reload();
},
});
},
updateGeofile(fileName) {
const isSingleFile = !!fileName;
this.$confirm({
@@ -1346,6 +1432,13 @@
// Initial status fetch
await this.getStatus();
// Silently check for panel updates so the indicator shows on load
HttpUtil.get('/panel/api/server/getPanelUpdateInfo').then(msg => {
if (msg && msg.success && msg.obj) {
panelUpdateModal.info = msg.obj;
}
});
// Setup WebSocket for real-time updates
if (window.wsClient) {
window.wsClient.connect();

View File

@@ -1,10 +1,19 @@
package service
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/mhsanaei/3x-ui/v2/config"
"github.com/mhsanaei/3x-ui/v2/logger"
)
@@ -12,6 +21,13 @@ import (
// It handles panel restart, updates, and system-level panel controls.
type PanelService struct{}
// PanelUpdateInfo contains the current and latest available panel versions.
type PanelUpdateInfo struct {
CurrentVersion string `json:"currentVersion"`
LatestVersion string `json:"latestVersion"`
UpdateAvailable bool `json:"updateAvailable"`
}
func (s *PanelService) RestartPanel(delay time.Duration) error {
p, err := os.FindProcess(syscall.Getpid())
if err != nil {
@@ -26,3 +42,161 @@ func (s *PanelService) RestartPanel(delay time.Duration) error {
}()
return nil
}
// GetUpdateInfo checks GitHub for the latest 3x-ui release.
func (s *PanelService) GetUpdateInfo() (*PanelUpdateInfo, error) {
latest, err := fetchLatestPanelVersion()
if err != nil {
return nil, err
}
current := config.GetVersion()
return &PanelUpdateInfo{
CurrentVersion: current,
LatestVersion: latest,
UpdateAvailable: isNewerVersion(latest, current),
}, nil
}
// StartUpdate starts the official updater outside of the current web request.
func (s *PanelService) StartUpdate() error {
if runtime.GOOS != "linux" {
return fmt.Errorf("panel web update is supported only on Linux installations")
}
bash, err := exec.LookPath("bash")
if err != nil {
return fmt.Errorf("bash is required to run the panel updater: %w", err)
}
curl, err := exec.LookPath("curl")
if err != nil {
return fmt.Errorf("curl is required to download the panel updater: %w", err)
}
mainFolder, serviceFolder := resolveUpdateFolders()
updateScript := fmt.Sprintf("set -o pipefail; %s -fLs https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh | %s", shellQuote(curl), shellQuote(bash))
if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
unitName := fmt.Sprintf("x-ui-web-update-%d", time.Now().Unix())
cmd := exec.Command(systemdRun,
"--unit", unitName,
"--setenv", "XUI_MAIN_FOLDER="+mainFolder,
"--setenv", "XUI_SERVICE="+serviceFolder,
bash, "-lc", updateScript,
)
out, err := cmd.CombinedOutput()
if err != nil {
output := strings.TrimSpace(string(out))
if !strings.Contains(output, "System has not been booted with systemd") &&
!strings.Contains(output, "Failed to connect to bus") {
return fmt.Errorf("failed to start panel update job: %w: %s", err, output)
}
logger.Warning("systemd-run is unavailable, falling back to detached update process:", output)
} else {
logger.Infof("started panel update job via systemd-run unit %s", unitName)
return nil
}
}
cmd := exec.Command(bash, "-lc", updateScript)
cmd.Env = append(os.Environ(),
"XUI_MAIN_FOLDER="+mainFolder,
"XUI_SERVICE="+serviceFolder,
)
setDetachedProcess(cmd)
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start panel update job: %w", err)
}
if err := cmd.Process.Release(); err != nil {
logger.Warning("failed to release panel update process:", err)
}
logger.Infof("started panel update job with pid %d", cmd.Process.Pid)
return nil
}
func fetchLatestPanelVersion() (string, error) {
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get("https://api.github.com/repos/MHSanaei/3x-ui/releases/latest")
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
}
var release Release
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return "", err
}
if release.TagName == "" {
return "", fmt.Errorf("latest panel release tag is empty")
}
return release.TagName, nil
}
func resolveUpdateFolders() (string, string) {
mainFolder := os.Getenv("XUI_MAIN_FOLDER")
if mainFolder == "" {
if exePath, err := os.Executable(); err == nil {
mainFolder = filepath.Dir(exePath)
}
}
if mainFolder == "" {
mainFolder = "/usr/local/x-ui"
}
serviceFolder := os.Getenv("XUI_SERVICE")
if serviceFolder == "" {
serviceFolder = "/etc/systemd/system"
}
return mainFolder, serviceFolder
}
func isNewerVersion(latest string, current string) bool {
cmp, ok := compareVersionStrings(latest, current)
if !ok {
return normalizeVersionTag(latest) != normalizeVersionTag(current)
}
return cmp > 0
}
func compareVersionStrings(a string, b string) (int, bool) {
aParts, okA := parseVersionParts(a)
bParts, okB := parseVersionParts(b)
if !okA || !okB {
return 0, false
}
for i := 0; i < len(aParts); i++ {
if aParts[i] > bParts[i] {
return 1, true
}
if aParts[i] < bParts[i] {
return -1, true
}
}
return 0, true
}
func parseVersionParts(version string) ([3]int, bool) {
var result [3]int
parts := strings.Split(normalizeVersionTag(version), ".")
if len(parts) != 3 {
return result, false
}
for i, part := range parts {
n, err := strconv.Atoi(part)
if err != nil {
return result, false
}
result[i] = n
}
return result, true
}
func normalizeVersionTag(version string) string {
return strings.TrimPrefix(strings.TrimSpace(version), "v")
}
func shellQuote(value string) string {
return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
}

View File

@@ -0,0 +1,7 @@
//go:build !linux
package service
import "os/exec"
func setDetachedProcess(cmd *exec.Cmd) {}

41
web/service/panel_test.go Normal file
View File

@@ -0,0 +1,41 @@
package service
import "testing"
func TestIsNewerVersion(t *testing.T) {
cases := []struct {
latest string
current string
want bool
}{
{"v2.9.4", "2.9.3", true},
{"v2.10.0", "2.9.9", true},
{"v2.9.3", "2.9.3", false},
{"v2.9.2", "2.9.3", false},
{"v3.0.0", "2.9.3", true},
}
for _, tc := range cases {
if got := isNewerVersion(tc.latest, tc.current); got != tc.want {
t.Fatalf("isNewerVersion(%q, %q) = %v, want %v", tc.latest, tc.current, got, tc.want)
}
}
}
func TestCompareVersionStringsRejectsUnexpectedFormats(t *testing.T) {
if _, ok := compareVersionStrings("latest", "2.9.3"); ok {
t.Fatal("expected non-semver latest tag to be rejected")
}
if _, ok := compareVersionStrings("v2.9", "2.9.3"); ok {
t.Fatal("expected short version to be rejected")
}
}
func TestShellQuote(t *testing.T) {
if got := shellQuote("/usr/bin/curl"); got != "'/usr/bin/curl'" {
t.Fatalf("unexpected quote result: %s", got)
}
if got := shellQuote("/tmp/a'b"); got != "'/tmp/a'\\''b'" {
t.Fatalf("unexpected quote result with single quote: %s", got)
}
}

12
web/service/panel_unix.go Normal file
View File

@@ -0,0 +1,12 @@
//go:build linux
package service
import (
"os/exec"
"syscall"
)
func setDetachedProcess(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
}

View File

@@ -124,8 +124,15 @@
"stopXray" = "Stop"
"restartXray" = "Restart"
"xraySwitch" = "Version"
"xrayUpdates" = "Xray Updates"
"xraySwitchClick" = "Choose the version you want to switch to."
"xraySwitchClickDesk" = "Choose carefully, as older versions may not be compatible with current configurations."
"updatePanel" = "Update Panel"
"panelUpdateDesc" = "This will update 3X-UI itself to the latest release and restart the panel service."
"currentPanelVersion" = "Current panel version"
"latestPanelVersion" = "Latest panel version"
"panelUpToDate" = "Panel is up to date"
"upToDate" = "Up to date"
"xrayStatusUnknown" = "Unknown"
"xrayStatusRunning" = "Running"
"xrayStatusStop" = "Stop"
@@ -147,6 +154,10 @@
"xraySwitchVersionDialog" = "Do you really want to change the Xray version?"
"xraySwitchVersionDialogDesc" = "This will change the Xray version to #version#."
"xraySwitchVersionPopover" = "Xray updated successfully"
"panelUpdateDialog" = "Do you really want to update the panel?"
"panelUpdateDialogDesc" = "This will update 3X-UI to #version# and restart the panel service."
"panelUpdateCheckPopover" = "Panel update check failed"
"panelUpdateStartedPopover" = "Panel update started"
"geofileUpdateDialog" = "Do you really want to update the geofile?"
"geofileUpdateDialogDesc" = "This will update the #filename# file."
"geofilesUpdateDialogDesc" = "This will update all geofiles."