(
ctx context.Context,
task *BackgroundTask,
cmd *exec.Cmd,
cancel context.CancelFunc,
done chan struct{},
timeout time.Duration,
hasTimeout bool)
| 268 | } |
| 269 | return new(string(data)) |
| 270 | } |
| 271 | |
| 272 | func (m *BackgroundManager) GetError(taskID string) *string { |
| 273 | m.mu.Lock() |
| 274 | task := m.tasks[taskID] |
| 275 | m.mu.Unlock() |
| 276 | if task == nil { |
| 277 | return nil |
| 278 | } |
| 279 | data, err := os.ReadFile(task.ErrorPath) |
| 280 | if err != nil { |
| 281 | return nil |
| 282 | } |
| 283 | |
| 284 | return new(string(data)) |
| 285 | } |
| 286 | |
| 287 | func (m *BackgroundManager) runTask( |
| 288 | ctx context.Context, |
| 289 | task *BackgroundTask, |
| 290 | cmd *exec.Cmd, |
| 291 | cancel context.CancelFunc, |
| 292 | done chan struct{}, |
| 293 | timeout time.Duration, |
| 294 | hasTimeout bool) { |
| 295 | defer close(done) |
| 296 | defer cancel() |
| 297 | var stdout, stderr bytes.Buffer |
| 298 | cmd.Stdout = &stdout |
| 299 | cmd.Stderr = &stderr |
| 300 | if hasTimeout && timeout <= 0 { |
| 301 | timeoutSeconds := formatDurationSeconds(timeout) |
| 302 | output := fmt.Sprintf("[Command timed out after %ss]\nCommand: %s\n", timeoutSeconds, task.Command) |
| 303 | _ = os.WriteFile(task.OutputPath, []byte(output), 0o600) |
| 304 | _ = os.WriteFile(task.ErrorPath, []byte("Timeout after "+timeoutSeconds+"s"), 0o600) |
| 305 | m.finishTask(task.TaskID, "failed", nil) |
| 306 | return |
| 307 | } |
| 308 | err := cmd.Start() |
| 309 | if err != nil { |
| 310 | if hasTimeout && errors.Is(ctx.Err(), context.DeadlineExceeded) { |
| 311 | timeoutSeconds := formatDurationSeconds(timeout) |
| 312 | output := fmt.Sprintf("[Command timed out after %ss]\nCommand: %s\n", timeoutSeconds, task.Command) |
| 313 | _ = os.WriteFile(task.OutputPath, []byte(output), 0o600) |
| 314 | _ = os.WriteFile(task.ErrorPath, []byte("Timeout after "+timeoutSeconds+"s"), 0o600) |
| 315 | m.finishTask(task.TaskID, "failed", nil) |
| 316 | return |
| 317 | } |
| 318 | _ = os.WriteFile(task.ErrorPath, []byte("Background task crashed: "+err.Error()), 0o600) |
| 319 | m.finishTask(task.TaskID, "failed", nil) |
| 320 | return |
| 321 | } |
| 322 | err = cmd.Wait() |
| 323 | if hasTimeout && errors.Is(ctx.Err(), context.DeadlineExceeded) { |
| 324 | terminateProcessTree(cmd) |
| 325 | timeoutSeconds := formatDurationSeconds(timeout) |
| 326 | output := fmt.Sprintf("[Command timed out after %ss]\nCommand: %s\n", timeoutSeconds, task.Command) |
| 327 | _ = os.WriteFile(task.OutputPath, []byte(output), 0o600) |
no test coverage detected