/ kubernetes / examples / task-executor / README_zh-CN.md
README_zh-CN.md
  1  # Task Executor 使用指南
  2  
  3  ## 简介
  4  
  5  `task-executor` 是一个轻量级组件,旨在 Kubernetes Pod 环境中运行和管理短期任务(进程或容器)。它充当本地代理,从 Kubernetes 控制器(例如 `BatchSandboxController`)接收任务规范,并在其运行的节点上执行这些任务。它暴露了一个简单的 HTTP API 用于任务创建、状态查询和管理。
  6  
  7  ## 运行 Task Executor
  8  
  9  可以使用 `cmd/task-executor/main.go` 入口点启动 `task-executor`。它支持各种命令行标志和环境变量进行配置。
 10  
 11  **基本启动:**
 12  
 13  ```bash
 14  /path/to/cmd/task-executor/main --data-dir=/var/lib/sandbox/tasks --listen-addr=0.0.0.0:5758
 15  ```
 16  
 17  **关键配置参数:**
 18  
 19  | 标志 / 环境变量 | 描述 | 默认值 |
 20  | :--- | :--- | :--- |
 21  | `--data-dir` (DATA_DIR) | 用于持久化任务状态和日志的目录。 | `/var/lib/sandbox/tasks` |
 22  | `--listen-addr` (LISTEN_ADDR) | HTTP API 服务器的地址和端口。 | `0.0.0.0:5758` |
 23  | `--enable-sidecar-mode` (ENABLE_SIDECAR_MODE) | 如果为 `true`,则启用 sidecar 模式执行,任务将在指定主容器的 PID 命名空间内运行。需要 `nsenter` 和适当的权限。 | `false` |
 24  | `--main-container-name` (MAIN_CONTAINER_NAME) | 当 `enable-sidecar-mode` 为 `true` 时,指定应使用其 PID 命名空间的主容器的名称。 | `main` |
 25  | `--enable-container-mode` (ENABLE_CONTAINER_MODE) | 如果为 `true`,则启用使用 CRI 运行时的容器模式执行。(注意:当前实现可能只是占位符)。 | `false` |
 26  | `--cri-socket` (CRI_SOCKET) | 当 `enable-container-mode` 为 `true` 时,CRI 套接字的路径(例如 `containerd.sock`)。 | `/var/run/containerd/containerd.sock` |
 27  | `--reconcile-interval` | 内部任务管理器协调任务状态的间隔。 | `500ms` |
 28  
 29  ## HTTP API 端点
 30  
 31  `task-executor` 暴露了一个 RESTful HTTP API。所有 API 调用都期望 JSON 请求体(如适用)并返回 JSON 响应。
 32  
 33  ### 1. `POST /tasks` - 创建新任务
 34  
 35  创建并启动单个任务。
 36  
 37  *   **方法:** `POST`
 38  *   **路径:** `/tasks`
 39  *   **请求体 (application/json):** 代表所需任务的对象。
 40  
 41      ```json
 42      {
 43        "name": "my-first-task",
 44        "spec": {
 45          "process": {
 46            "command": ["sh", "-c"],
 47            "args": ["echo 'Hello from my task!' && sleep 5 && echo 'Task finished.'"]
 48          }
 49        }
 50      }
 51      ```
 52  
 53  *   **响应体 (application/json):** 创建的任务对象及其初始状态。
 54  
 55      ```json
 56      {
 57        "name": "my-first-task",
 58        "spec": {
 59          "process": {
 60            "command": ["sh", "-c"],
 61            "args": ["echo 'Hello from my task!' && sleep 5 && echo 'Task finished.'"]
 62          }
 63        },
 64        "status": {
 65          "state": {
 66            "waiting": {
 67              "reason": "Initialized"
 68            }
 69          }
 70        }
 71      }
 72      ```
 73  
 74  **示例 (使用 `curl`):**
 75  
 76  ```bash
 77  curl -X POST -H "Content-Type: application/json" -d 
 78  '{
 79    "name": "my-first-task",
 80    "spec": {
 81      "process": {
 82        "command": ["sh", "-c"],
 83        "args": ["echo \"Hello from my task!\" && sleep 5 && echo \"Task finished.\""]
 84      }
 85    }
 86  }' http://localhost:5758/tasks
 87  ```
 88  
 89  ### 2. `GET /tasks/{id}` - 获取任务状态
 90  
 91  通过名称检索特定任务的当前状态。
 92  
 93  *   **方法:** `GET`
 94  *   **路径:** `/tasks/{taskName}`
 95  *   **响应体 (application/json):** 任务对象,包括其当前状态。
 96  
 97      ```json
 98      {
 99        "name": "my-first-task",
100        "spec": {
101          "process": {
102            "command": ["sh", "-c"],
103            "args": ["echo 'Hello from my task!' && sleep 5 && echo 'Task finished.'"]
104          }
105        },
106        "status": {
107          "state": {
108            "running": {
109              "startedAt": "2025-12-17T10:00:00Z"
110            }
111          }
112        }
113      }
114      ```
115  
116  **示例 (使用 `curl`):**
117  
118  ```bash
119  curl http://localhost:5758/tasks/my-first-task
120  ```
121  
122  ### 3. `DELETE /tasks/{id}` - 删除任务
123  
124  标记要删除的任务。`task-executor` 将尝试优雅地停止任务,然后删除其状态。
125  
126  *   **方法:** `DELETE`
127  *   **路径:** `/tasks/{taskName}`
128  *   **响应:** 成功标记删除时返回 `204 No Content`。
129  
130  **示例 (使用 `curl`):**
131  
132  ```bash
133  curl -X DELETE http://localhost:5758/tasks/my-first-task
134  ```
135  
136  ### 4. `POST /setTasks` - 同步任务
137  
138  此端点通常由控制器用于同步所需的任务集。不在所需列表中的任务将被标记为删除;新任务将被创建。
139  
140  *   **方法:** `POST`
141  *   **路径:** `/setTasks`
142  *   **请求体 (application/json):** 代表所需状态的任务对象数组。
143  
144      ```json
145      [
146        {
147          "name": "task-alpha",
148          "spec": {
149            "process": {
150              "command": ["sleep", "10"]
151            }
152          }
153        },
154        {
155          "name": "task-beta",
156          "spec": {
157            "process": {
158              "command": ["ls", "-l", "/tmp"]
159            }
160          }
161        }
162      ]
163      ```
164  
165  *   **响应体 (application/json):** 同步后执行器管理的当前任务列表。
166  
167      ```json
168      [
169        {
170          "name": "task-alpha",
171          "spec": {
172            "process": {
173              "command": ["sleep", "10"]
174            }
175          },
176          "status": {
177            "state": {
178              "waiting": {
179                "reason": "Initialized"
180              }
181            }
182          }
183        },
184        {
185          "name": "task-beta",
186          "spec": {
187            "process": {
188              "command": ["ls", "-l", "/tmp"]
189            }
190          },
191          "status": {
192            "state": {
193              "waiting": {
194                "reason": "Initialized"
195              }
196            }
197          }
198        }
199      ]
200      ```
201  
202  **示例 (使用 `curl`):**
203  
204  ```bash
205  curl -X POST -H "Content-Type: application/json" -d \
206  '[
207    {
208      "name": "task-alpha",
209      "spec": { "process": { "command": ["sleep", "10"] } }
210    },
211    {
212      "name": "task-beta",
213      "spec": { "process": { "command": ["ls", "-l", "/tmp"] } }
214    }
215  ]' http://localhost:5758/setTasks
216  ```
217  
218  ### 5. `GET /getTasks` - 列出所有任务
219  
220  检索 `task-executor` 当前管理的所有任务的列表。
221  
222  *   **方法:** `GET`
223  *   **路径:** `/getTasks`
224  *   **响应体 (application/json):** 任务对象数组。
225  
226      ```json
227      [
228        {
229          "name": "task-alpha",
230          "spec": {
231            "process": {
232              "command": ["sleep", "10"]
233            }
234          },
235          "status": {
236            "state": {
237              "running": {
238                "startedAt": "2025-12-17T10:05:00Z"
239              }
240            }
241          }
242        },
243        {
244          "name": "task-beta",
245          "spec": {
246            "process": {
247              "command": ["ls", "-l", "/tmp"]
248            }
249          },
250          "status": {
251            "state": {
252              "terminated": {
253                "exitCode": 0,
254                "reason": "Succeeded",
255                "startedAt": "2025-12-17T10:06:00Z",
256                "finishedAt": "2025-12-17T10:06:01Z"
257              }
258            }
259          }
260        }
261      ]
262      ```
263  
264  **示例 (使用 `curl`):**
265  
266  ```bash
267  curl http://localhost:5758/getTasks
268  ```
269  
270  ### 6. `GET /health` - 健康检查
271  
272  返回 `task-executor` 的健康状态。
273  
274  *   **方法:** `GET`
275  *   **路径:** `/health`
276  *   **响应体 (application/json):**
277  
278      ```json
279      {
280        "status": "healthy"
281      }
282      ```
283  
284  **示例 (使用 `curl`):**
285  
286  ```bash
287  curl http://localhost:5758/health
288  ```
289  
290  ## 任务规范 (`TaskSpec`) 结构
291  
292  任务对象中的 `spec` 字段 (`api/v1alpha1.TaskSpec`) 定义了应如何执行任务。它目前支持 `process` 和 `container` 执行模式。
293  
294  ### 进程任务示例
295  
296  此模式直接作为进程执行命令。
297  
298  ```json
299  {
300    "name": "my-process-task",
301    "spec": {
302      "process": {
303        "command": ["python3", "my_script.py"],
304        "args": ["--config", "/etc/app/config.yaml"],
305        "env": [
306          { "name": "DEBUG_MODE", "value": "true" }
307        ],
308        "workingDir": "/app"
309      }
310    }
311  }
312  ```
313  
314  ### 容器任务示例(占位符/未来特性)
315  
316  此模式旨在执行由 CRI 运行时管理的容器中的任务。请注意,根据 `internal/task-executor/runtime/container.go`,此模式可能仍是一个占位符。
317  
318  ```json
319  {
320    "name": "my-container-task",
321    "spec": {
322      "container": {
323        "image": "ubuntu:latest",
324        "command": ["/bin/bash", "-c"],
325        "args": ["apt update && apt install -y curl"],
326        "env": [
327          { "name": "http_proxy", "value": "http://myproxy.com:5758" }
328        ],
329        "volumeMounts": [
330          {
331            "name": "data-volume",
332            "mountPath": "/data"
333          }
334        ]
335      }
336    }
337  }
338  ```
339  
340  ## 任务状态 (`TaskStatus`) 结构
341  
342  任务对象中的 `status` 字段 (`internal/task-executor/types/Status` 映射到 `api/v1alpha1.TaskStatus` 用于外部 API) 提供了有关任务当前执行状态的详细信息。
343  
344  ```json
345  {
346    "name": "my-task",
347    "spec": { ... },
348    "status": {
349      "state": {
350        "waiting": {
351          "reason": "Initialized"
352        }
353      },
354      // 或者
355      "state": {
356        "running": {
357          "startedAt": "2025-12-17T10:00:00Z"
358        }
359      },
360      // 或者
361      "state": {
362        "terminated": {
363          "exitCode": 0,
364          "reason": "Succeeded",
365          "message": "Task completed successfully",
366          "startedAt": "2025-12-17T10:00:00Z",
367          "finishedAt": "2025-12-17T10:00:05Z"
368        }
369      }
370    }
371  }
372  ```
373  
374  **状态类型:**
375  
376  *   `waiting`:任务正在等待执行。
377  *   `running`:任务当前正在执行。
378  *   `terminated`:任务已完成(成功或失败)。
379  
380  ## 示例场景:运行 Sidecar 任务
381  
382  如果 `task-executor` 配置了 `--enable-sidecar-mode=true` 和 `--main-container-name=my-main-app`,它可以在 `my-main-app` 的 PID 命名空间内执行任务。
383  
384  ```bash
385  # 假设 task-executor 在 sidecar 模式下运行在一个包含 'my-main-app' 的 pod 上
386  # 此任务将从主容器的命名空间内执行 'ls /proc/self/ns'
387  curl -X POST -H "Content-Type: application/json" -d 
388  '{
389    "name": "sidecar-namespace-check",
390    "spec": {
391      "process": {
392        "command": ["ls", "/proc/self/ns"]
393      }
394    }
395  }' http://localhost:5758/tasks
396  ```