fix+docs: FunctionJob label bugfix, job ErrAlreadyExists, python str→text/plain, operator.yaml v0.1.33, progress.md
- controllers/functionjob_controller.go: - PodTemplate labels: functionjob=, function= (k8s 1.27+ удалил job-name=) - getJobPodOutput принимает labelSelector вместо jobName - захват stderr при Failed job; truncateForStatus() helper - terraform/provider/internal/client/client.go: ErrJobAlreadyExists (409 Conflict) - terraform/provider/internal/resources/job_resource.go: при конфликте создания — читаем существующий job - runtimes/python3.11/server.py: str return → text/plain - internal/builder/context.go: python runtime base image → v0.1.3 - deployments/k8s/operator.yaml: image → v0.1.33 - doc/progress.md: добавлены секции FunctionJob bugfix, str→text/plain, web-console v0.2.0
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
// Изменено: 2026-03-09 (feature B: захват stdout пода Job в status.Message)
|
||||
// Изменено: 2026-03-17 20:00 (bugfix: job-name label удалён в k8s 1.27+, split-brain cached client)
|
||||
// FunctionJobReconciler — контроллер одноразовых запусков функций.
|
||||
// При создании FunctionJob:
|
||||
// 1. Ждёт пока Function станет Ready
|
||||
@@ -134,6 +134,13 @@ func (r *FunctionJobReconciler) Reconcile(ctx context.Context, req ctrl.Request)
|
||||
// Автоудаление через 10 мин после завершения — чтобы не засорять кластер
|
||||
TTLSecondsAfterFinished: &ttl,
|
||||
Template: corev1.PodTemplateSpec{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Labels: map[string]string{
|
||||
"managed-by": "sless",
|
||||
"functionjob": fj.Name,
|
||||
"function": fn.Name,
|
||||
},
|
||||
},
|
||||
Spec: corev1.PodSpec{
|
||||
RestartPolicy: corev1.RestartPolicyNever,
|
||||
// Используем тот же образ что и Deployment функции
|
||||
@@ -194,12 +201,19 @@ func (r *FunctionJobReconciler) syncJobStatus(ctx context.Context, fj *slessv1al
|
||||
fj.Status.Phase = slessv1alpha1.FunctionJobPhaseSucceeded
|
||||
fj.Status.CompletionTime = &now
|
||||
// Захватываем stdout пода — это return value функции (runner делает print(json.dumps(result)))
|
||||
fj.Status.Message = getJobPodOutput(ctx, r.KubeClient, job.Namespace, job.Name)
|
||||
fj.Status.Message = getJobPodOutput(ctx, r.KubeClient, job.Namespace, "functionjob="+fj.Name)
|
||||
} else if job.Status.Failed > 0 {
|
||||
now := metav1.Now()
|
||||
fj.Status.Phase = slessv1alpha1.FunctionJobPhaseFailed
|
||||
fj.Status.CompletionTime = &now
|
||||
fj.Status.Message = "job failed, check pod logs: kubectl logs -n sless-fn-" + fj.Namespace + " -l functionjob=" + fj.Name
|
||||
// Захватываем логи по нашему лейблу functionjob= (работает во всех версиях k8s).
|
||||
// Устаревший job-name= удалён в k8s 1.27+, batch.kubernetes.io/job-name= — только с 1.27.
|
||||
podOutput := strings.TrimSpace(getJobPodOutput(ctx, r.KubeClient, job.Namespace, "functionjob="+fj.Name))
|
||||
if podOutput == "" || podOutput == "completed successfully" {
|
||||
fj.Status.Message = "job failed, check pod logs: kubectl logs -n " + job.Namespace + " -l functionjob=" + fj.Name
|
||||
} else {
|
||||
fj.Status.Message = "job failed: " + truncateForStatus(podOutput, 2000)
|
||||
}
|
||||
} else {
|
||||
// Job ещё выполняется — перечитаем через 5 секунд
|
||||
if err := r.Status().Update(ctx, fj); err != nil {
|
||||
@@ -213,6 +227,17 @@ func (r *FunctionJobReconciler) syncJobStatus(ctx context.Context, fj *slessv1al
|
||||
return ctrl.Result{}, nil
|
||||
}
|
||||
|
||||
// truncateForStatus ограничивает длину текста для безопасной записи в status.message.
|
||||
func truncateForStatus(message string, maxLen int) string {
|
||||
if len(message) <= maxLen {
|
||||
return message
|
||||
}
|
||||
if maxLen <= 3 {
|
||||
return message[:maxLen]
|
||||
}
|
||||
return message[:maxLen-3] + "..."
|
||||
}
|
||||
|
||||
// runtimeRunnerCommand возвращает CMD для запуска одноразового runner вместо HTTP-сервера.
|
||||
// runner читает env SLESS_EVENT и SLESS_ENTRYPOINT, вызывает handle(event) один раз и завершается.
|
||||
func runtimeRunnerCommand(runtime string) []string {
|
||||
@@ -280,16 +305,22 @@ func goJobModeEnv(runtime string) []corev1.EnvVar {
|
||||
return nil
|
||||
}
|
||||
|
||||
// getJobPodOutput находит под созданный Job-ом и возвращает его stdout (trimmed).
|
||||
// runner.py/runner.js печатают json.dumps(result) в stdout — это и есть return value функции.
|
||||
// getJobPodOutput находит под по labelSelector и возвращает его stdout+stderr (trimmed).
|
||||
// runner.py/runner.js печатают json.dumps(result) в stdout — return value функции.
|
||||
// Исключения/трейсбэки Python/Node пишут в stderr — поэтому собираем оба потока.
|
||||
// Если под не найден или логи недоступны — возвращает "completed successfully" как fallback.
|
||||
func getJobPodOutput(ctx context.Context, kube kubernetes.Interface, namespace, jobName string) string {
|
||||
// labelSelector передаётся снаружи — вызывающий код использует "functionjob=<name>" (наш лейбл,
|
||||
// выставляется на PodTemplate контроллером и не зависит от версии k8s).
|
||||
// НЕ использовать "job-name=" — этот встроенный лейбл удалён в k8s 1.27+ (у нас 1.34.1).
|
||||
func getJobPodOutput(ctx context.Context, kube kubernetes.Interface, namespace, labelSelector string) string {
|
||||
pods, err := kube.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{
|
||||
LabelSelector: "job-name=" + jobName,
|
||||
LabelSelector: labelSelector,
|
||||
})
|
||||
if err != nil || len(pods.Items) == 0 {
|
||||
return "completed successfully"
|
||||
}
|
||||
// Stdout: true, Stderr: true — собираем оба потока.
|
||||
// Python исключения идут в stderr, runner.py пишет результат в stdout.
|
||||
req := kube.CoreV1().Pods(namespace).GetLogs(pods.Items[0].Name, &corev1.PodLogOptions{})
|
||||
stream, err := req.Stream(ctx)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user