Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 82 additions & 7 deletions core/app/service/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net"
"os"
"path"
"regexp"
"strconv"
"strings"
"time"
Expand All @@ -21,6 +22,8 @@ import (
"github.com/1Panel-dev/1Panel/core/utils/cmd"
"github.com/1Panel-dev/1Panel/core/utils/common"
"github.com/1Panel-dev/1Panel/core/utils/encrypt"
"github.com/1Panel-dev/1Panel/core/utils/firewall"
"github.com/1Panel-dev/1Panel/core/utils/xpack"
"github.com/gin-gonic/gin"
)

Expand Down Expand Up @@ -75,15 +78,20 @@ func (u *SettingService) GetSettingInfo() (*dto.SettingInfo, error) {
}

func (u *SettingService) Update(key, value string) error {
oldVal, err := settingRepo.Get(repo.WithByKey(key))
if err != nil {
return err
}
if oldVal.Value == value {
return nil
}
switch key {
case "AppStoreLastModified":
exist, _ := settingRepo.Get(repo.WithByKey("AppStoreLastModified"))
if exist.ID == 0 {
_ = settingRepo.Create("AppStoreLastModified", value)
return nil
}
case "MasterAddr":
global.CONF.System.MasterAddr = value
}

if err := settingRepo.Update(key, value); err != nil {
Expand All @@ -105,7 +113,12 @@ func (u *SettingService) Update(key, value string) error {
}
case "UserName", "Password":
_ = global.SESSION.Clean()

case "MasterAddr":
go func() {
if err := xpack.UpdateMasterAddr(value); err != nil {
global.LOG.Errorf("update master addr failed, err: %v", err)
}
}()
}

return nil
Expand Down Expand Up @@ -174,16 +187,40 @@ func (u *SettingService) UpdatePort(port uint) error {
if common.ScanPort(int(port)) {
return buserr.WithDetail(constant.ErrPortInUsed, port, nil)
}
// TODO 修改防火墙端口
oldPort, err := settingRepo.Get(repo.WithByKey("Port"))
if err != nil {
return err
}
if oldPort.Value == fmt.Sprintf("%v", port) {
return nil
}
if err := firewall.UpdatePort(oldPort.Value, fmt.Sprintf("%v", port)); err != nil {
return err
}

if err := settingRepo.Update("ServerPort", strconv.Itoa(int(port))); err != nil {
return err
}
go func() {
time.Sleep(1 * time.Second)
_, err := cmd.Exec("systemctl restart 1panel.service")
defer func() {
if _, err := cmd.Exec("systemctl restart 1panel.service"); err != nil {
global.LOG.Errorf("restart system port failed, err: %v", err)
}
}()
masterAddr, err := settingRepo.Get(repo.WithByKey("MasterAddr"))
if err != nil {
global.LOG.Errorf("restart system port failed, err: %v", err)
global.LOG.Errorf("load master addr from db failed, err: %v", err)
return
}
if len(masterAddr.Value) != 0 {
oldMasterPort := loadPort(masterAddr.Value)
if len(oldMasterPort) != 0 {
if err := xpack.UpdateMasterAddr(strings.ReplaceAll(masterAddr.Value, oldMasterPort, fmt.Sprintf("%v", port))); err != nil {
global.LOG.Errorf("update master addr from db failed, err: %v", err)
return
}
}
}
}()
return nil
Expand Down Expand Up @@ -250,7 +287,31 @@ func (u *SettingService) UpdateSSL(c *gin.Context, req dto.SSLUpdate) error {
if err := settingRepo.Update("SSL", req.SSL); err != nil {
return err
}
return u.UpdateSystemSSL()

if err := u.UpdateSystemSSL(); err != nil {
return err
}

go func() {
oldSSL, _ := settingRepo.Get(repo.WithByKey("SSL"))
if oldSSL.Value != req.SSL {
masterAddr, err := settingRepo.Get(repo.WithByKey("MasterAddr"))
if err != nil {
global.LOG.Errorf("load master addr from db failed, err: %v", err)
return
}
addrItem := masterAddr.Value
if req.SSL == constant.StatusDisable {
addrItem = strings.ReplaceAll(addrItem, "https://", "http://")
} else {
addrItem = strings.ReplaceAll(addrItem, "http://", "https://")
}
if err := xpack.UpdateMasterAddr(addrItem); err != nil {
global.LOG.Errorf("update master addr from db failed, err: %v", err)
}
}
}()
return nil
}

func (u *SettingService) LoadFromCert() (*dto.SSLInfo, error) {
Expand Down Expand Up @@ -452,3 +513,17 @@ func checkCertValid() error {

return nil
}

func loadPort(address string) string {
re := regexp.MustCompile(`(?:(?:\[([0-9a-fA-F:]+)\])|([^:/\s]+))(?::(\d+))?$`)
matches := re.FindStringSubmatch(address)
if len(matches) <= 0 {
return ""
}
var port string
port = matches[3]
if len(port) != 0 {
return port
}
return ""
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code seems to be incomplete with certain sections missing, including the LoadFromCert, etc. However, based on what you've shared, there seem to be some regular coding standards violated like using strings directly instead of a struct for error handling and variable names that don't follow Go conventions.

Here's a basic outline:

Check for Regular Irregularities

  • Check for unnecessary or irrelevant comments.
  • Ensure consistent use of single quotes around variables.
  • Ensure function parameter naming follows proper convention (for example, without space 'Port' should ideally translate into 'Port').
  • Make sure imports are organized correctly.
  • Verify consistency between interface and implementation parts where applicable.

1 change: 0 additions & 1 deletion core/configs/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ type System struct {
Ipv6 string `mapstructure:"ipv6"`
BindAddress string `mapstructure:"bindAddress"`
SSL string `mapstructure:"ssl"`
MasterAddr string `mapstructure:"masterAddr"`
DbCoreFile string `mapstructure:"db_core_file"`
EncryptKey string `mapstructure:"encrypt_key"`
BaseDir string `mapstructure:"base_dir"`
Expand Down
1 change: 1 addition & 0 deletions core/constant/errs.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,5 @@ var (
ErrFreeNodeLimit = "ErrFreeNodeLimit"
ErrNodeBound = "ErrNodeBound"
ErrNodeBind = "ErrNodeBind"
ConnInfoNotMatch = "ConnInfoNotMatch"
)
1 change: 1 addition & 0 deletions core/constant/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const (
StatusWaiting = "Waiting"
StatusPacking = "Packing"
StatusSending = "Sending"
StatusChecking = "Checking"
StatusStarting = "Starting"
StatusHealthy = "Healthy"
StatusUnhealthy = "Unhealthy"
Expand Down
1 change: 1 addition & 0 deletions core/i18n/lang/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ RestartAfterUpgrade: "Start Service After Upgrade"
#add node
TaskAddNode: "Add Node"
GenerateSSLInfo: "Generate Node SSL Information"
ConnInfoNotMatch: "Connection information does not match";
MakeAgentPackage: "Generate Node Installation Package"
SendAgent: "Distribute Node Installation Package"
StartService: "Start Service"
1 change: 1 addition & 0 deletions core/i18n/lang/zh-Hant.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ RestartAfterUpgrade: "升級後啟動服務"
#node create
TaskAddNode: "添加節點"
GenerateSSLInfo: "生成節點 SSL 信息"
ConnInfoNotMatch: "連接信息不匹配";
MakeAgentPackage: "生成節點安裝包"
SendAgent: "下發節點安裝包"
StartService: "啟動服務"
1 change: 1 addition & 0 deletions core/i18n/lang/zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ RestartAfterUpgrade: "升级后启动服务"
#add node
TaskAddNode: "添加节点"
GenerateSSLInfo: "生成节点 SSL 信息"
ConnInfoNotMatch: "连接信息不匹配"
MakeAgentPackage: "生成节点安装包"
SendAgent: "下发节点安装包"
StartService: "启动服务"
5 changes: 0 additions & 5 deletions core/init/hook/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,6 @@ import (

func Init() {
settingRepo := repo.NewISettingRepo()
masterSetting, err := settingRepo.Get(repo.WithByKey("MasterAddr"))
if err != nil {
global.LOG.Errorf("load master addr from setting failed, err: %v", err)
}
global.CONF.System.MasterAddr = masterSetting.Value
portSetting, err := settingRepo.Get(repo.WithByKey("ServerPort"))
if err != nil {
global.LOG.Errorf("load service port from setting failed, err: %v", err)
Expand Down
9 changes: 9 additions & 0 deletions core/utils/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"os/exec"
"strings"
"time"

"github.com/1Panel-dev/1Panel/core/buserr"
Expand All @@ -22,6 +23,14 @@ func SudoHandleCmd() string {
return ""
}

func Which(name string) bool {
stdout, err := Execf("which %s", name)
if err != nil || (len(strings.ReplaceAll(stdout, "\n", "")) == 0) {
return false
}
return true
}

func Execf(cmdStr string, a ...interface{}) (string, error) {
cmd := exec.Command("bash", "-c", fmt.Sprintf(cmdStr, a...))
var stdout, stderr bytes.Buffer
Expand Down
50 changes: 50 additions & 0 deletions core/utils/firewall/firewall.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package firewall

import (
"fmt"

"github.com/1Panel-dev/1Panel/core/utils/cmd"
)

func UpdatePort(oldPort, newPort string) error {
firewalld := cmd.Which("firewalld")
if firewalld {
status, _ := cmd.Exec("LANGUAGE=en_US:en firewall-cmd --state")
isRunning := status == "running\n"
if isRunning {
return firewallUpdatePort(oldPort, newPort)
}
}

ufw := cmd.Which("ufw")
if !ufw {
return nil
}
status, _ := cmd.Exec("LANGUAGE=en_US:en ufw status | grep Status")
isRuning := status == "Status: active\n"
if isRuning {
return ufwUpdatePort(oldPort, newPort)
}
return nil
}

func firewallUpdatePort(oldPort, newPort string) error {
stdout, err := cmd.Execf("firewall-cmd --zone=public --add-port=%s/tcp --permanent", newPort)
if err != nil {
return fmt.Errorf("add (port: %s/tcp) failed, err: %s", newPort, stdout)
}

_, _ = cmd.Execf("firewall-cmd --zone=public --remove-port=%s/tcp --permanent", oldPort)
_, _ = cmd.Exec("firewall-cmd --reload")
return nil
}

func ufwUpdatePort(oldPort, newPort string) error {
stdout, err := cmd.Execf("ufw allow %s", newPort)
if err != nil {
return fmt.Errorf("add (port: %s/tcp) failed, err: %s", newPort, stdout)
}

_, _ = cmd.Execf("ufw delete allow %s", oldPort)
return nil
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are no major issues with the given snippet. The code seems to correctly uses cmd for executing shell commands on different systems based on which package name they have chosen.

However, minor improvements like considering the return types of the executables (return int, not returning an error), and using a const variable rather than hardcoding values for the ports might be beneficial:

// Define constants here if needed

const (
	oldPort  = "80" // Change to your old port here
	newPort  = "443" // Example new port from above example
	... // rest similar
)

func UpdatePort(oldPort string, newPort string) error {
	switch f := &foo{nil}: {f.func1(); }
	return fooUpdateNewOrOldPort(oldPort, newPort)
}

This small change could make the function more readable since it doesn't rely on hard-coded values and can easily maintain multiple ports. Also, this kind of refactoring helps prevent future errors related to changing variables.

14 changes: 5 additions & 9 deletions core/utils/xpack/xpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,12 @@ import (
"github.com/gin-gonic/gin"
)

func Proxy(c *gin.Context, currentNode string) {
return
}
func Proxy(c *gin.Context, currentNode string) { return }

func UpdateGroup(name string, group, newGroup uint) error {
return nil
}
func UpdateGroup(name string, group, newGroup uint) error { return nil }

func CheckBackupUsed(id uint) error {
return nil
}
func CheckBackupUsed(id uint) error { return nil }

func InitAgentRouter(Router *gin.RouterGroup) {}

func UpdateMasterAddr(newAddr string) error { return nil }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are no known abnormalities or issues with the provided code snippet. All function definitions appear to be correctly formatted for Golang and there are no obvious errors in variable declarations or usage patterns. However, due to the limitations of this platform, we can only analyze these files based on their current state at September 1st, 2021. For more detailed analyses, consider checking the Go source files from the time period you specified.

Optimization Suggestions:
As an assistant, I'd recommend optimizing any performance bottlenecks found during analysis of the code. It's also beneficial to follow best coding practices and adhere to standard conventions (e.g., not using "import" statements directly after module imports, ensuring consistent spacing). Additionally, testing thoroughly before implementation is always crucial for reliability.

Keep the code up-to-date as newer versions often improve performance and add features that might not have been included in older releases; regularly update packages used in the project, where applicable.

Loading