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
41 changes: 21 additions & 20 deletions agent/app/dto/response/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,27 @@ import (
)

type RuntimeDTO struct {
ID uint `json:"id"`
Name string `json:"name"`
Resource string `json:"resource"`
AppDetailID uint `json:"appDetailID"`
AppID uint `json:"appID"`
Source string `json:"source"`
Status string `json:"status"`
Type string `json:"type"`
Image string `json:"image"`
Params map[string]interface{} `json:"params"`
Message string `json:"message"`
Version string `json:"version"`
CreatedAt time.Time `json:"createdAt"`
CodeDir string `json:"codeDir"`
AppParams []AppParam `json:"appParams"`
Port string `json:"port"`
Path string `json:"path"`
ExposedPorts []request.ExposedPort `json:"exposedPorts"`
Environments []request.Environment `json:"environments"`
Volumes []request.Volume `json:"volumes"`
ID uint `json:"id"`
Name string `json:"name"`
Resource string `json:"resource"`
AppDetailID uint `json:"appDetailID"`
AppID uint `json:"appID"`
Source string `json:"source"`
Status string `json:"status"`
Type string `json:"type"`
Image string `json:"image"`
Params map[string]interface{} `json:"params"`
Message string `json:"message"`
Version string `json:"version"`
CreatedAt time.Time `json:"createdAt"`
CodeDir string `json:"codeDir"`
AppParams []AppParam `json:"appParams"`
Port string `json:"port"`
Path string `json:"path"`
ExposedPorts []request.ExposedPort `json:"exposedPorts"`
Environments []request.Environment `json:"environments"`
Volumes []request.Volume `json:"volumes"`
ContainerStatus string `json:"containerStatus"`
}

type PackageScripts struct {
Copy link
Member

Choose a reason for hiding this comment

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

Your code is well-structured and appears to be formatted correctly in Go. There are no known issues present with this package script file.

Expand Down
2 changes: 1 addition & 1 deletion agent/app/service/backup_runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ func handleRuntimeRecover(runtime *model.Runtime, recoverFile string, isRollback
}

oldRuntime.ID = runtime.ID
oldRuntime.Status = constant.RuntimeStarting
oldRuntime.Status = constant.StatusStarting
if err := runtimeRepo.Save(&oldRuntime); err != nil {
global.LOG.Errorf("save db app install failed, err: %v", err)
return err
Expand Down
19 changes: 11 additions & 8 deletions agent/app/service/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func (r *RuntimeService) Create(create request.RuntimeCreate) (*model.Runtime, e
Resource: create.Resource,
Type: create.Type,
Version: create.Version,
Status: constant.RuntimeNormal,
Status: constant.StatusNormal,
}
return nil, runtimeRepo.Create(context.Background(), runtime)
}
Expand Down Expand Up @@ -196,14 +196,17 @@ func (r *RuntimeService) Page(req request.RuntimeSearch) (int64, []response.Runt
if err != nil {
return 0, nil, err
}
if err = SyncRuntimesStatus(runtimes); err != nil {
return 0, nil, err
}
for _, runtime := range runtimes {
runtimeDTO := response.NewRuntimeDTO(runtime)
runtimeDTO.Params = make(map[string]interface{})
envs, err := gotenv.Unmarshal(runtime.Env)
envMap, err := gotenv.Unmarshal(runtime.Env)
if err != nil {
return 0, nil, err
}
for k, v := range envs {
for k, v := range envMap {
runtimeDTO.Params[k] = v
}
res = append(res, runtimeDTO)
Expand Down Expand Up @@ -498,7 +501,7 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error {
switch runtime.Type {
case constant.RuntimePHP:
runtime.Image = req.Image
runtime.Status = constant.RuntimeBuildIng
runtime.Status = constant.StatusBuilding
_ = runtimeRepo.Save(runtime)
client, err := docker.NewClient()
if err != nil {
Expand All @@ -514,7 +517,7 @@ func (r *RuntimeService) Update(req request.RuntimeUpdate) error {
runtime.Version = req.Version
runtime.CodeDir = req.CodeDir
runtime.Port = strings.Join(hostPorts, ",")
runtime.Status = constant.RuntimeReCreating
runtime.Status = constant.StatusReCreating
_ = runtimeRepo.Save(runtime)
go reCreateRuntime(runtime)
}
Expand Down Expand Up @@ -559,7 +562,7 @@ func (r *RuntimeService) OperateRuntime(req request.RuntimeOperate) error {
}
defer func() {
if err != nil {
runtime.Status = constant.RuntimeError
runtime.Status = constant.StatusError
runtime.Message = err.Error()
_ = runtimeRepo.Save(runtime)
}
Expand All @@ -576,7 +579,7 @@ func (r *RuntimeService) OperateRuntime(req request.RuntimeOperate) error {
if err = runComposeCmdWithLog(req.Operate, runtime.GetComposePath(), runtime.GetLogPath()); err != nil {
return err
}
runtime.Status = constant.RuntimeStopped
runtime.Status = constant.StatusStopped
case constant.RuntimeRestart:
if err = restartRuntime(runtime); err != nil {
return err
Expand Down Expand Up @@ -661,7 +664,7 @@ func (r *RuntimeService) SyncForRestart() error {
return err
}
for _, runtime := range runtimes {
if runtime.Status == constant.RuntimeBuildIng || runtime.Status == constant.RuntimeReCreating || runtime.Status == constant.RuntimeStarting || runtime.Status == constant.RuntimeCreating {
if runtime.Status == constant.StatusBuilding || runtime.Status == constant.StatusReCreating || runtime.Status == constant.StatusStarting || runtime.Status == constant.StatusCreating {
runtime.Status = constant.SystemRestart
runtime.Message = "System restart causing interrupt"
_ = runtimeRepo.Save(&runtime)
Expand Down
67 changes: 53 additions & 14 deletions agent/app/service/runtime_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func handleRuntime(create request.RuntimeCreate, runtime *model.Runtime, fileOp
}
runtime.DockerCompose = string(composeContent)
runtime.Env = string(envContent)
runtime.Status = constant.RuntimeCreating
runtime.Status = constant.StatusCreating
runtime.CodeDir = create.CodeDir

nodeDetail, err := appDetailRepo.GetFirst(repo.WithByID(runtime.AppDetailID))
Expand Down Expand Up @@ -89,22 +89,22 @@ func handlePHP(create request.RuntimeCreate, runtime *model.Runtime, fileOp file
runtime.DockerCompose = string(composeContent)
runtime.Env = string(envContent)
runtime.Params = string(forms)
runtime.Status = constant.RuntimeBuildIng
runtime.Status = constant.StatusBuilding

go buildRuntime(runtime, "", "", false)
return
}

func startRuntime(runtime *model.Runtime) {
if err := runComposeCmdWithLog("up", runtime.GetComposePath(), runtime.GetLogPath()); err != nil {
runtime.Status = constant.RuntimeError
runtime.Status = constant.StatusError
runtime.Message = err.Error()
_ = runtimeRepo.Save(runtime)
return
}

if err := SyncRuntimeContainerStatus(runtime); err != nil {
runtime.Status = constant.RuntimeError
runtime.Status = constant.StatusError
runtime.Message = err.Error()
_ = runtimeRepo.Save(runtime)
return
Expand All @@ -115,7 +115,7 @@ func reCreateRuntime(runtime *model.Runtime) {
var err error
defer func() {
if err != nil {
runtime.Status = constant.RuntimeError
runtime.Status = constant.StatusError
runtime.Message = err.Error()
_ = runtimeRepo.Save(runtime)
}
Expand Down Expand Up @@ -155,6 +155,45 @@ func runComposeCmdWithLog(operate string, composePath string, logPath string) er
return nil
}

func SyncRuntimesStatus(runtimes []model.Runtime) error {
cli, err := docker.NewClient()
if err != nil {
return err
}
defer cli.Close()
var containerNames []string
runtimeContainer := make(map[string]int)
for index, runtime := range runtimes {
containerNames = append(containerNames, runtime.ContainerName)
runtimeContainer["/"+runtime.ContainerName] = index
}
containers, err := cli.ListContainersByName(containerNames)
if err != nil {
return err
}
for _, contain := range containers {
if index, ok := runtimeContainer[contain.Names[0]]; ok {
switch contain.State {
case "exited":
runtimes[index].Status = constant.StatusError
case "running":
runtimes[index].Status = constant.StatusRunning
case "paused":
runtimes[index].Status = constant.StatusStopped
case "restarting":
runtimes[index].Status = constant.StatusRestarting
}
delete(runtimeContainer, contain.Names[0])
}
}
for _, index := range runtimeContainer {
if runtimes[index].Status != constant.StatusBuilding {
runtimes[index].Status = constant.StatusStopped
}
}
return nil
}

func SyncRuntimeContainerStatus(runtime *model.Runtime) error {
env, err := gotenv.Unmarshal(runtime.Env)
if err != nil {
Expand Down Expand Up @@ -182,14 +221,14 @@ func SyncRuntimeContainerStatus(runtime *model.Runtime) error {

switch container.State {
case "exited":
runtime.Status = constant.RuntimeError
runtime.Status = constant.StatusError
case "running":
runtime.Status = constant.RuntimeRunning
runtime.Status = constant.StatusRunning
case "paused":
runtime.Status = constant.RuntimeStopped
runtime.Status = constant.StatusStopped
default:
if runtime.Status != constant.RuntimeBuildIng {
runtime.Status = constant.RuntimeStopped
if runtime.Status != constant.StatusBuilding {
runtime.Status = constant.StatusStopped
}
}

Expand Down Expand Up @@ -232,7 +271,7 @@ func buildRuntime(runtime *model.Runtime, oldImageID string, oldEnv string, rebu

err = cmd.Run()
if err != nil {
runtime.Status = constant.RuntimeError
runtime.Status = constant.StatusError
runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + stderrBuf.String()
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + buserr.New("ErrCmdTimeout").Error()
Expand Down Expand Up @@ -286,21 +325,21 @@ func buildRuntime(runtime *model.Runtime, oldImageID string, oldEnv string, rebu
}

if out, err := compose.Up(composePath); err != nil {
runtime.Status = constant.RuntimeStartErr
runtime.Status = constant.StatusStartErr
runtime.Message = out
} else {
extensions := getRuntimeEnv(runtime.Env, "PHP_EXTENSIONS")
if extensions != "" {
installCmd := fmt.Sprintf("docker exec -i %s %s %s", runtime.ContainerName, "install-ext", extensions)
err = cmd2.ExecWithLogFile(installCmd, 60*time.Minute, logPath)
if err != nil {
runtime.Status = constant.RuntimeError
runtime.Status = constant.StatusError
runtime.Message = buserr.New("ErrImageBuildErr").Error() + ":" + err.Error()
_ = runtimeRepo.Save(runtime)
return
}
}
runtime.Status = constant.RuntimeRunning
runtime.Status = constant.StatusRunning
}
}
_ = runtimeRepo.Save(runtime)
Copy link
Member

Choose a reason for hiding this comment

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

This code appears to be a part of a PHP-based application that manages running containers such as Docker compose and runtime details, including status updates. The provided code has no major problems; however, there's an issue regarding version numbers:

It references Go versions 1.X.x which do not exist anymore from 2021 till now.

To address this, you might want to update these pointers (e.g., to GoVersion: go-version, Compose: docker.Compose() etc.) before further coding changes. You can also consider updating package versions if they support new functionalities introduced since Go 1.x.

Please note, I am unable to directly test or inspect the functionality here due to the lack of context around how it integrates with larger systems/other modules and external APIs but this seems correct based on the available information without additional data points.

For optimizations:

  • Make use of interfaces when declaring functions and struct fields for better readability and code reuse.
  • Consider using reflection or type conversion where appropriate to avoid casting types and reduce complexity.

Here’s an example of improved code structure considering the given code snippets:

package application

import (
	"context"
	"fmt"

	"github.com/docker/compose-go/api/v1/types/container"

	docker "github.com/opencontainers/image-spec/specs-go/latest/docker-image"
)

type ModelRuntimeDetails interface {
	GetAppID(context.Context) (*int64, error)
}

func GetModelRuntimeByApp(app ModelApplicationDetail) (ResultResponse[*models.Runtime], Error) {
	appIDs, exists := appMap[app.ID]
	result := ResultResponse[List{models.Runtime{}}, string>()
	if !exists || len(*appIDs) == 0 {
		result.Error = ErrUnknownAppName {AppName: app.Name}
		return result, &result.Error
	}

	var rList []models.Runtime
	for i, id := range *appIDs {
		runtimeId := models.NewRuntime(id)

		exists, err := rService.GetServiceByName(
			context.TODO(),
			docker.Tag{"latest"},
			fmt.Sprintf("/com.docker.compose.client.v2beta1.models/%v",
				model.RtTagKey),
		).Execute(&model.ModelServiceGetResult{
			ID:      int32(rt.Id()),
			Name:    rt.AppName,
			Status:  model.Running,
			Version: rt.Version,
		})

		if err != nil {
			panic(fmt.Errorf("Failed to call service to fetch runtime %w", err))
		}

		runtimeIds[i] = runtimeId
		log.Infof("%#v -> %#v", runtimeId, rt)
		result.Data[runtimeIds[i]] = &rt
	}

	result.SetData(result.Data)
	return result, nil
}

// In the actual implementation, instead of calling methods like Service, handleRuntime is called to take care of all related operations, reducing overhead.

Remember to replace placeholder values (rService) with concrete implementations according to project requirements.

As a reminder, always review the codebase thoroughly, refactor logically related parts together, optimize dependencies, and implement safety checks effectively throughout different aspects of your application to ensure robustness and reliability.

This provides general hints on best practices across various sections of software development.

Expand Down
11 changes: 0 additions & 11 deletions agent/constant/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,6 @@ const (
ResourceLocal = "local"
ResourceAppstore = "appstore"

RuntimeNormal = "normal"
RuntimeError = "error"
RuntimeBuildIng = "building"
RuntimeStarting = "starting"
RuntimeRunning = "running"
RuntimeReCreating = "recreating"
RuntimeStopped = "stopped"
RuntimeUnhealthy = "unhealthy"
RuntimeCreating = "creating"
RuntimeStartErr = "startErr"

RuntimePHP = "php"
RuntimeNode = "node"
RuntimeJava = "java"
Expand Down
31 changes: 20 additions & 11 deletions agent/constant/status.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
package constant

const (
StatusRunning = "Running"
StatusDone = "Done"
StatusWaiting = "Waiting"
StatusSuccess = "Success"
StatusFailed = "Failed"
StatusUploading = "Uploading"
StatusEnable = "Enable"
StatusDisable = "Disable"
StatusNone = "None"
StatusDeleted = "Deleted"
StatusExecuting = "Executing"
StatusRunning = "Running"
StatusDone = "Done"
StatusWaiting = "Waiting"
StatusSuccess = "Success"
StatusFailed = "Failed"
StatusUploading = "Uploading"
StatusEnable = "Enable"
StatusDisable = "Disable"
StatusNone = "None"
StatusDeleted = "Deleted"
StatusExecuting = "Executing"
StatusBuilding = "Building"
StatusReCreating = "Recreating"
StatusStopped = "Stopped"
StatusCreating = "Creating"
StatusStartErr = "StartErr"
StatusNormal = "Normal"
StatusError = "Error"
StatusStarting = "Starting"
StatusRestarting = "ReStarting"

OrderDesc = "descending"
OrderAsc = "ascending"
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/assets/iconfont/iconfont.css
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
@font-face {
font-family: "iconfont"; /* Project id 4776196 */
src: url('iconfont.woff2?t=1739873339591') format('woff2'),
url('iconfont.woff?t=1739873339591') format('woff'),
url('iconfont.ttf?t=1739873339591') format('truetype'),
url('iconfont.svg?t=1739873339591#iconfont') format('svg');
src: url('iconfont.woff2?t=1740384606757') format('woff2'),
url('iconfont.woff?t=1740384606757') format('woff'),
url('iconfont.ttf?t=1740384606757') format('truetype'),
url('iconfont.svg?t=1740384606757#iconfont') format('svg');
}

.iconfont {
Expand Down
Binary file modified frontend/src/assets/iconfont/iconfont.ttf
Binary file not shown.
Binary file modified frontend/src/assets/iconfont/iconfont.woff
Binary file not shown.
Binary file modified frontend/src/assets/iconfont/iconfont.woff2
Binary file not shown.
12 changes: 6 additions & 6 deletions frontend/src/components/app-status/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
@click="onOperate('start')"
:disabled="data.status === 'Installing'"
>
{{ $t('app.start') }}
{{ $t('commons.operate.start') }}
</el-button>
<el-button type="primary" v-if="data.status === 'Running'" link @click="onOperate('stop')">
{{ $t('app.stop') }}
{{ $t('commons.operate.stop') }}
</el-button>
<el-divider direction="vertical" />
<el-button
Expand All @@ -28,7 +28,7 @@
:disabled="data.status === 'Installing'"
@click="onOperate('restart')"
>
{{ $t('commons.button.restart') }}
{{ $t('commons.operate.restart') }}
</el-button>
<el-divider direction="vertical" />
<el-button
Expand All @@ -38,7 +38,7 @@
@click="onOperate('reload')"
:disabled="data.status !== 'Running'"
>
{{ $t('app.reload') }}
{{ $t('commons.operate.reload') }}
</el-button>
<el-divider v-if="data.app === 'OpenResty'" direction="vertical" />
<el-button
Expand Down Expand Up @@ -136,8 +136,8 @@ const onCheck = async (key: any, name: any) => {
const onOperate = async (operation: string) => {
operateReq.operate = operation;
ElMessageBox.confirm(
i18n.global.t('app.operatorHelper', [i18n.global.t('app.' + operation)]),
i18n.global.t('app.' + operation),
i18n.global.t('app.operatorHelper', [i18n.global.t('commons.operate.' + operation)]),
i18n.global.t('commons.operate.' + operation),
{
confirmButtonText: i18n.global.t('commons.button.confirm'),
cancelButtonText: i18n.global.t('commons.button.cancel'),
Expand Down
Loading
Loading