mirror of
https://github.com/1Panel-dev/1Panel.git
synced 2026-09-22 16:00:51 +00:00
feat: Swap settings support task mode (#10639)
This commit is contained in:
@@ -27,7 +27,8 @@ type SwapHelper struct {
|
||||
Size uint64 `json:"size"`
|
||||
Used string `json:"used"`
|
||||
|
||||
IsNew bool `json:"isNew"`
|
||||
IsNew bool `json:"isNew"`
|
||||
TaskID string `json:"taskID"`
|
||||
}
|
||||
|
||||
type TimeZoneOptions struct {
|
||||
|
||||
+51
-31
@@ -12,9 +12,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/1Panel-dev/1Panel/agent/app/dto"
|
||||
"github.com/1Panel-dev/1Panel/agent/app/task"
|
||||
"github.com/1Panel-dev/1Panel/agent/buserr"
|
||||
"github.com/1Panel-dev/1Panel/agent/constant"
|
||||
"github.com/1Panel-dev/1Panel/agent/global"
|
||||
"github.com/1Panel-dev/1Panel/agent/i18n"
|
||||
"github.com/1Panel-dev/1Panel/agent/utils/cmd"
|
||||
"github.com/1Panel-dev/1Panel/agent/utils/common"
|
||||
"github.com/1Panel-dev/1Panel/agent/utils/ntp"
|
||||
@@ -231,40 +233,58 @@ func (u *DeviceService) UpdatePasswd(req dto.ChangePasswd) error {
|
||||
}
|
||||
|
||||
func (u *DeviceService) UpdateSwap(req dto.SwapHelper) error {
|
||||
if cmd.CheckIllegal(req.Path) {
|
||||
return buserr.New("ErrCmdIllegal")
|
||||
}
|
||||
if !req.IsNew {
|
||||
std, err := cmd.RunDefaultWithStdoutBashCf("%s swapoff %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle swapoff %s failed, err: %s", req.Path, std)
|
||||
}
|
||||
}
|
||||
if req.Size == 0 {
|
||||
if req.Path == path.Join(global.Dir.BaseDir, ".1panel_swap") {
|
||||
_ = os.Remove(path.Join(global.Dir.BaseDir, ".1panel_swap"))
|
||||
}
|
||||
return operateSwapWithFile(true, req)
|
||||
}
|
||||
stdDD, err := cmd.RunDefaultWithStdoutBashCf("%s dd if=/dev/zero of=%s bs=1024 count=%d", cmd.SudoHandleCmd(), req.Path, req.Size)
|
||||
taskItem, err := task.NewTaskWithOps(req.Path, task.TaskSwapSet, task.TaskScopeSystem, req.TaskID, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle dd %s failed, std: %s, err: %s", req.Path, stdDD, err)
|
||||
}
|
||||
stdChmod, err := cmd.RunDefaultWithStdoutBashCf("%s chmod 0600 %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle chmod 0600 %s failed,std: %s, err: %s", req.Path, stdChmod, err)
|
||||
}
|
||||
stdMkswap, err := cmd.RunDefaultWithStdoutBashCf("%s mkswap -f %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle mkswap -f %s failed, std: %s, err: %s", req.Path, stdMkswap, err)
|
||||
global.LOG.Errorf("new task for create container failed, err: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
stdSwapon, err := cmd.RunDefaultWithStdoutBashCf("%s swapon %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
_, _ = cmd.RunDefaultWithStdoutBashCf("%s swapoff %s", cmd.SudoHandleCmd(), req.Path)
|
||||
return fmt.Errorf("handle swapoff %s failed,std: %s, err: %s", req.Path, stdSwapon, err)
|
||||
}
|
||||
return operateSwapWithFile(false, req)
|
||||
taskItem.AddSubTask(i18n.GetMsgWithMap("SetSwap", map[string]interface{}{"path": req.Path, "size": common.LoadSizeUnit2F(float64(req.Size * 1024))}), func(t *task.Task) error {
|
||||
if cmd.CheckIllegal(req.Path) {
|
||||
return buserr.New("ErrCmdIllegal")
|
||||
}
|
||||
cmdMgr := cmd.NewCommandMgr(cmd.WithTask(*taskItem))
|
||||
if !req.IsNew {
|
||||
std, err := cmdMgr.RunWithStdoutBashCf("%s swapoff %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle swapoff %s failed, err: %s", req.Path, std)
|
||||
}
|
||||
}
|
||||
if req.Size == 0 {
|
||||
if req.Path == path.Join(global.Dir.BaseDir, ".1panel_swap") {
|
||||
_ = os.Remove(path.Join(global.Dir.BaseDir, ".1panel_swap"))
|
||||
}
|
||||
return operateSwapWithFile(true, req)
|
||||
}
|
||||
taskItem.LogStart(i18n.GetMsgByKey("CreateSwap"))
|
||||
stdDD, err := cmdMgr.RunWithStdoutBashCf("%s dd if=/dev/zero of=%s bs=1024 count=%d", cmd.SudoHandleCmd(), req.Path, req.Size)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle dd %s failed, std: %s, err: %s", req.Path, stdDD, err)
|
||||
}
|
||||
|
||||
taskItem.Log("chmod 0600 " + req.Path)
|
||||
stdChmod, err := cmdMgr.RunWithStdoutBashCf("%s chmod 0600 %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle chmod 0600 %s failed,std: %s, err: %s", req.Path, stdChmod, err)
|
||||
}
|
||||
taskItem.LogStart(i18n.GetMsgByKey("FormatSwap"))
|
||||
stdMkswap, err := cmdMgr.RunWithStdoutBashCf("%s mkswap -f %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("handle mkswap -f %s failed, std: %s, err: %s", req.Path, stdMkswap, err)
|
||||
}
|
||||
|
||||
taskItem.LogStart(i18n.GetMsgByKey("EnableSwap"))
|
||||
stdSwapon, err := cmdMgr.RunWithStdoutBashCf("%s swapon %s", cmd.SudoHandleCmd(), req.Path)
|
||||
if err != nil {
|
||||
_, _ = cmdMgr.RunWithStdoutBashCf("%s swapoff %s", cmd.SudoHandleCmd(), req.Path)
|
||||
return fmt.Errorf("handle swapoff %s failed,std: %s, err: %s", req.Path, stdSwapon, err)
|
||||
}
|
||||
return operateSwapWithFile(false, req)
|
||||
}, nil)
|
||||
go func() {
|
||||
_ = taskItem.Execute()
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *DeviceService) LoadConf(name string) (string, error) {
|
||||
|
||||
@@ -74,6 +74,7 @@ const (
|
||||
TaskBatch = "TaskBatch"
|
||||
TaskProtect = "TaskProtect"
|
||||
TaskConvert = "TaskConvert"
|
||||
TaskSwapSet = "TaskSwapSet"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -247,6 +247,11 @@ NoSuchResource: "No backup content found in the database, skipping..."
|
||||
ErrNotExistUser: 'The current user does not exist, please modify and try again!'
|
||||
ErrBanAction: 'Setting failed. The current {{ .name }} service is unavailable. Please check and try again!'
|
||||
ErrClamdscanNotFound: 'The clamdscan command was not detected, please refer to the documentation to install it!'
|
||||
TaskSwapSet: "Set Swap"
|
||||
SetSwap: "Set Swap {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Create Swap File"
|
||||
FormatSwap: "Format Swap File"
|
||||
EnableSwap: "Enable Swap"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "Clean up historical protection settings"
|
||||
|
||||
@@ -246,6 +246,11 @@ NoSuchResource: "No se encontraron contenidos de respaldo en la base de datos, o
|
||||
ErrNotExistUser: 'El usuario actual no existe, modifíquelo e intente de nuevo'
|
||||
ErrBanAction: 'Fallo al configurar. El servicio {{ .name }} no está disponible, revise e intente de nuevo'
|
||||
ErrClamdscanNotFound: 'El comando clamdscan no fue detectado, siga la documentación para instalarlo'
|
||||
TaskSwapSet: "Configurar Swap"
|
||||
SetSwap: "Configurar Swap {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Crear Archivo Swap"
|
||||
FormatSwap: "Formatear Archivo Swap"
|
||||
EnableSwap: "Habilitar Swap"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "Limpiar configuraciones de protección históricas"
|
||||
|
||||
@@ -246,6 +246,11 @@ NoSuchResource: "データベースにバックアップ内容が見つかりま
|
||||
ErrNotExistUser: '現在のユーザーは存在しません。変更してもう一度お試しください。'
|
||||
ErrBanAction: '設定に失敗しました。現在の {{ .name }} サービスは利用できません。確認してもう一度お試しください。'
|
||||
ErrClamdscanNotFound: 'clamdscan コマンドが検出されませんでした。インストールするにはドキュメントを参照してください。'
|
||||
TaskSwapSet: "Swap設定"
|
||||
SetSwap: "Swap設定 {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Swapファイル作成"
|
||||
FormatSwap: "Swapファイルフォーマット"
|
||||
EnableSwap: "Swapファイル有効化"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "履歴保護設定をクリーンアップ"
|
||||
|
||||
@@ -247,6 +247,11 @@ NoSuchResource: "데이터베이스에서 백업 내용을 찾을 수 없어 건
|
||||
ErrNotExistUser: '현재 사용자가 존재하지 않습니다. 수정한 후 다시 시도하세요!'
|
||||
ErrBanAction: '설정에 실패했습니다. 현재 {{ .name }} 서비스를 사용할 수 없습니다. 확인하고 다시 시도하세요!'
|
||||
ErrClamdscanNotFound: 'clamdscan 명령이 감지되지 않았습니다. 설명서를 참조하여 설치하세요!'
|
||||
TaskSwapSet: "Swap 설정"
|
||||
SetSwap: "Swap 설정 {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Swap 파일 생성"
|
||||
FormatSwap: "Swap 파일 포맷"
|
||||
EnableSwap: "Swap 활성화"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "히스토리 보호 설정 정리"
|
||||
|
||||
@@ -247,6 +247,11 @@ NoSuchResource: "Tiada kandungan sandaran ditemui dalam pangkalan data, dilangka
|
||||
ErrNotExistUser: 'Pengguna semasa tidak wujud, sila ubah suai dan cuba lagi!'
|
||||
ErrBanAction: 'Tetapan gagal. Perkhidmatan {{ .name }} semasa tidak tersedia. Sila semak dan cuba lagi!'
|
||||
ErrClamdscanNotFound: 'Arahan clamdscan tidak dikesan, sila rujuk dokumentasi untuk memasangnya!'
|
||||
TaskSwapSet: "Tetapkan Swap"
|
||||
SetSwap: "Tetapkan Swap {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Buat Fail Swap"
|
||||
FormatSwap: "Format Fail Swap"
|
||||
EnableSwap: "Dayakan Swap"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "Bersihkan tetapan perlindungan sejarah"
|
||||
|
||||
@@ -247,6 +247,11 @@ NoSuchResource: "Nenhum conteúdo de backup encontrado no banco de dados, ignora
|
||||
ErrNotExistUser: 'O usuário atual não existe, modifique e tente novamente!'
|
||||
ErrBanAction: 'Falha na configuração. O serviço atual {{ .name }} não está disponível. Verifique e tente novamente!'
|
||||
ErrClamdscanNotFound: 'O comando clamdscan não foi detectado, consulte a documentação para instalá-lo!'
|
||||
TaskSwapSet: "Configurar Swap"
|
||||
SetSwap: "Configurar Swap {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Criar Arquivo Swap"
|
||||
FormatSwap: "Formatar Arquivo Swap"
|
||||
EnableSwap: "Ativar Swap"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "Limpar configurações de proteção históricas"
|
||||
|
||||
@@ -247,6 +247,11 @@ NoSuchResource: "В базе данных не найдено содержимо
|
||||
ErrNotExistUser: 'Текущий пользователь не существует, измените его и повторите попытку!'
|
||||
ErrBanAction: 'Настройка не удалась. Текущая служба {{ .name }} недоступна. Проверьте и повторите попытку!'
|
||||
ErrClamdscanNotFound: 'Команда clamdscan не обнаружена, обратитесь к документации, чтобы установить ее!'
|
||||
TaskSwapSet: "Настройка Swap"
|
||||
SetSwap: "Настроить Swap {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Создать Файл Swap"
|
||||
FormatSwap: "Форматировать Файл Swap"
|
||||
EnableSwap: "Включить Swap"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "Очистить исторические настройки защиты"
|
||||
|
||||
@@ -248,6 +248,11 @@ NoSuchResource: "Veritabanında yedek içeriği bulunamadı, atlanıyor..."
|
||||
ErrNotExistUser: 'Mevcut kullanıcı mevcut değil, lütfen değiştirin ve tekrar deneyin!'
|
||||
ErrBanAction: 'Ayarlama başarısız. Mevcut {{ .name }} servisi kullanılamıyor. Lütfen kontrol edin ve tekrar deneyin!'
|
||||
ErrClamdscanNotFound: 'clamdscan komutu tespit edilmedi, lütfen yüklemek için belgeleri inceleyin!'
|
||||
TaskSwapSet: "Swap Ayarla"
|
||||
SetSwap: "Swap Ayarla {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "Swap Dosyası Oluştur"
|
||||
FormatSwap: "Swap Dosyasını Biçimlendir"
|
||||
EnableSwap: "Swap Etkinleştir"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "Geçmiş koruma ayarlarını temizle"
|
||||
|
||||
@@ -246,6 +246,11 @@ NoSuchResource: "資料庫中未能查詢到備份內容,跳過..."
|
||||
ErrNotExistUser: '目前使用者不存在,請修改後重試!'
|
||||
ErrBanAction: '設定失敗,目前{{ .name }} 服務不可用,請檢查後再試一次!'
|
||||
ErrClamdscanNotFound: '未偵測到clamdscan 指令,請參考文件安裝!'
|
||||
TaskSwapSet: "設定 Swap"
|
||||
SetSwap: "設定 Swap {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "建立 Swap 檔案"
|
||||
FormatSwap: "格式化 Swap 檔案"
|
||||
EnableSwap: "啟用 Swap"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "清理歷史防護設定"
|
||||
|
||||
@@ -246,6 +246,11 @@ NoSuchResource: "数据库中未能查询到备份内容,跳过..."
|
||||
ErrNotExistUser: "当前用户不存在,请修改后重试!"
|
||||
ErrBanAction: "设置失败,当前 {{ .name }} 服务不可用,请检查后重试!"
|
||||
ErrClamdscanNotFound: "未检测到 clamdscan 命令,请参考文档安装!"
|
||||
TaskSwapSet: "设置 Swap"
|
||||
SetSwap: "设置 Swap {{ .path }} - {{ .size }}"
|
||||
CreateSwap: "创建 Swap 文件"
|
||||
FormatSwap: "格式化 Swap 文件"
|
||||
EnableSwap: "启用 Swap"
|
||||
|
||||
#tamper
|
||||
CleanTamperSetting: "清理历史防护设置"
|
||||
|
||||
@@ -80,13 +80,15 @@
|
||||
</span>
|
||||
</template>
|
||||
</DrawerPro>
|
||||
<TaskLog ref="taskLogRef" width="70%" @close="search" />
|
||||
</template>
|
||||
<script lang="ts" setup>
|
||||
import { reactive, ref } from 'vue';
|
||||
import i18n from '@/lang';
|
||||
import { MsgError, MsgSuccess } from '@/utils/message';
|
||||
import { updateDeviceSwap, getDeviceBase } from '@/api/modules/toolbox';
|
||||
import { computeSize, splitSize } from '@/utils/util';
|
||||
import { computeSize, newUUID, splitSize } from '@/utils/util';
|
||||
import TaskLog from '@/components/log/task/index.vue';
|
||||
import { loadBaseDir } from '@/api/modules/setting';
|
||||
|
||||
const form = reactive({
|
||||
@@ -100,6 +102,7 @@ const form = reactive({
|
||||
|
||||
const drawerVisible = ref();
|
||||
const loading = ref();
|
||||
const taskLogRef = ref();
|
||||
|
||||
const acceptParams = (): void => {
|
||||
search();
|
||||
@@ -176,19 +179,23 @@ const onSave = async (row) => {
|
||||
used: '0',
|
||||
|
||||
isNew: row.isNew,
|
||||
taskID: newUUID(),
|
||||
};
|
||||
loading.value = true;
|
||||
await updateDeviceSwap(params)
|
||||
.then(() => {
|
||||
loading.value = false;
|
||||
openTaskLog(params.taskID);
|
||||
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
|
||||
search();
|
||||
})
|
||||
.catch(() => {
|
||||
loading.value = false;
|
||||
});
|
||||
});
|
||||
};
|
||||
const openTaskLog = (taskID: string) => {
|
||||
taskLogRef.value.openWithTaskID(taskID);
|
||||
};
|
||||
|
||||
const loadItemSize = (row: any) => {
|
||||
switch (row.sizeUnit) {
|
||||
|
||||
Reference in New Issue
Block a user