| 141 | } |
| 142 | |
| 143 | func NewTask(name, operate, taskScope, taskID string, resourceID uint) (*Task, error) { |
| 144 | if taskID == "" { |
| 145 | taskID = uuid.New().String() |
| 146 | } |
| 147 | logDir := path.Join(global.Dir.TaskDir, taskScope) |
| 148 | if _, err := os.Stat(logDir); os.IsNotExist(err) { |
| 149 | if err = os.MkdirAll(logDir, constant.DirPerm); err != nil { |
| 150 | return nil, fmt.Errorf("failed to create log directory: %w", err) |
| 151 | } |
| 152 | } |
| 153 | logPath := path.Join(global.Dir.TaskDir, taskScope, taskID+".log") |
| 154 | logger := logrus.New() |
| 155 | logger.SetFormatter(&SimpleFormatter{}) |
| 156 | logFile, err := os.OpenFile(logPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, constant.FilePerm) |
| 157 | if err != nil { |
| 158 | return nil, fmt.Errorf("failed to open log file: %w", err) |
| 159 | } |
| 160 | logger.SetOutput(logFile) |
| 161 | taskModel := &model.Task{ |
| 162 | ID: taskID, |
| 163 | Name: name, |
| 164 | Type: taskScope, |
| 165 | LogFile: logPath, |
| 166 | Status: constant.StatusExecuting, |
| 167 | ResourceID: resourceID, |
| 168 | Operate: operate, |
| 169 | } |
| 170 | taskRepo := repo.NewITaskRepo() |
| 171 | ctx, cancel := context.WithCancel(context.Background()) |
| 172 | global.TaskCtxMap[taskID] = cancel |
| 173 | task := &Task{TaskCtx: ctx, Name: name, logFile: logFile, Logger: logger, taskRepo: taskRepo, Task: taskModel} |
| 174 | return task, nil |
| 175 | } |
| 176 | |
| 177 | func ReNewTaskWithOps(resourceName, operate, scope, taskID string, resourceID uint) (*Task, error) { |
| 178 | return ReNewTask(GetTaskName(resourceName, operate, scope), operate, scope, taskID, resourceID) |