feat: add task workdir option
This commit is contained in:
@@ -27,6 +27,7 @@ func (tc *TaskController) CreateTask(c *gin.Context) {
|
|||||||
Command string `json:"command" binding:"required"`
|
Command string `json:"command" binding:"required"`
|
||||||
Schedule string `json:"schedule" binding:"required"`
|
Schedule string `json:"schedule" binding:"required"`
|
||||||
Timeout int `json:"timeout"`
|
Timeout int `json:"timeout"`
|
||||||
|
WorkDir string `json:"work_dir"`
|
||||||
CleanConfig string `json:"clean_config"`
|
CleanConfig string `json:"clean_config"`
|
||||||
Envs string `json:"envs"`
|
Envs string `json:"envs"`
|
||||||
}
|
}
|
||||||
@@ -41,7 +42,7 @@ func (tc *TaskController) CreateTask(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
task := tc.taskService.CreateTask(req.Name, req.Command, req.Schedule, req.Timeout, req.CleanConfig, req.Envs)
|
task := tc.taskService.CreateTask(req.Name, req.Command, req.Schedule, req.Timeout, req.WorkDir, req.CleanConfig, req.Envs)
|
||||||
tc.cronService.AddTask(task)
|
tc.cronService.AddTask(task)
|
||||||
|
|
||||||
utils.Success(c, task)
|
utils.Success(c, task)
|
||||||
@@ -83,6 +84,7 @@ func (tc *TaskController) UpdateTask(c *gin.Context) {
|
|||||||
Command string `json:"command"`
|
Command string `json:"command"`
|
||||||
Schedule string `json:"schedule"`
|
Schedule string `json:"schedule"`
|
||||||
Timeout int `json:"timeout"`
|
Timeout int `json:"timeout"`
|
||||||
|
WorkDir string `json:"work_dir"`
|
||||||
CleanConfig string `json:"clean_config"`
|
CleanConfig string `json:"clean_config"`
|
||||||
Envs string `json:"envs"`
|
Envs string `json:"envs"`
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
@@ -100,7 +102,7 @@ func (tc *TaskController) UpdateTask(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
task := tc.taskService.UpdateTask(id, req.Name, req.Command, req.Schedule, req.Timeout, req.CleanConfig, req.Envs, req.Enabled)
|
task := tc.taskService.UpdateTask(id, req.Name, req.Command, req.Schedule, req.Timeout, req.WorkDir, req.CleanConfig, req.Envs, req.Enabled)
|
||||||
if task == nil {
|
if task == nil {
|
||||||
utils.NotFound(c, "任务不存在")
|
utils.NotFound(c, "任务不存在")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ type Task struct {
|
|||||||
Command string `json:"command" gorm:"type:text;not null"`
|
Command string `json:"command" gorm:"type:text;not null"`
|
||||||
Schedule string `json:"schedule" gorm:"size:100"` // cron expression
|
Schedule string `json:"schedule" gorm:"size:100"` // cron expression
|
||||||
Timeout int `json:"timeout" gorm:"default:30"` // 超时时间(分钟),默认30分钟
|
Timeout int `json:"timeout" gorm:"default:30"` // 超时时间(分钟),默认30分钟
|
||||||
|
WorkDir string `json:"work_dir" gorm:"size:255;default:''"` // 工作目录,为空则使用 scripts 目录
|
||||||
CleanConfig string `json:"clean_config" gorm:"size:255;default:''"` // 清理配置 JSON
|
CleanConfig string `json:"clean_config" gorm:"size:255;default:''"` // 清理配置 JSON
|
||||||
Envs string `json:"envs" gorm:"size:255;default:''"` // 环境变量ID列表,逗号分隔
|
Envs string `json:"envs" gorm:"size:255;default:''"` // 环境变量ID列表,逗号分隔
|
||||||
Enabled bool `json:"enabled" gorm:"default:true"`
|
Enabled bool `json:"enabled" gorm:"default:true"`
|
||||||
|
|||||||
@@ -300,12 +300,18 @@ func (es *ExecutorService) executeTaskInternal(taskID int) *ExecutionResult {
|
|||||||
envService := NewEnvService()
|
envService := NewEnvService()
|
||||||
envVars := envService.GetEnvVarsByIDs(task.Envs)
|
envVars := envService.GetEnvVarsByIDs(task.Envs)
|
||||||
|
|
||||||
|
// 确定工作目录
|
||||||
|
workDir := task.WorkDir
|
||||||
|
if workDir == "" {
|
||||||
|
workDir = constant.ScriptsWorkDir
|
||||||
|
}
|
||||||
|
|
||||||
// 使用任务配置的超时时间
|
// 使用任务配置的超时时间
|
||||||
timeout := task.Timeout
|
timeout := task.Timeout
|
||||||
if timeout <= 0 {
|
if timeout <= 0 {
|
||||||
timeout = constant.DefaultTaskTimeout
|
timeout = constant.DefaultTaskTimeout
|
||||||
}
|
}
|
||||||
result := es.ExecuteCommandWithEnv(task.Command, time.Duration(timeout)*time.Minute, envVars)
|
result := es.ExecuteCommandWithOptions(task.Command, time.Duration(timeout)*time.Minute, envVars, workDir)
|
||||||
result.TaskID = taskID
|
result.TaskID = taskID
|
||||||
|
|
||||||
// 标记任务结束
|
// 标记任务结束
|
||||||
@@ -338,6 +344,11 @@ func (es *ExecutorService) ExecuteCommandWithTimeout(command string, timeout tim
|
|||||||
|
|
||||||
// ExecuteCommandWithEnv executes a shell command with specified timeout and environment variables
|
// ExecuteCommandWithEnv executes a shell command with specified timeout and environment variables
|
||||||
func (es *ExecutorService) ExecuteCommandWithEnv(command string, timeout time.Duration, envVars []string) *ExecutionResult {
|
func (es *ExecutorService) ExecuteCommandWithEnv(command string, timeout time.Duration, envVars []string) *ExecutionResult {
|
||||||
|
return es.ExecuteCommandWithOptions(command, timeout, envVars, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecuteCommandWithOptions executes a shell command with specified timeout, environment variables and working directory
|
||||||
|
func (es *ExecutorService) ExecuteCommandWithOptions(command string, timeout time.Duration, envVars []string, workDir string) *ExecutionResult {
|
||||||
result := &ExecutionResult{
|
result := &ExecutionResult{
|
||||||
Success: false,
|
Success: false,
|
||||||
Start: time.Now(),
|
Start: time.Now(),
|
||||||
@@ -352,6 +363,11 @@ func (es *ExecutorService) ExecuteCommandWithEnv(command string, timeout time.Du
|
|||||||
cmd.Stdout = &stdout
|
cmd.Stdout = &stdout
|
||||||
cmd.Stderr = &stderr
|
cmd.Stderr = &stderr
|
||||||
|
|
||||||
|
// 设置工作目录
|
||||||
|
if workDir != "" {
|
||||||
|
cmd.Dir = workDir
|
||||||
|
}
|
||||||
|
|
||||||
// 设置环境变量:继承系统环境变量 + 自定义环境变量
|
// 设置环境变量:继承系统环境变量 + 自定义环境变量
|
||||||
if len(envVars) > 0 {
|
if len(envVars) > 0 {
|
||||||
cmd.Env = append(os.Environ(), envVars...)
|
cmd.Env = append(os.Environ(), envVars...)
|
||||||
|
|||||||
@@ -11,12 +11,13 @@ func NewTaskService() *TaskService {
|
|||||||
return &TaskService{}
|
return &TaskService{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ts *TaskService) CreateTask(name, command, schedule string, timeout int, cleanConfig, envs string) *models.Task {
|
func (ts *TaskService) CreateTask(name, command, schedule string, timeout int, workDir, cleanConfig, envs string) *models.Task {
|
||||||
task := &models.Task{
|
task := &models.Task{
|
||||||
Name: name,
|
Name: name,
|
||||||
Command: command,
|
Command: command,
|
||||||
Schedule: schedule,
|
Schedule: schedule,
|
||||||
Timeout: timeout,
|
Timeout: timeout,
|
||||||
|
WorkDir: workDir,
|
||||||
CleanConfig: cleanConfig,
|
CleanConfig: cleanConfig,
|
||||||
Envs: envs,
|
Envs: envs,
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
@@ -55,7 +56,7 @@ func (ts *TaskService) GetTaskByID(id int) *models.Task {
|
|||||||
return &task
|
return &task
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ts *TaskService) UpdateTask(id int, name, command, schedule string, timeout int, cleanConfig, envs string, enabled bool) *models.Task {
|
func (ts *TaskService) UpdateTask(id int, name, command, schedule string, timeout int, workDir, cleanConfig, envs string, enabled bool) *models.Task {
|
||||||
var task models.Task
|
var task models.Task
|
||||||
if err := database.DB.First(&task, id).Error; err != nil {
|
if err := database.DB.First(&task, id).Error; err != nil {
|
||||||
return nil
|
return nil
|
||||||
@@ -64,6 +65,7 @@ func (ts *TaskService) UpdateTask(id int, name, command, schedule string, timeou
|
|||||||
task.Command = command
|
task.Command = command
|
||||||
task.Schedule = schedule
|
task.Schedule = schedule
|
||||||
task.Timeout = timeout
|
task.Timeout = timeout
|
||||||
|
task.WorkDir = workDir
|
||||||
task.CleanConfig = cleanConfig
|
task.CleanConfig = cleanConfig
|
||||||
task.Envs = envs
|
task.Envs = envs
|
||||||
task.Enabled = enabled
|
task.Enabled = enabled
|
||||||
|
|||||||
@@ -220,6 +220,7 @@ export interface Task {
|
|||||||
command: string
|
command: string
|
||||||
schedule: string
|
schedule: string
|
||||||
timeout: number
|
timeout: number
|
||||||
|
work_dir: string
|
||||||
clean_config: string
|
clean_config: string
|
||||||
envs: string
|
envs: string
|
||||||
enabled: boolean
|
enabled: boolean
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, watch } from 'vue'
|
||||||
|
import { Folder, ChevronRight, ChevronDown, FolderOpen } from 'lucide-vue-next'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||||
|
import { api, type FileNode } from '@/api'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
modelValue: string
|
||||||
|
placeholder?: string
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:modelValue': [value: string]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const open = ref(false)
|
||||||
|
const loading = ref(false)
|
||||||
|
const fileTree = ref<FileNode[]>([])
|
||||||
|
const expandedDirs = ref<Set<string>>(new Set())
|
||||||
|
|
||||||
|
// 只保留目录节点
|
||||||
|
function filterDirs(nodes: FileNode[]): FileNode[] {
|
||||||
|
return nodes
|
||||||
|
.filter(n => n.isDir)
|
||||||
|
.map(n => ({
|
||||||
|
...n,
|
||||||
|
children: n.children ? filterDirs(n.children) : undefined
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirTree = computed(() => filterDirs(fileTree.value))
|
||||||
|
|
||||||
|
async function loadTree() {
|
||||||
|
if (fileTree.value.length > 0) return
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
fileTree.value = await api.files.tree()
|
||||||
|
} catch {
|
||||||
|
fileTree.value = []
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleDir(path: string) {
|
||||||
|
if (expandedDirs.value.has(path)) {
|
||||||
|
expandedDirs.value.delete(path)
|
||||||
|
} else {
|
||||||
|
expandedDirs.value.add(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectDir(path: string) {
|
||||||
|
emit('update:modelValue', path)
|
||||||
|
open.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectRoot() {
|
||||||
|
emit('update:modelValue', '')
|
||||||
|
open.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(open, (val) => {
|
||||||
|
if (val) loadTree()
|
||||||
|
})
|
||||||
|
|
||||||
|
const displayValue = computed(() => {
|
||||||
|
if (!props.modelValue) return props.placeholder || 'scripts (默认)'
|
||||||
|
return props.modelValue
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Popover v-model:open="open">
|
||||||
|
<PopoverTrigger as-child>
|
||||||
|
<Button variant="outline" class="w-full justify-start font-mono text-sm h-9">
|
||||||
|
<Folder class="h-4 w-4 mr-2 text-yellow-500 shrink-0" />
|
||||||
|
<span class="truncate">{{ displayValue }}</span>
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent class="w-[300px] p-2" align="start">
|
||||||
|
<div class="text-xs text-muted-foreground mb-2">选择工作目录</div>
|
||||||
|
<div class="max-h-[240px] overflow-y-auto">
|
||||||
|
<!-- 根目录选项 -->
|
||||||
|
<div
|
||||||
|
:class="[
|
||||||
|
'flex items-center gap-1.5 py-1 px-2 rounded cursor-pointer text-sm',
|
||||||
|
!modelValue ? 'bg-primary/10 text-primary' : 'hover:bg-muted'
|
||||||
|
]"
|
||||||
|
@click="selectRoot"
|
||||||
|
>
|
||||||
|
<FolderOpen class="h-4 w-4 text-yellow-500" />
|
||||||
|
<span>scripts (默认)</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 目录树 -->
|
||||||
|
<DirTreeNode
|
||||||
|
v-for="node in dirTree"
|
||||||
|
:key="node.path"
|
||||||
|
:node="node"
|
||||||
|
:expanded-dirs="expandedDirs"
|
||||||
|
:selected-path="modelValue"
|
||||||
|
@toggle="toggleDir"
|
||||||
|
@select="selectDir"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div v-if="loading" class="text-xs text-muted-foreground text-center py-4">
|
||||||
|
加载中...
|
||||||
|
</div>
|
||||||
|
<div v-else-if="dirTree.length === 0" class="text-xs text-muted-foreground text-center py-2">
|
||||||
|
暂无子目录
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script lang="ts">
|
||||||
|
import { defineComponent, h } from 'vue'
|
||||||
|
|
||||||
|
// 内联递归组件
|
||||||
|
const DirTreeNode = defineComponent({
|
||||||
|
name: 'DirTreeNode',
|
||||||
|
props: {
|
||||||
|
node: { type: Object as () => FileNode, required: true },
|
||||||
|
expandedDirs: { type: Object as () => Set<string>, required: true },
|
||||||
|
selectedPath: { type: String, default: '' },
|
||||||
|
depth: { type: Number, default: 0 }
|
||||||
|
},
|
||||||
|
emits: ['toggle', 'select'],
|
||||||
|
setup(props, { emit }) {
|
||||||
|
const isExpanded = computed(() => props.expandedDirs.has(props.node.path))
|
||||||
|
const isSelected = computed(() => props.selectedPath === props.node.path)
|
||||||
|
|
||||||
|
return () => h('div', [
|
||||||
|
h('div', {
|
||||||
|
class: [
|
||||||
|
'flex items-center gap-1 py-1 px-2 rounded cursor-pointer text-sm',
|
||||||
|
isSelected.value ? 'bg-primary/10 text-primary' : 'hover:bg-muted'
|
||||||
|
],
|
||||||
|
style: { paddingLeft: (props.depth * 12 + 8) + 'px' },
|
||||||
|
onClick: () => emit('select', props.node.path)
|
||||||
|
}, [
|
||||||
|
h('span', {
|
||||||
|
class: 'shrink-0 cursor-pointer',
|
||||||
|
onClick: (e: Event) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
emit('toggle', props.node.path)
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
isExpanded.value
|
||||||
|
? h(ChevronDown, { class: 'h-3 w-3' })
|
||||||
|
: h(ChevronRight, { class: 'h-3 w-3' })
|
||||||
|
]),
|
||||||
|
h(Folder, { class: 'h-4 w-4 text-yellow-500 shrink-0' }),
|
||||||
|
h('span', { class: 'truncate' }, props.node.name)
|
||||||
|
]),
|
||||||
|
isExpanded.value && props.node.children?.length
|
||||||
|
? props.node.children.map(child =>
|
||||||
|
h(DirTreeNode, {
|
||||||
|
key: child.path,
|
||||||
|
node: child,
|
||||||
|
expandedDirs: props.expandedDirs,
|
||||||
|
selectedPath: props.selectedPath,
|
||||||
|
depth: props.depth + 1,
|
||||||
|
onToggle: (path: string) => emit('toggle', path),
|
||||||
|
onSelect: (path: string) => emit('select', path)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
export { DirTreeNode }
|
||||||
|
</script>
|
||||||
@@ -9,6 +9,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
|||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import Pagination from '@/components/Pagination.vue'
|
import Pagination from '@/components/Pagination.vue'
|
||||||
|
import DirTreeSelect from '@/components/DirTreeSelect.vue'
|
||||||
import { Plus, Play, Pencil, Trash2, Search, ScrollText, ChevronDown, X } from 'lucide-vue-next'
|
import { Plus, Play, Pencil, Trash2, Search, ScrollText, ChevronDown, X } from 'lucide-vue-next'
|
||||||
import { api, type Task, type EnvVar } from '@/api'
|
import { api, type Task, type EnvVar } from '@/api'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
@@ -118,7 +119,7 @@ function handlePageChange(page: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
editingTask.value = { name: '', command: '', schedule: '0 * * * * *', timeout: 30, enabled: true, clean_config: '', envs: '' }
|
editingTask.value = { name: '', command: '', schedule: '0 * * * * *', timeout: 30, work_dir: '', enabled: true, clean_config: '', envs: '' }
|
||||||
cleanType.value = 'none'
|
cleanType.value = 'none'
|
||||||
cleanKeep.value = 30
|
cleanKeep.value = 30
|
||||||
selectedEnvIds.value = []
|
selectedEnvIds.value = []
|
||||||
@@ -192,7 +193,7 @@ async function runTask(id: number) {
|
|||||||
|
|
||||||
async function toggleTask(task: Task, enabled: boolean) {
|
async function toggleTask(task: Task, enabled: boolean) {
|
||||||
try {
|
try {
|
||||||
await api.tasks.update(task.id, { name: task.name, command: task.command, schedule: task.schedule, timeout: task.timeout, clean_config: task.clean_config, envs: task.envs, enabled })
|
await api.tasks.update(task.id, { name: task.name, command: task.command, schedule: task.schedule, timeout: task.timeout, work_dir: task.work_dir, clean_config: task.clean_config, envs: task.envs, enabled })
|
||||||
toast.success(enabled ? '任务已启用' : '任务已禁用')
|
toast.success(enabled ? '任务已启用' : '任务已禁用')
|
||||||
loadTasks()
|
loadTasks()
|
||||||
} catch { toast.error('操作失败') }
|
} catch { toast.error('操作失败') }
|
||||||
@@ -291,6 +292,12 @@ onMounted(() => {
|
|||||||
<Label class="text-right">执行命令</Label>
|
<Label class="text-right">执行命令</Label>
|
||||||
<Input v-model="editingTask.command" placeholder="node script.js" class="col-span-3 font-mono" />
|
<Input v-model="editingTask.command" placeholder="node script.js" class="col-span-3 font-mono" />
|
||||||
</div>
|
</div>
|
||||||
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
|
<Label class="text-right">工作目录</Label>
|
||||||
|
<div class="col-span-3">
|
||||||
|
<DirTreeSelect v-model="editingTask.work_dir" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="grid grid-cols-4 items-center gap-4">
|
<div class="grid grid-cols-4 items-center gap-4">
|
||||||
<Label class="text-right">定时规则</Label>
|
<Label class="text-right">定时规则</Label>
|
||||||
<Input v-model="editingTask.schedule" placeholder="0 * * * * *" class="col-span-3 font-mono" />
|
<Input v-model="editingTask.schedule" placeholder="0 * * * * *" class="col-span-3 font-mono" />
|
||||||
|
|||||||
Reference in New Issue
Block a user