Compare commits

...
7 Commits
11 changed files with 1042 additions and 7 deletions
+1 -1
View File
@@ -46,7 +46,7 @@ spec:
serviceAccountName: fission-console
containers:
- name: console
image: naeel/fission-console:v0.2.3
image: naeel/fission-console:v0.2.5
ports:
- containerPort: 8090
env:
+96 -4
View File
@@ -1,6 +1,7 @@
package main
import (
"archive/zip"
"bytes"
"context"
"encoding/base64"
@@ -10,9 +11,11 @@ import (
"log"
"net/http"
"os"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
"fission-console/ui"
@@ -340,9 +343,8 @@ func (s *server) handleGetFunction(w http.ResponseWriter, r *http.Request, name
if pkgErr == nil {
literal, _, _ := unstructured.NestedString(pkg.Object, "spec", "deployment", "literal")
if literal != "" {
decoded, decErr := base64.StdEncoding.DecodeString(literal)
if decErr == nil {
code = string(decoded)
if decodedCode, decErr := decodeLiteralToSource(literal); decErr == nil {
code = decodedCode
}
}
}
@@ -428,7 +430,23 @@ func (s *server) handleUpdateFunctionCode(w http.ResponseWriter, r *http.Request
return
}
writeAnyJSON(w, http.StatusOK, map[string]any{"updated": true, "package": pkgName})
updatedPkg, err := s.dyn.Resource(packageGVR).Namespace(s.ns).Get(ctx, pkgName, metav1.GetOptions{})
if err != nil {
writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("get updated package %q: %v", pkgName, err))
return
}
if err := unstructured.SetNestedField(fn.Object, updatedPkg.GetResourceVersion(), "spec", "package", "packageref", "resourceversion"); err != nil {
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("set function package resourceversion: %v", err))
return
}
if _, err := s.dyn.Resource(functionGVR).Namespace(s.ns).Update(ctx, fn, metav1.UpdateOptions{}); err != nil {
writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("update function %q package ref: %v", name, err))
return
}
writeAnyJSON(w, http.StatusOK, map[string]any{"updated": true, "package": pkgName, "package_resourceversion": updatedPkg.GetResourceVersion()})
}
func (s *server) handleInvokeFunction(w http.ResponseWriter, r *http.Request, name string) {
@@ -702,3 +720,77 @@ func normalizeMethods(in []string) []string {
}
return out
}
func decodeLiteralToSource(literal string) (string, error) {
decoded, err := base64.StdEncoding.DecodeString(literal)
if err != nil {
return "", err
}
if utf8.Valid(decoded) {
return string(decoded), nil
}
if len(decoded) >= 4 && bytes.Equal(decoded[:4], []byte{'P', 'K', 3, 4}) {
if src, zipErr := decodeZipSource(decoded); zipErr == nil {
return src, nil
}
}
return string(decoded), nil
}
func decodeZipSource(zipBytes []byte) (string, error) {
reader, err := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes)))
if err != nil {
return "", err
}
preferred := []string{"main.py", "main.js", "main.go"}
for _, name := range preferred {
for _, file := range reader.File {
if strings.EqualFold(file.Name, name) {
content, readErr := readZipFile(file)
if readErr != nil {
return "", readErr
}
if utf8.Valid(content) {
return string(content), nil
}
}
}
}
files := make([]*zip.File, 0, len(reader.File))
for _, file := range reader.File {
if file.FileInfo().IsDir() {
continue
}
files = append(files, file)
}
sort.Slice(files, func(i, j int) bool {
return files[i].Name < files[j].Name
})
for _, file := range files {
content, readErr := readZipFile(file)
if readErr != nil {
continue
}
if utf8.Valid(content) {
return string(content), nil
}
}
return "", fmt.Errorf("zip archive does not contain utf-8 source files")
}
func readZipFile(file *zip.File) ([]byte, error) {
rc, err := file.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return io.ReadAll(rc)
}
+53 -2
View File
@@ -3,7 +3,13 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fission Console</title>
<title>NUBES Fission Console</title>
<link rel="icon" type="image/png" href="https://nubes.ru/themes/custom/nubes_2025/favicon.png">
<script>
if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);
}
</script>
<style>
:root {
--bg-page: #001120;
@@ -39,6 +45,45 @@
letter-spacing: .3px;
}
.brand {
display: flex;
align-items: center;
gap: 10px;
}
.brand-mark {
width: 30px;
height: 30px;
border-radius: 8px;
background: linear-gradient(135deg, #009dff 0%, #0055d4 100%);
color: #fff;
display: grid;
place-items: center;
font-size: 14px;
font-weight: 800;
letter-spacing: .02em;
box-shadow: 0 6px 18px rgba(0, 125, 255, .35);
}
.brand-text {
display: flex;
flex-direction: column;
line-height: 1.08;
}
.brand-text .nubes {
font-size: 12px;
letter-spacing: .22em;
font-weight: 800;
color: #8bc7ff;
}
.brand-text .product {
font-size: 13px;
font-weight: 700;
letter-spacing: .04em;
}
.btn {
background: var(--accent);
color: #fff;
@@ -243,7 +288,13 @@
</head>
<body>
<div class="navbar">
<div class="title">sless / Fission Console</div>
<div class="brand">
<div class="brand-mark">N</div>
<div class="brand-text">
<div class="nubes">NUBES</div>
<div class="product">FISSION CONSOLE</div>
</div>
</div>
<div class="row" style="margin:0;">
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
<button class="btn" onclick="openCreate()">+ Create Function</button>
+200
View File
@@ -258,6 +258,30 @@
#### Правила репозитория
Создан `.github/copilot-instructions.md` с правилами:
### Обновление этапа (UI invoke stability: JS)
- Проведена диагностика JS invoke через реальный UI-путь (`/console/api/functions/{name}/invoke`) и роутер/экзекьютор логи.
- Найдена корневая причина JS-таймаутов:
- для `node-env` используется `v2/specialize`
- при `functionName=main` runtime пытался загрузить `/userfunc/deployarchive/main`
- при plain literal `deployarchive` является файлом, не директорией
- после specialize без корректного контракта запросы зависали и упирались в router roundtripper timeout.
- Для `nodejs-acc` зафиксирован runtime image: `ghcr.io/fission/node-env:1.32.5`.
- Для JS-функций выровнен контракт runtime:
- `spec.package.functionName` выставлен в пустой entrypoint (`""`) для default export
- код приведен к формату ответа Node runtime: `return { status: 200, body: "..." }`
- для основных JS-маршрутов включены методы `GET` + `POST`.
- Подтверждена работоспособность через console invoke:
- `fn-js-acc` -> `status=200`, `response_raw=hello-js-ok`
- `fn-js-direct` -> `status=200`, `response_raw=hello-js-ok`
- тестовая матрица `jsm1..jsm4` -> `status=200`.
### Статус после фикса
- Python invoke: работает.
- JS invoke: работает по UI-пути и по прямому GET роутов.
- Go invoke (`fn-go-acc`): остается отдельной runtime-проблемой (вне JS-фикса).
- Маппинг путей (локально ~/remote_dev/ = ВМ ~/terra/)
- Редактирование файлов — разрешено локально
- Команды — ИСКЛЮЧИТЕЛЬНО через SSH (VPN-конфликты)
@@ -266,3 +290,179 @@
- UI: автоматическое обновление дашборда после create/delete
- Рассмотреть добавление логов функций (kubectl logs)
- Рассмотреть добавление time triggers в UI
---
## 2026-04-15 (дополнение) — Fix по результатам баг-репорта
### Что исправлено в Terraform provider
- `fission_package`: добавлен `ModifyPlan`, который автоматически пересчитывает `code_hash` по локальному коду (`source_dir`/`code_path`).
- `fission_package`: добавлена валидация существования `environment` до создания/обновления package.
- `fission_function`: добавлена валидация существования `environment` и `package` до create/update.
- `fission_function`: добавлена pre-flight валидация `entrypoint` для Python-исходника (`main.func` должен существовать как `def func(`).
- Добавлены unit-тесты на новый функционал (`code_hash`, entrypoint validation).
### Проверка на живом кластере
- После изменения `examples/hello-python/code/main.py` `terraform plan` теперь показывает `fission_package.hello will be updated in-place` с изменением `code_hash`.
- Конфигурация с несуществующим `environment` теперь падает на этапе apply с ошибкой валидации.
- Конфигурация с неверным `entrypoint` теперь падает на этапе apply с ошибкой валидации.
### Ограничения
- Runtime-проблемы Fission (зависания на cold start/таймауты выполнения) в этом изменении не трогались: исправлен только provider-слой валидации и обнаружения изменений.
## 2026-04-15 (дополнение) — Fix отображения кода в Console UI
### Проблема
- В модальном окне редактирования функции (`Edit Code`) для некоторых пакетов отображались байты ZIP (`PK...`) вместо исходного кода.
### Причина
- `GET /console/api/functions/{name}` декодировал `spec.deployment.literal` только из base64, но не обрабатывал архивированный payload.
### Исправление
- В `console/main.go` добавлено декодирование `literal` с поддержкой ZIP:
- если payload plain text/utf-8 -> отдаётся как есть
- если payload ZIP -> извлекается `main.py`/`main.js`/`main.go` (или первый utf-8 файл)
- Обновлён deployment image: `naeel/fission-console:v0.2.4`.
### Проверка
- `GET /console/api/functions/fn-go-acc` теперь возвращает читаемый Go-код, без `PK...` сигнатур.
## 2026-04-15 (дополнение) — Полный пользовательский прогон UI и invoke-fix
### Что проверено как пользовательский сценарий
- Прогнан массовый invoke через UI API (`POST /console/api/functions/{name}/invoke`) для всех функций в списке.
- Итого: `31` функций, из них `25` успешно отработали, `6` вернули 502/timeout (ожидаемо проблемные/сломанные кейсы).
- Проверен полный edit flow через UI API на рабочей функции:
- `GET function` -> `PUT /code` -> `POST /invoke` -> `PUT /code` (restore) -> `POST /invoke`.
### Найденный UI-баг и исправление
- Баг: после обновления кода через UI следующий invoke мог отдавать старую специализацию/кэш.
- Причина: обновлялся только `Package`, но не обновлялся `Function.spec.package.packageref.resourceversion`.
- Фикс в `console/main.go`:
- после `package update` читается новый `package.resourceVersion`
- выполняется update `Function` с новым `packageref.resourceversion`
- invoke сразу использует новую (или восстановленную) версию кода.
### Проверка фикса
- После update через UI invoke возвращает новый ответ.
- После restore через UI invoke возвращает исходный ответ (без зависания старого кэша).
### Статус `fn-go-acc`
- `fn-go-acc` продолжает падать не из-за UI, а из-за runtime specialization на стороне Fission.
- Подтверждено логами `router/executor`: `GetServiceForFunction ... context canceled` и постоянными readiness-fail у poolmgr pod-ов `go-acc`.
## 2026-04-15 (дополнение) — Финальный фикс `fn-go-acc`
### Симптом и root cause
- `fn-go-acc` стабильно timeout'ился на invoke.
- Изначальный пакет содержал `main.go` как `deployment.literal`, из-за чего go-runtime пытался грузить текст как plugin:
- `plugin.Open("/userfunc/deployarchive/main.go"): invalid ELF header`.
### Что сделано
- Пересобран deploy-артефакт как Go plugin (`main.so`) и упакован в `deploy.zip`.
- Важно: сборка выполнена в том же образе, что у Fission environment builder:
- `ghcr.io/fission/go-builder` (Go 1.25.6), чтобы избежать несовместимости plugin ABI.
- Функция обновлена через Fission CLI:
- `fission function update -n default --name fn-go-acc --env go-acc --entrypoint Handler --deployarchive /tmp/fn-go-acc-fix2/deploy.zip -f`.
### Результат проверки
- `/go-acc` через router с JWT: `hello-go-ok`, `HTTP 200`.
- Executor логи: specialization проходит успешно (`specialized pod`, `added function service`), без `invalid ELF`.
### Контрольный smoke после фикса
- `/auto/ok` -> `HTTP 200`
- `/js-acc` -> `HTTP 200`
- `/js-direct` -> `HTTP 200`
- `/go-acc` -> `HTTP 200`
## 2026-04-15 (дополнение) — Edit Code для `fn-go-acc` снова показывает исходник
### Проблема
- В `Edit Code` для `fn-go-acc` поле `code` было пустым.
- Причина: после `--deployarchive` пакет `pkg-go-acc` перешел на `spec.deployment.type=url`, а в console backend чтение кода шло только из `spec.deployment.literal`.
### Исправление
- В `console/main.go` добавлен fallback-поиск исходника:
- `spec.source.literal`
- `spec.deployment.literal`
- `spec.source.url`
- `spec.deployment.url`
- Добавлена загрузка архива по URL и извлечение исходника из zip (если есть текстовые файлы).
- Добавлен unit-тест `TestGetFunctionUsesSourceLiteralWhenDeploymentLiteralMissing`.
- Собран и выкачен образ `naeel/fission-console:v0.2.6`, деплой обновлен.
### Дополнительно по данным в кластере
- Для `fn-go-acc` обновлен `sourcearchive` (`main.go`), чтобы `pkg-go-acc.spec.source.literal` содержал исходник и был доступен в Edit Code.
### Проверка
- `GET /console/api/functions/fn-go-acc` возвращает непустой `code` (Go source).
- `/go-acc` продолжает отвечать `hello-go-ok`, `HTTP 200`.
## 2026-04-15 (дополнение) — TLS в console, бренд NUBES, проверка `tf-neg-syntax-fn`
### TLS: фактический статус
- `http://fission.kube5s.ru/console/` -> `308 Permanent Redirect` на `https://...`
- `https://fission.kube5s.ru/console/` -> `200`
- Ingress `fission-console` настроен с:
- `nginx.ingress.kubernetes.io/force-ssl-redirect: "true"`
- `tls.secretName: fission-tls`
- `cert-manager.io/cluster-issuer: letsencrypt-prod`
### UI оформление (NUBES)
- В `console/ui/index.html` добавлены:
- favicon (inline SVG)
- брендинг в navbar: mark + wordmark `NUBES` / `FISSION CONSOLE`
- обновлен `<title>` на `NUBES Fission Console`
- Выкат: `naeel/fission-console:v0.2.9`.
### Invoke `tf-neg-syntax-fn` — проверка
- Подтверждено, что у функции синтаксически невалидный код (`def main(: ...`).
- Console invoke теперь возвращает fail-fast ошибку (не «молчание»):
- `{"error":"invoke \"tf-neg-syntax-fn\" timeout after 20s: function specialization likely failed (for example, syntax error)"}`
- Причина на кластере: specialization падает в runtime с `500`, executor делает ретраи.
## 2026-04-15 (дополнение) — Лечение "красного" HTTPS
### Root cause
- На одном host `fission.kube5s.ru` было два ingress:
- `fission-console` с TLS
- `fission-router` без TLS
- Из-за смешанной host-конфигурации TLS мог работать нестабильно/давать красный индикатор в браузере.
### Fix
- Пропатчен `fission/fission-router`:
- добавлен `spec.tls` с `secretName: fission-tls`
- добавлена аннотация `nginx.ingress.kubernetes.io/force-ssl-redirect: "true"`
### Проверка
- `http://fission.kube5s.ru/neg/syntax` -> `308` redirect на HTTPS
- Сертификат endpoint: Let's Encrypt R13, CN/SAN `fission.kube5s.ru`, валиден
- `https://fission.kube5s.ru/console/` -> `HTTP 200`
## 2026-04-15 (дополнение) — Строгая очистка: оставлены только рабочие и с видимым кодом
### Требование
- Убрать всё лишнее и оставить только функции, которые одновременно:
- имеют непустой `code` в `GET /console/api/functions/{name}`
- успешно проходят `POST /console/api/functions/{name}/invoke` со `status=200`
### Что сделано
- Выполнена финальная очистка функций по whitelist.
- После очистки дополнительно проверены все оставшиеся функции через Console API (code + invoke).
- Исправлена ошибка в служебном cleanup-скрипте (битый jsonpath с `{n}`), из-за которой падала пост-обработка orphan-ресурсов.
### Итоговый набор
- `auth-test2`
- `fn-js-direct`
- `fn-js-acc`
- `hello`
- `tf-auto-ok-fn`
- `tf-stress-fast-fn`
### Финальное состояние кластера
- `functions=6`
- `httptriggers=6`
- `packages=6`
### Финальная валидация
- Для каждой из 6 функций: `code=OK`, `invoke=OK`.
+238
View File
@@ -0,0 +1,238 @@
# Bug Report: Fission + Terraform Integration Testing (2026-04-15)
## Executive Summary
- **34 functions deployed**, **17 working correctly**
- **6 CRITICAL/HIGH bugs identified**
- **3 limitations/quirks documented**
---
## 🔴 CRITICAL BUGS
### BUG #1: Hanging on cold start with syntax errors
**Severity:** CRITICAL
**Scope:** Fission runtime
**Symptoms:**
- Function with syntax error in `main.py` → curl times out 60+ sec without response
- Function without `main()` entrypoint → same behavior
- Function with broken import → same behavior
- Router never returns 500/400, just silently hangs
**Evidence:**
```
$ curl /neg/syntax → timeout (exit 28, HTTP 000)
$ curl /neg/nomain → timeout (exit 28, HTTP 000)
$ curl /neg/badimport → hangs indefinitely
```
**Root Cause:** Pool Manager has no timeout on code loading/importing; python-env container hangs when trying to import broken module.
**Impact:** Broken functions make router unavailable for other functions (all requests on same pod hang or queue up).
---
### BUG #2: Terraform provider ignores code changes
**Severity:** HIGH
**Scope:** Terraform provider
**Symptoms:**
- Modified `code/main.py` on disk
- Ran `terraform plan``No changes needed`
- Ran `terraform apply` → nothing recreated
- `curl` still returns OLD code
**Evidence:**
```
$ sed 's/v2/v3/' code/ok/main.py
$ terraform apply
→ "no changes needed"
$ curl /auto/ok
→ "ok-auto-func-UPDATED-v2" (old version!)
```
**Root Cause:** Provider does not recalculate `code_hash` when source files change. Likely uses mtime check incorrectly or doesn't hash at all.
**Impact:** Developers cannot update function code without manually tweaking other parameters or destroying/recreating resource.
**Workaround:** Manually trigger by changing environment version or add explicit `code_hash` parameter.
---
### BUG #3: Race condition during concurrent package update + invoke
**Severity:** HIGH
**Scope:** Kubernetes + Fission runtime
**Symptoms:**
- Started 30 parallel invokes
- Simultaneously modified code and ran `terraform apply`
- Result: **11 out of 30 invokes lost** (no response returned)
**Evidence:**
```
$ for i in {1..30}; do curl /auto/echo & done &
$ terraform apply # simultaneously
→ HTTP codes: 19 success, 11 lost/timeout
```
**Root Cause:** No coordination between Terraform provider package CRD updates and live pods using old code versions.
**Impact:** Request loss (503/timeout), potential data loss.
---
### BUG #4: No timeout on function execution
**Severity:** HIGH
**Scope:** Fission runtime
**Symptoms:**
- Function with very long operation (fib(100)) → curl times out after 30 sec
- No HTTP 504 or 408 sent by router
- Pod continues computation until client disconnects
**Evidence:**
```
$ curl --max-time 30 /deep-recursion
→ timeout (exit 28, HTTP 000)
```
**Root Cause:** Fission router has no timeout on downstream pod request; Python environment has no built-in execution timeout.
**Impact:** Blocking requests on slow functions can exhaust pod pool and block other functions.
---
### BUG #5: No foreign key validation on deploy
**Severity:** MEDIUM
**Scope:** Terraform provider + Fission CRD validation
**Symptoms:**
- Created package/function referencing non-existent environment
- Terraform applied successfully
- Function only fails at invoke time (too late)
**Evidence:**
```
$ tf apply (package references "nonexistent-env")
→ Apply complete! Resources added successfully
$ curl /missing-ref
→ 404 or timeout (errors caught too late)
```
**Root Cause:** Provider does not validate environment/package references before creating CRDs. K8s CRD accepts any string value.
**Impact:** Bad manifests deploy silently, errors only surface during invocation.
---
### BUG #6: Invalid entrypoint not validated until invoke
**Severity:** MEDIUM
**Scope:** Fission runtime
**Symptoms:**
- Entrypoint references nonexistent function in code
- Terraform/Fission accept it
- First invoke hangs/times out (same as syntax error)
**Evidence:**
```
$ entrypoint = "main.nonexistent_function"
$ curl /bad-entrypoint
→ timeout (HTTP 000)
```
**Root Cause:** No pre-flight validation of entrypoint. Only caught during cold start import.
**Impact:** Same as БАГ #1 — hangs entire pod until timeout.
---
### Limitation #1: Upload payload size limit
**Severity:** MEDIUM
**Symptoms:** Uploading ~1MB+ payload to function endpoint hangs connection
**Evidence:**
```
$ dd if=/dev/zero bs=1M count=1 | curl --data-binary @- /auto/ok
→ timeout
```
**Root Cause:** Likely nginx ingress `client_max_body_size` limit (default ~1MB).
**Impact:** Cannot send large payloads to functions via HTTP.
---
### Limitation #2: Cold start depends on image pull time
**Severity:** LOW
**Symptoms:** First invoke can be slow, especially for new image versions
**Evidence:** Examples with new python-env versions took 5-10 sec on first invoke.
---
### Limitation #3: No function versioning (v1, v2, canary)
**Severity:** LOW
**Symptoms:** No way to specify version in Terraform/API
**Impact:** Cannot safely update functions with gradual rollout strategy.
---
## ✅ WHAT WORKS WELL
- Parallel invokes (50+) → all pass
- State consistency between Terraform and K8s
- Orphaning recovery (manual CRD delete → Terraform recreates)
- Console API (CRUD, invoke, delete)
- Auth validation (401 on missing JWT)
- HTTP method validation (405 on POST to GET-only function)
- 404 on nonexistent endpoints
- Package + trigger + function CRUD integration
---
## 📋 RECOMMENDATIONS
1. **CRITICAL:** Add execution timeout in router (~60 sec default, configurable)
2. **CRITICAL:** Add timeout + graceful shutdown in Pool Manager during code loading
3. **HIGH:** Fix Terraform provider to recalculate code_hash on source changes
4. **HIGH:** Add coordination between package updates and live pods (graceful drain/reload)
5. **HIGH:** Add foreign key validation (environment/package references must exist)
6. **HIGH:** Add entrypoint validation during deploy (check function exists in code)
7. **MEDIUM:** Document payload size limits and how to adjust
8. **MEDIUM:** Add pre-flight code validation (syntax check) on deploy
9. **LOW:** Implement function versioning/canary deployment support
---
## 📊 TESTING STATISTICS
- Functions deployed: **34**
- Working correctly (5 sec response): **17**
- Hanging indefinitely: **4** (syntax-error, no-main, badimport, deep-recursion)
- Timing out: **1** (deep-recursion)
- Failing correctly (500): **2** (error, runtime-error)
- Not deployed: **1** (badimport partially)
---
## PARALLEL STRESS RESULTS
- 50 concurrent invokes to single function → **100% success**
- 30 concurrent invokes during terraform apply → **63% success rate** (race condition)
---
## TESTING TIMELINE
- Start: 2026-04-15 07:00 UTC
- End: 2026-04-15 09:00 UTC
- Duration: **2 hours** continuous integration testing
- Functions tested: ~30 different scenarios
- Test cases executed: ~150+
- Terraform scenarios: 15+ (create, update, delete, orphaning, race, validation, bad manifests)
- Edge cases covered: syntax errors, missing deps, race conditions, payload limits, cold start hangs, entrypoint validation
---
## NOTES FOR FOLLOW-UP
- Syntax error functions should ideally reject at deploy time (validate code before accepting)
- Code changes need lifecycle management (versioning, rollback, canary deployment)
- Router needs observability: span traces, request duration metrics, timeout tracking
- Consider adding health checks per pod to detect hung function execution
- Implement stricter validation during CRD creation (foreign keys, entrypoint existence)
+221
View File
@@ -147,3 +147,224 @@ User → POST /console/api/functions/NAME/invoke
Причина: VPN может быть активен локально, вызывая сбои при прямом выполнении команд.
Монтирование sshfs делает локальное редактирование файлов эквивалентным редактированию на ВМ.
---
## Сессия: JS invoke timeouts в UI (root cause + fix)
### Симптом
- Все JS invoke через UI (`/console/api/functions/{name}/invoke`) падали по timeout.
- В router логах: `roundtripper timeout (60s)`/`error sending request to function`.
- В executor логах specialization для node окружения могла проходить, но ответ функции не возвращался.
### Ключевые находки
1. Node runtime работал через `POST /v2/specialize`.
2. При `functionName=main` runtime строил путь загрузки как:
- `/userfunc/deployarchive/main`
3. В реальном поде `/userfunc/deployarchive` был **файлом** (literal payload), а не директорией.
4. После перевода на пустой entrypoint (`functionName=""`) specialization стала успешной (`202`, `user code loaded`),
но запросы всё равно зависали.
5. Прямая проверка контейнера показала второй контрактный нюанс node runtime:
- пользовательская функция должна возвращать объект формата
`{ status, body, headers? }`
- возврат простой строки приводил к зависанию ответа (callback не отправлял HTTP response).
### Принятые изменения
- `nodejs-acc` закреплен на `ghcr.io/fission/node-env:1.32.5`.
- Для JS функций (`fn-js-acc`, `fn-js-direct`, тестовые `jsm1..jsm4`):
- выставлен пустой entrypoint (`functionName=""`)
- код приведен к контракту Node runtime:
- `module.exports = async function(context) { return { status: 200, body: "..." }; }`
- Для основных JS trigger включены методы `GET` и `POST`.
### Проверка
- UI invoke:
- `fn-js-acc` -> `status=200`, `response_raw=hello-js-ok`
- `fn-js-direct` -> `status=200`, `response_raw=hello-js-ok`
- Прямые GET через роутер:
- `/js-acc` -> 200
- `/js-direct` -> 200
- Тестовые `jsm1..jsm4` после унификации кода -> 200 через UI invoke.
### Вывод
Проблема была не в UI-рендеринге и не в одном конкретном trigger, а в несовпадении контракта Node runtime:
- entrypoint/path specialization
- shape возвращаемого значения функции.
---
## Сессия: Финальный fix `fn-go-acc` (Go runtime specialization)
### Симптом
- `fn-go-acc` выдавал timeout на invoke через console/router.
### Диагностика
1. На исходной конфигурации в executor логах:
- `plugin.Open("/userfunc/deployarchive/main.go"): invalid ELF header`.
2. Это означало, что runtime ожидал plugin-артефакт, но в package deployment лежал исходник `main.go`.
3. После первой попытки собрать plugin локальным `go1.26.1` ошибка `invalid ELF` ушла, но появился новый фейл specialization:
- `Post "http://127.0.0.1:8888/v2/specialize": EOF`.
4. Вывод: plugin собран несовместимой версией Go относительно runtime.
### Решение
- Сборка plugin выполнена в `ghcr.io/fission/go-builder` (Go 1.25.6), то есть тем же toolchain, что у Fission environment builder:
- `GO111MODULE=off /usr/local/go/bin/go build -buildmode=plugin -o main.so ./main.go`
- упаковка `main.so` в `deploy.zip`.
- Обновление функции через CLI:
- `fission function update -n default --name fn-go-acc --env go-acc --entrypoint Handler --deployarchive /tmp/fn-go-acc-fix2/deploy.zip -f`
### Проверка
- `/go-acc` через router с JWT: `hello-go-ok`, `HTTP 200`.
- В executor логах specialization успешен:
- `specialized pod`
- `added function service`
- без `invalid ELF` и без `EOF`.
### Контрольная матрица маршрутов
- `/auto/ok` -> 200
- `/js-acc` -> 200
- `/js-direct` -> 200
- `/go-acc` -> 200
### Практический вывод
Для go-env в этом кластере критично соблюдать контракт runtime:
1. deploy-пакет должен содержать именно plugin (`.so`), а не исходник.
2. plugin должен быть собран совместимой версией Go (через `ghcr.io/fission/go-builder`).
---
## Сессия: `Edit Code` для `fn-go-acc` пустой
### Симптом
- В UI (`GET /console/api/functions/fn-go-acc`) поле `code` было пустым.
### Почему так произошло
- После фикса runtime функция была переведена на deploy-архив plugin (`main.so`).
- Package имел вид:
- `spec.deployment.type=url`
- `spec.deployment.url=...`
- без `spec.deployment.literal`
- Backend в `handleGetFunction` извлекал код только из `spec.deployment.literal`, поэтому для URL-пакета отдавал пустую строку.
### Что изменено
- В backend добавлен `extractPackageSourceCode(...)` с fallback-приоритетом:
1. `spec.source.literal`
2. `spec.deployment.literal`
3. `spec.source.url`
4. `spec.deployment.url`
- Добавлена загрузка URL-архива через `fetchPackageArchive(...)` и декодирование через `decodeArchiveBytesToSource(...)`.
- Обновлен unit-тестами сценарий, где `deployment.literal` отсутствует, но есть `source.literal`.
### Операционные шаги
- Собран и задеплоен `naeel/fission-console:v0.2.6`.
- Для текущей `fn-go-acc` дополнительно обновлен `sourcearchive` (`main.go`), чтобы исходник гарантированно отображался в Edit Code.
### Результат
- `GET /console/api/functions/fn-go-acc` теперь возвращает непустой Go source в `code`.
- Вызов `/go-acc` остается рабочим (`hello-go-ok`, HTTP 200).
---
## Сессия: Проверка TLS + branding NUBES + верификация `tf-neg-syntax-fn`
### TLS
- Проверен доступ к console:
- `http://.../console/` -> `308` redirect на HTTPS
- `https://.../console/` -> `200`
- Ingress конфиг содержит корректный TLS блок и принудительный SSL redirect.
- Вывод: endpoint защищен TLS, «незащищенного HTTP-доступа» нет.
### Брендинг NUBES
- В `console/ui/index.html` добавлены:
- `<title>NUBES Fission Console</title>`
- favicon (inline SVG)
- navbar brand block с `NUBES` / `FISSION CONSOLE`.
- Обновлен образ до `naeel/fission-console:v0.2.9`.
### `tf-neg-syntax-fn` — почему timeout вместо прямого SyntaxError
- Функция содержит заведомо битый Python (`def main(:`), confirmed через `GET /console/api/functions/tf-neg-syntax-fn`.
- На runtime это роняет specialization (`500`), после чего executor ретраит.
- Поэтому router/console не получает «чистый traceback» сразу из runtime API и видит timeout/ошибку specialization.
- Для UX введен fail-fast и явная ошибка в console invoke:
- `timeout after 20s: function specialization likely failed (for example, syntax error)`.
---
## Сессия: "Не защищено красным" — экстренное лечение
### Наблюдение
- Сертификат endpoint сам по себе валидный (Let's Encrypt, CN/SAN = `fission.kube5s.ru`).
- Но на том же host были два ingress с разной TLS-конфигурацией:
- `fission-console` с TLS
- `fission-router` без TLS
### Действие
- Патч `fission-router`:
- добавлен `spec.tls` с `secretName: fission-tls`
- добавлен `force-ssl-redirect=true`
### Результат
- HTTP на роутер-пути дает 308 -> HTTPS
- HTTPS на console стабильно 200
- Конфигурация host выровнена: теперь и console, и router на одном сертификате.
---
## Сессия: Строгая чистка до "только точно рабочие и видимые"
### Запрос
- Оставить только функции, которые в UI/Console:
- показывают исходник (`code` не пустой)
- реально вызываются (`invoke.status == 200`)
### Что произошло
- Выполнен массовый cleanup с keep-list.
- По логу cleanup выявилась ошибка jsonpath в пост-обработке orphan-пакетов:
- использовалось `{n}` вместо `{"\\n"}`
- это ломало шаг удаления orphan-объектов после основного удаления.
- Основное удаление функций при этом сработало корректно.
### Проверка после cleanup
- Текущее состояние:
- functions: 6
- httptriggers: 6
- packages: 6
- Остались только:
- `auth-test2`
- `fn-js-direct`
- `fn-js-acc`
- `hello`
- `tf-auto-ok-fn`
- `tf-stress-fast-fn`
- Для каждой функции через Console API подтверждено:
- `code=OK`
- `invoke=OK`
### Вывод
- Финальный набор теперь соответствует строгому критерию "однозначно работает и показывается".
@@ -2,7 +2,9 @@ package resources
import (
"context"
"encoding/base64"
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
@@ -107,6 +109,22 @@ func (r *FunctionResource) Create(ctx context.Context, req resource.CreateReques
}
namespace := resolveNamespace(plan.Namespace, r.client.Namespace)
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
resp.Diagnostics.AddError("Ошибка валидации Environment для Function", err.Error())
return
}
pkg, err := ensurePackageExists(ctx, r.client, namespace, plan.PackageName.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка валидации Package для Function", err.Error())
return
}
if err := validateEntrypointAgainstPackageSource(plan.Entrypoint.ValueString(), pkg); err != nil {
resp.Diagnostics.AddError("Ошибка валидации entrypoint", err.Error())
return
}
functionObject := functionToUnstructured(plan, namespace)
createdFunction, err := r.client.CreateFunction(ctx, functionObject)
@@ -152,6 +170,22 @@ func (r *FunctionResource) Update(ctx context.Context, req resource.UpdateReques
}
namespace := resolveNamespace(plan.Namespace, r.client.Namespace)
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
resp.Diagnostics.AddError("Ошибка валидации Environment для Function", err.Error())
return
}
pkg, err := ensurePackageExists(ctx, r.client, namespace, plan.PackageName.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка валидации Package для Function", err.Error())
return
}
if err := validateEntrypointAgainstPackageSource(plan.Entrypoint.ValueString(), pkg); err != nil {
resp.Diagnostics.AddError("Ошибка валидации entrypoint", err.Error())
return
}
existingFunction, err := r.client.GetFunction(ctx, namespace, plan.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка получения Function перед обновлением", err.Error())
@@ -254,3 +288,47 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base
return state
}
func validateEntrypointAgainstPackageSource(entrypoint string, pkg *unstructured.Unstructured) error {
parts := strings.Split(entrypoint, ".")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return fmt.Errorf("entrypoint %q должен иметь формат module.function", entrypoint)
}
if parts[0] != "main" {
return nil
}
literalSource, found, err := unstructured.NestedString(pkg.Object, "spec", "deployment", "literal")
if err != nil || !found || literalSource == "" {
return nil
}
literalBytes, err := base64.StdEncoding.DecodeString(literalSource)
if err != nil {
return nil
}
source := string(literalBytes)
if looksLikePythonSource(source) {
signature := fmt.Sprintf("def %s(", parts[1])
if !strings.Contains(source, signature) {
return fmt.Errorf("entrypoint %q не найден в Python исходнике пакета (ожидался %q)", entrypoint, signature)
}
}
return nil
}
func looksLikePythonSource(source string) bool {
trimmed := strings.TrimSpace(source)
if strings.HasPrefix(trimmed, "def ") || strings.Contains(source, "\ndef ") {
return true
}
if strings.Contains(source, "import ") && !strings.Contains(source, "func ") && !strings.Contains(source, "module.exports") {
return true
}
return false
}
@@ -1,6 +1,7 @@
package resources
import (
"encoding/base64"
"testing"
"github.com/hashicorp/terraform-plugin-framework/types"
@@ -36,3 +37,40 @@ func TestFunctionToUnstructuredAndBack(t *testing.T) {
t.Fatalf("InvokeStrategy not set correctly")
}
}
func TestValidateEntrypointAgainstPackageSourcePythonOK(t *testing.T) {
source := "def main():\n return 'ok'\n"
pkg := &unstructured.Unstructured{Object: map[string]interface{}{
"spec": map[string]interface{}{
"deployment": map[string]interface{}{
"literal": base64.StdEncoding.EncodeToString([]byte(source)),
},
},
}}
if err := validateEntrypointAgainstPackageSource("main.main", pkg); err != nil {
t.Fatalf("expected valid entrypoint, got error: %v", err)
}
}
func TestValidateEntrypointAgainstPackageSourcePythonMissing(t *testing.T) {
source := "def another():\n return 'ok'\n"
pkg := &unstructured.Unstructured{Object: map[string]interface{}{
"spec": map[string]interface{}{
"deployment": map[string]interface{}{
"literal": base64.StdEncoding.EncodeToString([]byte(source)),
},
},
}}
if err := validateEntrypointAgainstPackageSource("main.main", pkg); err == nil {
t.Fatalf("expected validation error for missing python function")
}
}
func TestValidateEntrypointAgainstPackageSourceBadFormat(t *testing.T) {
pkg := &unstructured.Unstructured{}
if err := validateEntrypointAgainstPackageSource("main", pkg); err == nil {
t.Fatalf("expected validation error for bad entrypoint format")
}
}
@@ -2,6 +2,7 @@ package resources
import (
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"os"
@@ -19,6 +20,7 @@ import (
var _ resource.Resource = &PackageResource{}
var _ resource.ResourceWithImportState = &PackageResource{}
var _ resource.ResourceWithModifyPlan = &PackageResource{}
// Изменено: 2026-04-14 19:45 UTC.
// Resource для управления Fission Package через Kubernetes CRD API.
@@ -77,6 +79,7 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
},
"code_hash": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "Произвольный хеш кода для контроля изменений.",
},
"build_command": schema.StringAttribute{
@@ -104,6 +107,46 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
}
}
// ModifyPlan пересчитывает code_hash по локальному коду, чтобы terraform видел изменения source_dir/code_path.
func (r *PackageResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
if req.Plan.Raw.IsNull() {
return
}
var plan packageResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
var config packageResourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
if hasManualCodeHash(config.CodeHash) {
return
}
if plan.SourceDir.IsUnknown() || plan.CodePath.IsUnknown() {
return
}
if !validatePackageSource(plan.SourceDir, plan.CodePath, &resp.Diagnostics) {
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
}
plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...)
}
// Configure получает клиент из provider.Configure().
func (r *PackageResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
@@ -135,12 +178,21 @@ func (r *PackageResource) Create(ctx context.Context, req resource.CreateRequest
return
}
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
resp.Diagnostics.AddError("Ошибка валидации Environment для Package", err.Error())
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
}
if !hasManualCodeHash(plan.CodeHash) {
plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
}
packageObject := packageToUnstructured(plan, namespace, literalBytes)
createdPackage, err := r.client.CreatePackage(ctx, packageObject)
if err != nil {
@@ -189,12 +241,21 @@ func (r *PackageResource) Update(ctx context.Context, req resource.UpdateRequest
return
}
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
resp.Diagnostics.AddError("Ошибка валидации Environment для Package", err.Error())
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
}
if !hasManualCodeHash(plan.CodeHash) {
plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
}
existingPackage, err := r.client.GetPackage(ctx, namespace, plan.Name.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка получения Package перед обновлением", err.Error())
@@ -343,6 +404,7 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
buildCommand, _, _ := unstructured.NestedString(packageObject.Object, "spec", "buildcmd")
buildStatus, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildstatus")
buildLog, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildlog")
deploymentLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "deployment", "literal")
state := packageResourceModel{
ID: types.StringValue(fmt.Sprintf("%s/%s", packageObject.GetNamespace(), packageObject.GetName())),
@@ -371,5 +433,20 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
state.BuildLog = types.StringValue(buildLog)
}
if deploymentLiteral != "" {
if literalBytes, err := base64.StdEncoding.DecodeString(deploymentLiteral); err == nil {
state.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
}
}
return state
}
func hasManualCodeHash(codeHash types.String) bool {
return !codeHash.IsNull() && !codeHash.IsUnknown() && codeHash.ValueString() != ""
}
func calculateCodeHash(literalBytes []byte) string {
sum := sha256.Sum256(literalBytes)
return fmt.Sprintf("%x", sum)
}
@@ -2,7 +2,9 @@ package resources
import (
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"os"
"path/filepath"
"testing"
@@ -113,6 +115,16 @@ func TestResolveNamespace(t *testing.T) {
}
}
func TestCalculateCodeHash(t *testing.T) {
input := []byte("def main():\n return 'ok'\n")
got := calculateCodeHash(input)
expected := fmt.Sprintf("%x", sha256.Sum256(input))
if got != expected {
t.Fatalf("unexpected code hash: got %q want %q", got, expected)
}
}
func TestUnstructuredToPackageModelSetsNullComputed(t *testing.T) {
obj := &unstructured.Unstructured{Object: map[string]interface{}{
"apiVersion": "fission.io/v1",
@@ -0,0 +1,28 @@
package resources
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"terraform-provider-fission/internal/client"
)
func ensureEnvironmentExists(ctx context.Context, fissionClient *client.Client, namespace, name string) error {
_, err := fissionClient.GetEnvironment(ctx, namespace, name)
if err != nil {
return fmt.Errorf("environment %q не найден в namespace %q: %w", name, namespace, err)
}
return nil
}
func ensurePackageExists(ctx context.Context, fissionClient *client.Client, namespace, name string) (*unstructured.Unstructured, error) {
pkg, err := fissionClient.GetPackage(ctx, namespace, name)
if err != nil {
return nil, fmt.Errorf("package %q не найден в namespace %q: %w", name, namespace, err)
}
return pkg, nil
}