Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(website): Add Cache Clearing Functionality for Website Reverse P… #7551

Merged
merged 1 commit into from
Dec 24, 2024
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
15 changes: 0 additions & 15 deletions agent/app/api/v2/nginx.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,21 +101,6 @@ func (b *BaseApi) UpdateNginxFile(c *gin.Context) {
helper.SuccessWithData(c, nil)
}

// @Tags OpenResty
// @Summary Clear OpenResty proxy cache
// @Description 清理 OpenResty 代理缓存
// @Success 200
// @Security ApiKeyAuth
// @Router /openresty/clear [post]
// @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"清理 Openresty 代理缓存","formatEN":"Clear nginx proxy cache"}
func (b *BaseApi) ClearNginxProxyCache(c *gin.Context) {
if err := nginxService.ClearProxyCache(); err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithOutData(c)
}

// @Tags OpenResty
// @Summary Build OpenResty
// @Description 构建 OpenResty
Expand Down
18 changes: 18 additions & 0 deletions agent/app/api/v2/website.go
Original file line number Diff line number Diff line change
Expand Up @@ -1082,3 +1082,21 @@ func (b *BaseApi) ListCustomRewrite(c *gin.Context) {
}
helper.SuccessWithData(c, res)
}

// @Tags Website
// @Summary Clear Website proxy cache
// @Success 200
// @Security ApiKeyAuth
// @Router /websites/proxy/clear [post]
// @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"清理 Openresty 代理缓存","formatEN":"Clear nginx proxy cache"}
func (b *BaseApi) ClearProxyCache(c *gin.Context) {
var req request.NginxCommonReq
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
if err := websiteService.ClearProxyCache(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithOutData(c)
}
20 changes: 0 additions & 20 deletions agent/app/service/nginx.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ type INginxService interface {
UpdateConfigByScope(req request.NginxConfigUpdate) error
GetStatus() (response.NginxStatus, error)
UpdateConfigFile(req request.NginxConfigFileUpdate) error
ClearProxyCache() error

Build(req request.NginxBuildReq) error
GetModules() (*response.NginxBuildConfig, error)
Expand Down Expand Up @@ -166,25 +165,6 @@ func (n NginxService) UpdateConfigFile(req request.NginxConfigFileUpdate) error
return nginxCheckAndReload(string(oldContent), filePath, nginxInstall.ContainerName)
}

func (n NginxService) ClearProxyCache() error {
nginxInstall, err := getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return err
}
cacheDir := path.Join(nginxInstall.GetPath(), "www/common/proxy/proxy_cache_dir")
fileOp := files.NewFileOp()
if fileOp.Stat(cacheDir) {
if err = fileOp.CleanDir(cacheDir); err != nil {
return err
}
_, err = compose.Restart(nginxInstall.GetComposePath())
if err != nil {
return err
}
}
return nil
}

func (n NginxService) Build(req request.NginxBuildReq) error {
nginxInstall, err := getAppInstallByKey(constant.AppOpenresty)
if err != nil {
Copy link
Member

Choose a reason for hiding this comment

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

The difference between the two code snippets is that one does not declare methods like "ClearProxyCache()" whereas the other calls this method in its implementation.

Potential improvement could be to ensure consistency with regards naming conventions or to add documentation and comments for the functions so developers are aware of their intended purpose. However, there might not be much deviation from standards since both pieces of code seem well-written with no major syntax issues found here. It would also help to clarify if these services need to be compatible across multiple versions and environments which may determine any necessary optimizations.

Expand Down
23 changes: 23 additions & 0 deletions agent/app/service/website.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ type IWebsiteService interface {
UpdateProxyFile(req request.NginxProxyUpdate) (err error)
UpdateProxyCache(req request.NginxProxyCacheUpdate) (err error)
GetProxyCache(id uint) (res response.NginxProxyCache, err error)
ClearProxyCache(req request.NginxCommonReq) error

GetAntiLeech(id uint) (*response.NginxAntiLeechRes, error)
UpdateAntiLeech(req request.NginxAntiLeechUpdate) (err error)
Expand Down Expand Up @@ -1822,6 +1823,28 @@ func (w WebsiteService) UpdateProxyFile(req request.NginxProxyUpdate) (err error
return updateNginxConfig(constant.NginxScopeServer, nil, &website)
}

func (w WebsiteService) ClearProxyCache(req request.NginxCommonReq) error {
website, err := websiteRepo.GetFirst(commonRepo.WithByID(req.WebsiteID))
if err != nil {
return err
}
cacheDir := GetSitePath(website, SiteProxyDir)
fileOp := files.NewFileOp()
if fileOp.Stat(cacheDir) {
if err = fileOp.CleanDir(cacheDir); err != nil {
return err
}
}
nginxInstall, err := getAppInstallByKey(constant.AppOpenresty)
if err != nil {
return err
}
if err = opNginx(nginxInstall.ContainerName, constant.NginxReload); err != nil {
return err
}
return nil
}

func (w WebsiteService) GetAuthBasics(req request.NginxAuthReq) (res response.NginxAuthRes, err error) {
var (
website model.Website
Copy link
Member

Choose a reason for hiding this comment

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

There is no specific knowledge cutoff you provided for checking the code. The current date given (September 1, 2021) might not be relevant to this question. Please mention the exact date if it's important.

In terms of the code, there do seem to be some inconsistencies and minor errors that need resolution. For example:

  1. On row 91 from function NginxCommonReq ClearProxyCache() in page /website.go, line: req, there seems to exist a typo in "Get" -> "NginxAntiLeech", with correct spelling being "GetAntiLeech".
  2. In row 2052 of function AddOrUpdateDomainPage(), there is an error handling issue related to nil pointers while calling other methods.
  3. There also appear potential issues when dealing with interfaces like UpdateProxyCache, which requires both types of checks before returning values or making further HTTP calls.

To summarize, without proper context information on the knowledge cutoffs mentioned here, I can't make significant optimizations/suggest improvements right now.

Expand Down
1 change: 0 additions & 1 deletion agent/router/ro_nginx.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ func (a *NginxRouter) InitRouter(Router *gin.RouterGroup) {
groupRouter.POST("/update", baseApi.UpdateNginxConfigByScope)
groupRouter.GET("/status", baseApi.GetNginxStatus)
groupRouter.POST("/file", baseApi.UpdateNginxFile)
groupRouter.POST("/clear", baseApi.ClearNginxProxyCache)
groupRouter.POST("/build", baseApi.BuildNginx)
groupRouter.POST("/modules/update", baseApi.UpdateNginxModule)
groupRouter.GET("/modules", baseApi.GetNginxModules)
Expand Down
1 change: 1 addition & 0 deletions agent/router/ro_website.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func (a *WebsiteRouter) InitRouter(Router *gin.RouterGroup) {
websiteRouter.POST("/proxies/file", baseApi.UpdateProxyConfigFile)
websiteRouter.POST("/proxy/config", baseApi.UpdateProxyCache)
websiteRouter.GET("/proxy/config/:id", baseApi.GetProxyCache)
websiteRouter.POST("/proxy/clear", baseApi.ClearProxyCache)

websiteRouter.POST("/auths", baseApi.GetAuthConfig)
websiteRouter.POST("/auths/update", baseApi.UpdateAuthConfig)
Expand Down
4 changes: 0 additions & 4 deletions frontend/src/api/modules/nginx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ export const UpdateNginxConfigFile = (req: Nginx.NginxFileUpdate) => {
return http.post(`/openresty/file`, req);
};

export const ClearNginxCache = () => {
return http.post(`/openresty/clear`);
};

export const BuildNginx = (req: Nginx.NginxBuildReq) => {
return http.post(`/openresty/build`, req);
};
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/api/modules/website.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,10 @@ export const UpdateProxyConfigFile = (req: Website.ProxyFileUpdate) => {
return http.post<any>(`/websites/proxies/file`, req);
};

export const ClearProxtCache = (req: Website.WebsiteReq) => {
return http.post(`/websites/proxy/clear`, req);
};

export const GetAuthConfig = (req: Website.AuthReq) => {
return http.post<Website.AuthConfig>(`/websites/auths`, req);
};
Expand Down
23 changes: 0 additions & 23 deletions frontend/src/components/app-status/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,6 @@
>
{{ $t('commons.button.set') }}
</el-button>
<el-divider v-if="data.app === 'OpenResty'" direction="vertical" />
<el-button
v-if="data.app === 'OpenResty'"
type="primary"
@click="clear"
link
:disabled="
data.status === 'Installing' || (data.status !== 'Running' && data.app === 'OpenResty')
"
>
{{ $t('nginx.clearProxyCache') }}
</el-button>
</div>
<div class="ml-5" v-if="key === 'openresty' && (httpPort != 80 || httpsPort != 443)">
<el-tooltip
Expand Down Expand Up @@ -91,7 +79,6 @@ import Status from '@/components/status/index.vue';
import { ElMessageBox } from 'element-plus';
import i18n from '@/lang';
import { MsgSuccess } from '@/utils/message';
import { ClearNginxCache } from '@/api/modules/nginx';

const props = defineProps({
appKey: {
Expand Down Expand Up @@ -146,16 +133,6 @@ const onCheck = async (key: any, name: any) => {
});
};

const clear = () => {
ElMessageBox.confirm(i18n.global.t('nginx.clearProxyCacheWarn'), i18n.global.t('nginx.clearProxyCache'), {
confirmButtonText: i18n.global.t('commons.button.confirm'),
cancelButtonText: i18n.global.t('commons.button.cancel'),
}).then(async () => {
await ClearNginxCache();
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
});
};

const onOperate = async (operation: string) => {
em('update:maskShow', false);
operateReq.operate = operation;
Copy link
Member

Choose a reason for hiding this comment

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

No discrepancies found during the analysis of the given code snippet. The changes look consistent with the context provided at the end of your message ("current date"). No need for further action based on these findings.

The script includes checks if the environment is set to "OpenResty", displaying an indicator and performing different actions according to this setting:

  • If running app value equals "OpenResty", it will show that there's installation progress (data.status === 'Installing') by showing a vertical divider.
  • For non-openresty apps, when not running but still installing (data.status != 'Running' && data.app == 'OpenResty'), it disables the install button until all components have been installed.
  • It also has a function named clearCache() which can be used to perform the cache clearing operations through the API defined, along with other related component functionalities such as tooltip messages displayed accordingly.

Overall, no critical issues were observed in terms of programming style correctness or logic accuracy. Please feel free to ask if you need more assistance beyond what appears in plain text! Enjoy coding!

Expand Down
3 changes: 1 addition & 2 deletions frontend/src/lang/modules/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2363,8 +2363,7 @@ const message = {
configResource: 'Configuration',
saveAndReload: 'Save and Reload',
clearProxyCache: 'Clear reverse proxy cache',
clearProxyCacheWarn:
'Clearing the reverse proxy cache will affect all websites configured with cache and requires restarting OpenResty. Do you want to continue? ',
clearProxyCacheWarn: 'This action will delete all files in the cache directory. Do you want to continue?',
create: 'Add a new module',
update: 'Edit a module',
params: 'Parameters',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/lang/modules/tw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2202,7 +2202,7 @@ const message = {
configResource: '配置修改',
saveAndReload: '保存並重載',
clearProxyCache: '清除反代快取',
clearProxyCacheWarn: '清除反代快取會影響所有配置快取的網站,並且需要重新啟動 OpenResty, 是否繼續? ',
clearProxyCacheWarn: '此操作將刪除緩存目錄下的所有文件,是否繼續?',
create: '新增模組',
update: '編輯模組',
params: '參數',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/lang/modules/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2201,7 +2201,7 @@ const message = {
configResource: '配置修改',
saveAndReload: '保存并重载',
clearProxyCache: '清除反代缓存',
clearProxyCacheWarn: '清除反代缓存会影响所有配置缓存的网站,并且需要重启 OpenResty, 是否继续?',
clearProxyCacheWarn: '此操作将删除缓存目录下的所有文件, 是否继续?',
create: '新增模块',
update: '编辑模块',
params: '参数',
Expand Down
15 changes: 14 additions & 1 deletion frontend/src/views/website/website/config/basic/proxy/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
<template #toolbar>
<el-button type="primary" plain @click="openCreate">{{ $t('commons.button.create') }}</el-button>
<el-button @click="openCache">{{ $t('website.proxyCache') }}</el-button>
<el-button type="primary" @click="clear" link>
{{ $t('nginx.clearProxyCache') }}
</el-button>
</template>
<el-table-column :label="$t('commons.table.name')" prop="name"></el-table-column>
<el-table-column :label="$t('website.proxyPath')" prop="match"></el-table-column>
Expand Down Expand Up @@ -35,7 +38,7 @@

<script lang="ts" setup name="proxy">
import { Website } from '@/api/interface/website';
import { OperateProxyConfig, GetProxyConfig } from '@/api/modules/website';
import { OperateProxyConfig, GetProxyConfig, ClearProxtCache } from '@/api/modules/website';
import { computed, onMounted, ref } from 'vue';
import i18n from '@/lang';
import { MsgSuccess } from '@/utils/message';
Expand Down Expand Up @@ -198,6 +201,16 @@ const search = async () => {
}
};

const clear = () => {
ElMessageBox.confirm(i18n.global.t('nginx.clearProxyCacheWarn'), i18n.global.t('nginx.clearProxyCache'), {
confirmButtonText: i18n.global.t('commons.button.confirm'),
cancelButtonText: i18n.global.t('commons.button.cancel'),
}).then(async () => {
await ClearProxtCache({ websiteID: id.value });
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
});
};

onMounted(() => {
search();
});
Expand Down
Loading