feat(update): add rolling dev update channel for per-commit builds

Adds an opt-in Dev channel so panels running CI per-commit builds can self-update to the latest commit, mirroring the stable online-update flow.

CI publishes/overwrites a single fixed-tag pre-release (dev-latest), force-moved to the newest main commit and marked --latest=false so releases/latest stays the stable tag. Builds stamp the short commit via -ldflags; the panel compares the running commit to the dev release commit to detect an update, and update.sh honors XUI_UPDATE_TAG to install from that tag. Linux/systemd only.
This commit is contained in:
MHSanaei
2026-06-24 18:11:22 +02:00
parent 93ff60e568
commit aad2b3eb1e
25 changed files with 556 additions and 48 deletions
+130 -12
View File
@@ -8,6 +8,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
@@ -25,17 +26,27 @@ import (
type PanelService struct{}
// PanelUpdateInfo contains the current and latest available panel versions.
// On the dev channel the version fields carry a "dev+<sha>" label and the commit
// fields hold the short SHAs that drive the update-available decision.
type PanelUpdateInfo struct {
Channel string `json:"channel"`
CurrentVersion string `json:"currentVersion"`
LatestVersion string `json:"latestVersion"`
CurrentCommit string `json:"currentCommit,omitempty"`
LatestCommit string `json:"latestCommit,omitempty"`
UpdateAvailable bool `json:"updateAvailable"`
}
const (
panelUpdaterURL = "https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh"
maxPanelUpdaterBytes = 2 << 20
// devReleaseTag is the fixed-tag rolling pre-release the CI force-moves to the
// newest main commit; the dev update channel installs from it.
devReleaseTag = "dev-latest"
)
var releaseCommitRegex = regexp.MustCompile(`(?i)commit=([0-9a-f]{7,40})`)
func (s *PanelService) RestartPanel(delay time.Duration) error {
go func() {
time.Sleep(delay)
@@ -58,20 +69,59 @@ func (s *PanelService) RestartPanel(delay time.Duration) error {
return nil
}
// GetUpdateInfo checks GitHub for the latest 3x-ui release.
// GetUpdateInfo checks GitHub for the latest 3x-ui release. When the dev channel
// is enabled on a dev build it compares commits against the rolling dev release;
// otherwise it compares versions against the latest stable tag.
func (s *PanelService) GetUpdateInfo() (*PanelUpdateInfo, error) {
if devChannelActive() {
return getDevUpdateInfo()
}
latest, err := fetchLatestPanelVersion()
if err != nil {
return nil, err
}
current := config.GetVersion()
return &PanelUpdateInfo{
Channel: "stable",
CurrentVersion: current,
LatestVersion: latest,
UpdateAvailable: isNewerVersion(latest, current),
}, nil
}
// devChannelActive reports whether self-update should track the rolling dev
// release. It requires both the opt-in setting and a dev build, so a stable
// binary with the toggle left on never cross-grades to the dev channel.
func devChannelActive() bool {
if !config.IsDevBuild() {
return false
}
enabled, err := (&service.SettingService{}).GetDevChannelEnable()
return err == nil && enabled
}
// getDevUpdateInfo compares the running commit against the commit recorded in the
// rolling dev release.
func getDevUpdateInfo() (*PanelUpdateInfo, error) {
release, err := fetchPanelRelease(devReleaseTag)
if err != nil {
return nil, err
}
latestCommit := extractReleaseCommit(release)
if latestCommit == "" {
return nil, fmt.Errorf("dev release commit is unknown")
}
currentCommit := config.GetBuildCommit()
return &PanelUpdateInfo{
Channel: "dev",
CurrentVersion: config.GetVersion(),
CurrentCommit: shortCommit(currentCommit),
LatestCommit: shortCommit(latestCommit),
LatestVersion: "dev+" + shortCommit(latestCommit),
UpdateAvailable: !commitsEqual(currentCommit, latestCommit),
}, nil
}
// StartUpdate starts the official updater outside of the current web request.
func (s *PanelService) StartUpdate() error {
if runtime.GOOS != "linux" {
@@ -89,6 +139,10 @@ func (s *PanelService) StartUpdate() error {
}
mainFolder, serviceFolder := resolveUpdateFolders()
updateTag := ""
if devChannelActive() {
updateTag = devReleaseTag
}
updateScript := fmt.Sprintf("set -e; trap 'rm -f %s' EXIT; %s %s", shellQuote(scriptPath), shellQuote(bash), shellQuote(scriptPath))
if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
@@ -97,6 +151,7 @@ func (s *PanelService) StartUpdate() error {
"--unit", unitName,
"--setenv", "XUI_MAIN_FOLDER="+mainFolder,
"--setenv", "XUI_SERVICE="+serviceFolder,
"--setenv", "XUI_UPDATE_TAG="+updateTag,
bash, "-lc", updateScript,
)
out, err := cmd.CombinedOutput()
@@ -118,6 +173,7 @@ func (s *PanelService) StartUpdate() error {
cmd.Env = append(os.Environ(),
"XUI_MAIN_FOLDER="+mainFolder,
"XUI_SERVICE="+serviceFolder,
"XUI_UPDATE_TAG="+updateTag,
)
setDetachedProcess(cmd)
if err := cmd.Start(); err != nil {
@@ -170,26 +226,88 @@ func downloadPanelUpdater() (string, error) {
}
func fetchLatestPanelVersion() (string, error) {
client := (&service.SettingService{}).NewProxiedHTTPClient(10 * time.Second)
resp, err := client.Get("https://api.github.com/repos/MHSanaei/3x-ui/releases/latest")
release, err := fetchPanelRelease("")
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 service.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
}
// fetchPanelRelease fetches a release from GitHub. An empty tag resolves the
// latest stable release; a non-empty tag (e.g. dev-latest) resolves that tag.
func fetchPanelRelease(tag string) (*service.Release, error) {
url := "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest"
if tag != "" {
url = "https://api.github.com/repos/MHSanaei/3x-ui/releases/tags/" + tag
}
client := (&service.SettingService{}).NewProxiedHTTPClient(10 * time.Second)
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GitHub API returned status %d: %s", resp.StatusCode, resp.Status)
}
var release service.Release
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return nil, err
}
return &release, nil
}
// extractReleaseCommit reads the build commit recorded in the dev release: first
// the `commit=<sha>` marker the CI writes into the body, falling back to the
// tag's target commit.
func extractReleaseCommit(release *service.Release) string {
if m := releaseCommitRegex.FindStringSubmatch(release.Body); m != nil {
return strings.ToLower(m[1])
}
if isCommitSHA(release.TargetCommitish) {
return strings.ToLower(release.TargetCommitish)
}
return ""
}
func isCommitSHA(s string) bool {
s = strings.TrimSpace(s)
if len(s) < 7 || len(s) > 40 {
return false
}
for _, r := range s {
if (r < '0' || r > '9') && (r < 'a' || r > 'f') && (r < 'A' || r > 'F') {
return false
}
}
return true
}
func shortCommit(sha string) string {
sha = strings.TrimSpace(sha)
if len(sha) > 8 {
return sha[:8]
}
return sha
}
// commitsEqual compares a short (injected) commit against a full release commit
// by prefix, so an 8-char build stamp matches the 40-char release SHA.
func commitsEqual(a, b string) bool {
a = strings.ToLower(strings.TrimSpace(a))
b = strings.ToLower(strings.TrimSpace(b))
if a == "" || b == "" {
return false
}
if len(a) > len(b) {
a, b = b, a
}
return strings.HasPrefix(b, a)
}
func resolveUpdateFolders() (string, string) {
mainFolder := os.Getenv("XUI_MAIN_FOLDER")
if mainFolder == "" {
+69 -1
View File
@@ -1,6 +1,10 @@
package panel
import "testing"
import (
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
func TestIsNewerVersion(t *testing.T) {
cases := []struct {
@@ -39,3 +43,67 @@ func TestShellQuote(t *testing.T) {
t.Fatalf("unexpected quote result with single quote: %s", got)
}
}
func TestExtractReleaseCommit(t *testing.T) {
full := "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"
cases := []struct {
name string
release service.Release
want string
}{
{
name: "from body marker",
release: service.Release{Body: "Rolling build\n\ncommit=" + full + "\nbuilt=2026-06-24T00:00:00Z"},
want: full,
},
{
name: "body marker is case-insensitive and wins over target",
release: service.Release{Body: "COMMIT=" + full, TargetCommitish: "deadbeef"},
want: full,
},
{
name: "fallback to target commit sha",
release: service.Release{Body: "no marker here", TargetCommitish: full},
want: full,
},
{
name: "branch target is not a commit",
release: service.Release{Body: "no marker", TargetCommitish: "main"},
want: "",
},
}
for _, tc := range cases {
if got := extractReleaseCommit(&tc.release); got != tc.want {
t.Fatalf("%s: extractReleaseCommit = %q, want %q", tc.name, got, tc.want)
}
}
}
func TestCommitsEqual(t *testing.T) {
full := "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"
cases := []struct {
a, b string
want bool
}{
{"1a2b3c4d", full, true}, // injected 8-char prefix matches full release sha
{full, "1a2b3c4d", true}, // order independent
{"1A2B3C4D", full, true}, // case insensitive
{"deadbeef", full, false}, // different commit
{"", full, false}, // empty current never matches
{"1a2b3c4d", "", false}, // empty latest never matches
}
for _, tc := range cases {
if got := commitsEqual(tc.a, tc.b); got != tc.want {
t.Fatalf("commitsEqual(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want)
}
}
}
func TestShortCommit(t *testing.T) {
if got := shortCommit("1a2b3c4d5e6f7a8b"); got != "1a2b3c4d" {
t.Fatalf("shortCommit truncation = %q, want %q", got, "1a2b3c4d")
}
if got := shortCommit("abc"); got != "abc" {
t.Fatalf("shortCommit short input = %q, want %q", got, "abc")
}
}
+4 -1
View File
@@ -117,7 +117,10 @@ type Status struct {
// Release represents information about a software release from GitHub.
type Release struct {
TagName string `json:"tag_name"` // The tag name of the release
TagName string `json:"tag_name"` // The tag name of the release
Body string `json:"body"` // The release notes; the dev channel reads its commit from here
TargetCommitish string `json:"target_commitish"` // The branch/commit the tag points at
Prerelease bool `json:"prerelease"` // Whether this is a pre-release
}
// ServerService provides business logic for server monitoring and management.
+33 -19
View File
@@ -14,6 +14,7 @@ import (
"time"
"github.com/google/uuid"
"github.com/mhsanaei/3x-ui/v3/internal/config"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
@@ -109,6 +110,7 @@ var defaultValueMap = map[string]string{
"restartXrayOnClientDisable": "true",
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
"panelOutbound": "",
"devChannelEnable": "false",
// LDAP defaults
"ldapEnable": "false",
@@ -855,6 +857,16 @@ func (s *SettingService) SetRestartXrayOnClientDisable(value bool) error {
return s.setBool("restartXrayOnClientDisable", value)
}
// GetDevChannelEnable reports whether the panel self-update tracks the rolling
// per-commit dev release instead of the latest stable tag.
func (s *SettingService) GetDevChannelEnable() (bool, error) {
return s.getBool("devChannelEnable")
}
func (s *SettingService) SetDevChannelEnable(value bool) error {
return s.setBool("devChannelEnable", value)
}
// GetIpLimitEnable reports whether the IP-limit feature is available. Always
// true since the panel enforces limits via the core's online-stats API; on an
// older core the job falls back to access-log parsing and warns there when the
@@ -1209,25 +1221,27 @@ func (s *SettingService) BuildSubURIBase(host string) string {
func (s *SettingService) GetDefaultSettings(host string) (any, error) {
type settingFunc func() (any, error)
settings := map[string]settingFunc{
"expireDiff": func() (any, error) { return s.GetExpireDiff() },
"trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
"pageSize": func() (any, error) { return s.GetPageSize() },
"defaultCert": func() (any, error) { return s.GetCertFile() },
"defaultKey": func() (any, error) { return s.GetKeyFile() },
"tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
"subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
"subEnable": func() (any, error) { return s.GetSubEnable() },
"subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
"subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
"subTitle": func() (any, error) { return s.GetSubTitle() },
"subURI": func() (any, error) { return s.GetSubURI() },
"subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
"subClashURI": func() (any, error) { return s.GetSubClashURI() },
"datepicker": func() (any, error) { return s.GetDatepicker() },
"ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
"accessLogEnable": func() (any, error) { return s.GetAccessLogEnable() },
"webDomain": func() (any, error) { return s.GetWebDomain() },
"subDomain": func() (any, error) { return s.GetSubDomain() },
"expireDiff": func() (any, error) { return s.GetExpireDiff() },
"trafficDiff": func() (any, error) { return s.GetTrafficDiff() },
"pageSize": func() (any, error) { return s.GetPageSize() },
"defaultCert": func() (any, error) { return s.GetCertFile() },
"defaultKey": func() (any, error) { return s.GetKeyFile() },
"tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
"subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
"subEnable": func() (any, error) { return s.GetSubEnable() },
"subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
"subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
"subTitle": func() (any, error) { return s.GetSubTitle() },
"subURI": func() (any, error) { return s.GetSubURI() },
"subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
"subClashURI": func() (any, error) { return s.GetSubClashURI() },
"datepicker": func() (any, error) { return s.GetDatepicker() },
"ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
"accessLogEnable": func() (any, error) { return s.GetAccessLogEnable() },
"webDomain": func() (any, error) { return s.GetWebDomain() },
"subDomain": func() (any, error) { return s.GetSubDomain() },
"devChannelEnable": func() (any, error) { return s.GetDevChannelEnable() },
"isDevBuild": func() (any, error) { return config.IsDevBuild(), nil },
}
result := make(map[string]any)