feat: Openresty 支持非 80 443 端口安装 (#2059)

This commit is contained in:
zhengkunwang 2023-08-24 18:20:15 +08:00 committed by GitHub
parent a3c07dd3d3
commit 684f20a5dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 103 additions and 28 deletions

View File

@ -39,6 +39,8 @@ type AppInstalledCheck struct {
AppInstallID uint `json:"appInstallId"`
ContainerName string `json:"containerName"`
InstallPath string `json:"installPath"`
HttpPort int `json:"httpPort"`
HttpsPort int `json:"httpsPort"`
}
type AppDetailDTO struct {

View File

@ -394,12 +394,14 @@ func (a AppService) Install(ctx context.Context, req request.AppInstallCreate) (
return
}
go func() {
if err = copyData(app, appDetail, appInstall, req); err != nil {
if appInstall.Status == constant.Installing {
defer func() {
if err != nil {
appInstall.Status = constant.Error
appInstall.Message = err.Error()
_ = appInstallRepo.Save(context.Background(), appInstall)
}
_ = appInstallRepo.Save(context.Background(), appInstall)
}()
if err = copyData(app, appDetail, appInstall, req); err != nil {
return
}
if err = runScript(appInstall, "init"); err != nil {

View File

@ -156,6 +156,8 @@ func (a *AppInstallService) CheckExist(key string) (*response.AppInstalledCheck,
res.AppInstallID = appInstall.ID
res.IsExist = true
res.InstallPath = path.Join(constant.AppInstallDir, app.Key, appInstall.Name)
res.HttpPort = appInstall.HttpPort
res.HttpsPort = appInstall.HttpsPort
return res, nil
}

View File

@ -613,8 +613,9 @@ func runScript(appInstall *model.AppInstall, operate string) error {
out, err := cmd.ExecScript(scriptPath, workDir)
if err != nil {
if out != "" {
global.LOG.Errorf("run script %s error %s", scriptPath, out)
return errors.New(out)
errMsg := fmt.Sprintf("run script %s error %s", scriptPath, out)
global.LOG.Error(errMsg)
return errors.New(errMsg)
}
return err
}
@ -907,6 +908,16 @@ func getAppInstallByKey(key string) (model.AppInstall, error) {
return appInstall, nil
}
func getAppInstallPort(key string) (httpPort, httpsPort int, err error) {
install, err := getAppInstallByKey(key)
if err != nil {
return
}
httpPort = install.HttpPort
httpsPort = install.HttpsPort
return
}
func updateToolApp(installed *model.AppInstall) {
tooKey, ok := dto.AppToolMap[installed.App.Key]
if !ok {

View File

@ -1,6 +1,7 @@
package service
import (
"fmt"
"io"
"net/http"
"os"
@ -61,7 +62,15 @@ func (n NginxService) UpdateConfigByScope(req request.NginxConfigUpdate) error {
}
func (n NginxService) GetStatus() (response.NginxStatus, error) {
res, err := http.Get("http://127.0.0.1/nginx_status")
httpPort, _, err := getAppInstallPort(constant.AppOpenresty)
if err != nil {
return response.NginxStatus{}, err
}
url := "http://127.0.0.1/nginx_status"
if httpPort != 80 {
url = fmt.Sprintf("http://127.0.0.1:%v/nginx_status", httpPort)
}
res, err := http.Get(url)
if err != nil {
return response.NginxStatus{}, err
}

View File

@ -22,7 +22,6 @@ import (
"github.com/1Panel-dev/1Panel/backend/app/api/v1/helper"
"github.com/1Panel-dev/1Panel/backend/utils/cmd"
"github.com/1Panel-dev/1Panel/backend/utils/common"
"github.com/1Panel-dev/1Panel/backend/utils/nginx"
"github.com/1Panel-dev/1Panel/backend/utils/nginx/components"
"github.com/1Panel-dev/1Panel/backend/utils/nginx/parser"
@ -175,6 +174,11 @@ func (w WebsiteService) CreateWebsite(create request.WebsiteCreate) (err error)
if exist, _ := websiteDomainRepo.GetBy(websiteDomainRepo.WithDomain(create.PrimaryDomain)); len(exist) > 0 {
return buserr.New(constant.ErrDomainIsExist)
}
nginxInstall, err := getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return err
}
defaultHttpPort := nginxInstall.HttpPort
defaultDate, _ := time.Parse(constant.DateLayout, constant.DefaultDate)
website := &model.Website{
@ -291,13 +295,13 @@ func (w WebsiteService) CreateWebsite(create request.WebsiteCreate) (err error)
}
var domains []model.WebsiteDomain
domains = append(domains, model.WebsiteDomain{Domain: website.PrimaryDomain, Port: 80})
domains = append(domains, model.WebsiteDomain{Domain: website.PrimaryDomain, Port: defaultHttpPort})
otherDomainArray := strings.Split(create.OtherDomains, "\n")
for _, domain := range otherDomainArray {
if domain == "" {
continue
}
domainModel, err := getDomain(domain)
domainModel, err := getDomain(domain, defaultHttpPort)
if err != nil {
return err
}
@ -445,11 +449,11 @@ func (w WebsiteService) CreateWebsiteDomain(create request.WebsiteDomainCreate)
ports []int
domains []string
)
if create.Port != 80 {
if common.ScanPort(create.Port) {
return domainModel, buserr.WithDetail(constant.ErrPortInUsed, create.Port, nil)
}
httpPort, _, err := getAppInstallPort(constant.AppOpenresty)
if err != nil {
return domainModel, err
}
website, err := websiteRepo.GetFirst(commonRepo.WithByID(create.WebsiteID))
if err != nil {
return domainModel, err
@ -466,7 +470,7 @@ func (w WebsiteService) CreateWebsiteDomain(create request.WebsiteDomainCreate)
Port: create.Port,
WebsiteID: create.WebsiteID,
}
if create.Port != 80 {
if create.Port != httpPort {
go func() {
_ = OperateFirewallPort(nil, []int{create.Port})
}()
@ -652,7 +656,12 @@ func (w WebsiteService) OpWebsiteHTTPS(ctx context.Context, req request.WebsiteH
if !req.Enable {
website.Protocol = constant.ProtocolHTTP
website.WebsiteSSLID = 0
if err := deleteListenAndServerName(website, []string{"443", "[::]:443"}, []string{}); err != nil {
_, httpsPort, err := getAppInstallPort(constant.AppOpenresty)
if err != nil {
return nil, err
}
httpsPortStr := strconv.Itoa(httpsPort)
if err := deleteListenAndServerName(website, []string{httpsPortStr, "[::]:" + httpsPortStr}, []string{}); err != nil {
return nil, err
}
nginxParams := getNginxParamsFromStaticFile(dto.SSL, nil)
@ -1007,12 +1016,17 @@ func (w WebsiteService) ChangeDefaultServer(id uint) error {
if err != nil {
return err
}
httpPort, httpsPort, err := getAppInstallPort(constant.AppOpenresty)
if err != nil {
return err
}
var changeParams []dto.NginxParam
for _, param := range params {
paramLen := len(param.Params)
bind := param.Params[0]
var newParam []string
if bind == "80" || bind == "443" || bind == "[::]:80" || bind == "[::]:443" {
if bind == strconv.Itoa(httpPort) || bind == strconv.Itoa(httpsPort) || bind == "[::]:"+strconv.Itoa(httpPort) || bind == "[::]:"+strconv.Itoa(httpsPort) {
if param.Params[paramLen-1] == components.DefaultServer {
newParam = param.Params
} else {

View File

@ -115,7 +115,10 @@ func (w WebsiteSSLService) Create(create request.WebsiteSSLCreate) (request.Webs
if err != nil {
return request.WebsiteSSLCreate{}, err
}
if err := client.UseHTTP(path.Join(constant.AppInstallDir, constant.AppOpenresty, appInstall.Name, "root")); err != nil {
if appInstall.HttpPort != 80 {
return request.WebsiteSSLCreate{}, buserr.WithDetail("ErrOpenrestyPort", appInstall.HttpPort, nil)
}
if err := client.UseHTTP(path.Join(appInstall.GetPath(), "root")); err != nil {
return res, err
}
websiteSSL.AutoRenew = create.AutoRenew

View File

@ -23,12 +23,12 @@ import (
"gorm.io/gorm"
)
func getDomain(domainStr string) (model.WebsiteDomain, error) {
func getDomain(domainStr string, defaultPort int) (model.WebsiteDomain, error) {
domain := model.WebsiteDomain{}
domainArray := strings.Split(domainStr, ":")
if len(domainArray) == 1 {
domain.Domain = domainArray[0]
domain.Port = 80
domain.Port = defaultPort
return domain, nil
}
if len(domainArray) > 1 {
@ -186,6 +186,7 @@ func configDefaultNginx(website *model.Website, domains []model.WebsiteDomain, a
return errors.New("nginx config is not valid")
}
server := servers[0]
server.DeleteListen("80")
var serverNames []string
for _, domain := range domains {
serverNames = append(serverNames, domain.Domain)
@ -378,27 +379,33 @@ func applySSL(website model.Website, websiteSSL model.WebsiteSSL, req request.We
}
config := nginxFull.SiteConfig.Config
server := config.FindServers()[0]
server.UpdateListen("443", website.DefaultServer, "ssl", "http2")
httpPort := strconv.Itoa(nginxFull.Install.HttpPort)
httpsPort := strconv.Itoa(nginxFull.Install.HttpsPort)
httpPortIPV6 := "[::]:" + httpPort
httpsPortIPV6 := "[::]:" + httpsPort
server.UpdateListen(httpsPort, website.DefaultServer, "ssl", "http2")
if website.IPV6 {
server.UpdateListen("[::]:443", website.DefaultServer, "ssl", "http2")
server.UpdateListen(httpsPortIPV6, website.DefaultServer, "ssl", "http2")
}
switch req.HttpConfig {
case constant.HTTPSOnly:
server.RemoveListenByBind("80")
server.RemoveListenByBind("[::]:80")
server.RemoveListenByBind(httpPort)
server.RemoveListenByBind(httpPortIPV6)
server.RemoveDirective("if", []string{"($scheme"})
case constant.HTTPToHTTPS:
server.UpdateListen("80", website.DefaultServer)
server.UpdateListen(httpPort, website.DefaultServer)
if website.IPV6 {
server.UpdateListen("[::]:80", website.DefaultServer)
server.UpdateListen(httpPortIPV6, website.DefaultServer)
}
server.AddHTTP2HTTPS()
case constant.HTTPAlso:
server.UpdateListen("80", website.DefaultServer)
server.UpdateListen(httpPort, website.DefaultServer)
server.RemoveDirective("if", []string{"($scheme"})
if website.IPV6 {
server.UpdateListen("[::]:80", website.DefaultServer)
server.UpdateListen(httpPortIPV6, website.DefaultServer)
}
}

View File

@ -75,6 +75,7 @@ ErrSSLKeyNotFound: 'The private key file does not exist'
ErrSSLCertificateNotFound: 'The certificate file does not exist'
ErrSSLKeyFormat: 'Private key file verification error'
ErrSSLCertificateFormat: 'Certificate file format error, please use pem format'
ErrOpenrestyPort: 'The default port of openresty is {{ .detail }}, HTTP mode cannot be used!'
#mysql
ErrUserIsExist: "The current user already exists. Please enter a new user"

View File

@ -75,6 +75,7 @@ ErrSSLKeyNotFound: '私鑰文件不存在'
ErrSSLCertificateNotFound: '證書文件不存在'
ErrSSLKeyFormat: '私鑰文件校驗錯誤'
ErrSSLCertificateFormat: '證書文件格式錯誤,請使用 pem 格式'
ErrOpenrestyPort: 'openresty 默認端口為 {{ .detail }},無法使用 HTTP 模式!'
#mysql
ErrUserIsExist: "當前用戶已存在,請重新輸入"

View File

@ -75,6 +75,7 @@ ErrSSLKeyNotFound: '私钥文件不存在'
ErrSSLCertificateNotFound: '证书文件不存在'
ErrSSLKeyFormat: '私钥文件校验失败'
ErrSSLCertificateFormat: '证书文件格式错误,请使用 pem 格式'
ErrOpenrestyPort: 'openresty 默认端口为 {{ .detail }},无法使用 HTTP 模式!'
#mysql
ErrUserIsExist: "当前用户已存在,请重新输入"

View File

@ -144,7 +144,7 @@ func ExecWithCheck(name string, a ...string) (string, error) {
func ExecScript(scriptPath, workDir string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
cmd := exec.Command("/bin/sh", scriptPath)
cmd := exec.Command("bash", scriptPath)
cmd.Dir = workDir
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout

View File

@ -133,6 +133,8 @@ export namespace App {
appInstallId: number;
containerName: string;
installPath: string;
httpPort: number;
httpsPort: number;
}
export interface DatabaseConnInfo {

View File

@ -41,6 +41,12 @@
{{ $t('commons.button.set') }}
</el-button>
</span>
<span class="warn" v-if="key === 'openresty' && httpPort != 80">
<el-alert class="helper" type="error" :closable="false">
{{ $t('website.openrestryHelper', [httpPort]) }}
</el-alert>
</span>
</div>
</el-card>
</div>
@ -95,6 +101,7 @@ let operateReq = reactive({
operate: '',
});
let refresh = ref(1);
const httpPort = ref(0);
const em = defineEmits(['setting', 'isExist', 'before', 'update:loading', 'update:maskShow']);
const setting = () => {
@ -111,6 +118,7 @@ const onCheck = async () => {
data.value = res.data;
em('isExist', res.data);
operateReq.installId = res.data.appInstallId;
httpPort.value = res.data.httpPort;
refresh.value++;
})
.catch(() => {
@ -166,3 +174,12 @@ onMounted(() => {
onCheck();
});
</script>
<style lang="scss">
.warn {
margin-left: 20px;
.helper {
display: inline;
}
}
</style>

View File

@ -1496,6 +1496,7 @@ const message = {
changeVersion: 'Switch version',
retainConfig: 'Whether to keep php-fpm.conf and php.ini files',
runDirHelper2: 'Please ensure that the secondary running directory is under the index directory',
openrestryHelper: 'The default port of OpenResty is {0}, which affects website domain name access',
},
php: {
short_open_tag: 'Short tag support',

View File

@ -1426,6 +1426,7 @@ const message = {
changeVersion: '切換版本',
retainConfig: '是否保留 php-fpm.conf php.ini 文件',
runDirHelper2: '請確保二級運行目錄位於 index 目錄下',
openrestryHelper: 'OpenResty默認端口為 {0}影響網站域名訪問',
},
php: {
short_open_tag: '短標簽支持',

View File

@ -1426,6 +1426,7 @@ const message = {
changeVersion: '切换版本',
retainConfig: '是否保留 php-fpm.conf php.ini 文件',
runDirHelper2: '请确保二级运行目录位于 index 目录下',
openrestryHelper: 'OpenResty默认端口为 {0}影响网站域名访问',
},
php: {
short_open_tag: '短标签支持',