Skip to content

Commit

Permalink
feat: runtime 增加删除功能
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengkunwang223 committed Apr 6, 2023
1 parent 64a954d commit 22d9bda
Show file tree
Hide file tree
Showing 19 changed files with 217 additions and 43 deletions.
9 changes: 9 additions & 0 deletions backend/app/api/v1/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,15 @@ func SuccessWithData(ctx *gin.Context, data interface{}) {
ctx.Abort()
}

func SuccessWithOutData(ctx *gin.Context) {
res := dto.Response{
Code: constant.CodeSuccess,
Message: "success",
}
ctx.JSON(http.StatusOK, res)
ctx.Abort()
}

func SuccessWithMsg(ctx *gin.Context, msg string) {
res := dto.Response{
Code: constant.CodeSuccess,
Expand Down
25 changes: 24 additions & 1 deletion backend/app/api/v1/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,28 @@ func (b *BaseApi) CreateRuntime(c *gin.Context) {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
return
}
helper.SuccessWithData(c, nil)
helper.SuccessWithOutData(c)
}

// @Tags Website
// @Summary Delete runtime
// @Description 删除运行环境
// @Accept json
// @Param request body request.RuntimeDelete true "request"
// @Success 200
// @Security ApiKeyAuth
// @Router /runtimes/del [post]
// @x-panel-log {"bodyKeys":["id"],"paramKeys":[],"BeforeFuntions":[],"formatZH":"删除网站 [name]","formatEN":"Delete website [name]"}
func (b *BaseApi) DeleteRuntime(c *gin.Context) {
var req request.RuntimeDelete
if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return
}
err := runtimeService.Delete(req.ID)
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
return
}
helper.SuccessWithOutData(c)
}
4 changes: 4 additions & 0 deletions backend/app/dto/request/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@ type RuntimeCreate struct {
Type string `json:"type"`
Version string `json:"version"`
}

type RuntimeDelete struct {
ID uint `json:"Id"`
}
9 changes: 9 additions & 0 deletions backend/app/repo/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type IRuntimeRepo interface {
Create(ctx context.Context, runtime *model.Runtime) error
Save(runtime *model.Runtime) error
DeleteBy(opts ...DBOption) error
GetFirst(opts ...DBOption) (*model.Runtime, error)
}

func NewIRunTimeRepo() IRuntimeRepo {
Expand Down Expand Up @@ -40,3 +41,11 @@ func (r *RuntimeRepo) Save(runtime *model.Runtime) error {
func (r *RuntimeRepo) DeleteBy(opts ...DBOption) error {
return getDb(opts...).Delete(&model.Runtime{}).Error
}

func (r *RuntimeRepo) GetFirst(opts ...DBOption) (*model.Runtime, error) {
var runtime model.Runtime
if err := getDb(opts...).First(&runtime).Error; err != nil {
return nil, err
}
return &runtime, nil
}
45 changes: 35 additions & 10 deletions backend/app/service/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package service

import (
"context"
"fmt"
"github.com/1Panel-dev/1Panel/backend/app/dto/request"
"github.com/1Panel-dev/1Panel/backend/app/dto/response"
"github.com/1Panel-dev/1Panel/backend/app/model"
Expand All @@ -12,6 +13,8 @@ import (
"github.com/1Panel-dev/1Panel/backend/utils/files"
"github.com/subosito/gotenv"
"path"
"path/filepath"
"time"
)

type RuntimeService struct {
Expand All @@ -20,6 +23,7 @@ type RuntimeService struct {
type IRuntimeService interface {
Page(req request.RuntimeSearch) (int64, []response.RuntimeRes, error)
Create(create request.RuntimeCreate) error
Delete(id uint) error
}

func NewRuntimeService() IRuntimeService {
Expand Down Expand Up @@ -50,21 +54,25 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) error {
if !fileOp.Stat(buildDir) {
return buserr.New(constant.ErrDirNotFound)
}
tempDir := path.Join(constant.RuntimeDir, app.Key)
runtimeDir := path.Join(constant.RuntimeDir, create.Type)
tempDir := filepath.Join(runtimeDir, fmt.Sprintf("%d", time.Now().UnixNano()))
if err := fileOp.CopyDir(buildDir, tempDir); err != nil {
return err
}
oldDir := path.Join(tempDir, "build")
newNameDir := path.Join(tempDir, create.Name)
defer func(defErr *error) {
if defErr != nil {
newNameDir := path.Join(runtimeDir, create.Name)
defer func() {
if err != nil {
_ = fileOp.DeleteDir(newNameDir)
}
}(&err)
}()
if oldDir != newNameDir {
if err := fileOp.Rename(oldDir, newNameDir); err != nil {
return err
}
if err := fileOp.DeleteDir(tempDir); err != nil {
return err
}
}
composeFile, err := fileOp.GetContent(path.Join(newNameDir, "docker-compose.yml"))
if err != nil {
Expand Down Expand Up @@ -95,9 +103,6 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) error {
return err
}
composeService.SetProject(project)
if err := composeService.ComposeBuild(); err != nil {
return err
}
runtime := &model.Runtime{
Name: create.Name,
DockerCompose: string(composeFile),
Expand All @@ -106,9 +111,14 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) error {
Type: create.Type,
Image: create.Image,
Resource: create.Resource,
Status: constant.RuntimeNormal,
Status: constant.RuntimeBuildIng,
Version: create.Version,
}
return runtimeRepo.Create(context.Background(), runtime)
if err := runtimeRepo.Create(context.Background(), runtime); err != nil {
return err
}
go buildRuntime(runtime, composeService)
return nil
}

func (r *RuntimeService) Page(req request.RuntimeSearch) (int64, []response.RuntimeRes, error) {
Expand All @@ -130,3 +140,18 @@ func (r *RuntimeService) Page(req request.RuntimeSearch) (int64, []response.Runt
}
return total, res, nil
}

func (r *RuntimeService) Delete(id uint) error {
runtime, err := runtimeRepo.GetFirst(commonRepo.WithByID(id))
if err != nil {
return err
}
//TODO 校验网站关联
if runtime.Resource == constant.ResourceAppstore {
runtimeDir := path.Join(constant.RuntimeDir, runtime.Type, runtime.Name)
if err := files.NewFileOp().DeleteDir(runtimeDir); err != nil {
return err
}
}
return runtimeRepo.DeleteBy(commonRepo.WithByID(id))
}
18 changes: 18 additions & 0 deletions backend/app/service/runtime_utils.go
Original file line number Diff line number Diff line change
@@ -1 +1,19 @@
package service

import (
"github.com/1Panel-dev/1Panel/backend/app/model"
"github.com/1Panel-dev/1Panel/backend/buserr"
"github.com/1Panel-dev/1Panel/backend/constant"
"github.com/1Panel-dev/1Panel/backend/utils/docker"
)

func buildRuntime(runtime *model.Runtime, service *docker.ComposeService) {
err := service.ComposeBuild()
if err != nil {
runtime.Status = constant.RuntimeError
runtime.Message = buserr.New(constant.ErrImageBuildErr).Error() + ":" + err.Error()
} else {
runtime.Status = constant.RuntimeNormal
}
_ = runtimeRepo.Save(runtime)
}
8 changes: 4 additions & 4 deletions backend/constant/errs.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,9 @@ var (
ErrObjectInUsed = "ErrObjectInUsed"
)

//runtime

// runtime
var (
ErrDirNotFound = "ErrDirNotFound"
ErrFileNotExist = "ErrFileNotExist"
ErrDirNotFound = "ErrDirNotFound"
ErrFileNotExist = "ErrFileNotExist"
ErrImageBuildErr = "ErrImageBuildErr"
)
10 changes: 5 additions & 5 deletions backend/constant/runtime.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package constant

const (
ResourceLocal = "Local"
ResourceAppstore = "Appstore"
ResourceLocal = "local"
ResourceAppstore = "appstore"

RuntimeNormal = "Normal"
RuntimeBuildSuccess = "BuildSuccess"
RuntimeBuildFailed = "BuildFailed"
RuntimeNormal = "normal"
RuntimeError = "error"
RuntimeBuildIng = "building"
)
3 changes: 2 additions & 1 deletion backend/i18n/lang/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,5 @@ ErrObjectInUsed: "This object is in use and cannot be deleted"

#runtime
ErrDirNotFound: "The build folder does not exist! Please check file integrity!"
ErrFileNotExist: "{{ .detail }} file does not exist! Please check source file integrity!"
ErrFileNotExist: "{{ .detail }} file does not exist! Please check source file integrity!"
ErrImageBuildErr: "Image build failed"
3 changes: 2 additions & 1 deletion backend/i18n/lang/zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,5 @@ ErrObjectInUsed: "该对象正被使用,无法删除"

#runtime
ErrDirNotFound: "build 文件夹不存在!请检查文件完整性!"
ErrFileNotExist: "{{ .detail }} 文件不存在!请检查源文件完整性!"
ErrFileNotExist: "{{ .detail }} 文件不存在!请检查源文件完整性!"
ErrImageBuildErr: "镜像 build 失败"
1 change: 1 addition & 0 deletions backend/router/ro_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ func (r *RuntimeRouter) InitRuntimeRouter(Router *gin.RouterGroup) {
{
groupRouter.POST("/search", baseApi.SearchRuntimes)
groupRouter.POST("", baseApi.CreateRuntime)
groupRouter.POST("/del", baseApi.DeleteRuntime)
}
}
4 changes: 4 additions & 0 deletions frontend/src/api/interface/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,8 @@ export namespace Runtime {
appId?: number;
version?: string;
}

export interface RuntimeDelete {
id: number;
}
}
4 changes: 4 additions & 0 deletions frontend/src/api/modules/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ export const SearchRuntimes = (req: Runtime.RuntimeReq) => {
export const CreateRuntime = (req: Runtime.RuntimeCreate) => {
return http.post<any>(`/runtimes`, req);
};

export const DeleteRuntime = (req: Runtime.RuntimeDelete) => {
return http.post<any>(`/runtimes/del`, req);
};
13 changes: 12 additions & 1 deletion frontend/src/lang/modules/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ const message = {
exited: 'Exited',
enabled: 'Enabled',
disabled: 'Disabled',
normal: 'Normal',
building: 'Building',
},
},
menu: {
Expand Down Expand Up @@ -1237,7 +1239,16 @@ const message = {
runtime: {
runtime: 'Runtime',
image: 'Image',
workDir: 'WorkDir',
workDir: 'working directory',
create: 'Create runtime',
name: 'Name',
resource: 'Source',
appstore: 'App Store',
local: 'Local',
app: 'Application',
localHelper: 'The local operating environment needs to be installed by itself',
version: 'Version',
status: 'Status',
},
};

Expand Down
5 changes: 4 additions & 1 deletion frontend/src/lang/modules/zh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ const message = {
installing: '安装中',
enabled: '已启用',
disabled: '已停止',
normal: '正',
building: '制作镜像中',
},
},
menu: {
Expand Down Expand Up @@ -1231,11 +1233,12 @@ const message = {
create: '创建运行环境',
name: '名',
resource: '来',
appStore: '应用商店',
appstore: '应用商店',
local: '本',
app: '应',
localHelper: '本地运行环境需要自行安装',
version: '版',
status: '状',
},
};
export default {
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/utils/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,7 @@ export function isJson(str: string) {
return false;
}
}

export function toLowerCase(str: string) {
return str.toLowerCase();
}
13 changes: 11 additions & 2 deletions frontend/src/views/website/runtime/create/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
@change="changeResource(runtimeCreate.resource)"
>
<el-radio :label="'AppStore'" :value="'AppStore'">
{{ $t('runtime.appStore') }}
{{ $t('runtime.appstore') }}
</el-radio>
<el-radio :label="'Local'" :value="'Local'">
{{ $t('runtime.local') }}
Expand Down Expand Up @@ -135,6 +135,7 @@ const changeResource = (resource: string) => {
runtimeCreate.value.image = '';
} else {
runtimeCreate.value.version = '';
searchApp();
}
};
Expand Down Expand Up @@ -179,7 +180,15 @@ const submit = async (formEl: FormInstance | undefined) => {
});
};
const acceptParams = async () => {
const acceptParams = async (type: string) => {
runtimeCreate.value = {
name: '',
appDetailId: undefined,
image: '',
params: {},
type: type,
resource: 'AppStore',
};
searchApp();
open.value = true;
};
Expand Down
Loading

0 comments on commit 22d9bda

Please sign in to comment.