Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50ba09e1b6 | ||
|
|
903610bf71 | ||
|
|
0a1708e682 | ||
|
|
579bf97e17 | ||
|
|
c40fc47025 | ||
|
|
fd236d87ea |
+11
-220
@@ -1,223 +1,14 @@
|
|||||||
# Правила работы агента в проекте fission
|
# Правила
|
||||||
|
|
||||||
## ГЛАВНОЕ ПРАВИЛО
|
## ⛔ ОТВЕЧАТЬ КРАТКО — АБСОЛЮТНОЕ ПРАВИЛО
|
||||||
|
- Вопрос → короткий ответ → СТОП. Не рассуждать, не исследовать без команды.
|
||||||
|
- НЕ делать ничего "попутно" без явной просьбы. Сделал — стоп — ждёшь команды.
|
||||||
|
|
||||||
**НЕ "СОВЕРШЕНСТВОВАТЬ" РАБОЧИЙ КОД БЕЗ ЯВНОГО УКАЗАНИЯ.**
|
> Подробные правила: [`.github/pravila.md`](pravila.md)
|
||||||
|
|
||||||
---
|
1. Не трогать рабочий код без явного указания.
|
||||||
|
2. Файлы редактировать локально — `~/remote_dev/` = `~/terra/` на ВМ (sshfs), SCP не нужен.
|
||||||
## Файловая система и выполнение команд
|
3. Все команды — **только через SSH**, никогда локально:
|
||||||
|
```bash
|
||||||
### Маппинг путей
|
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 'КОМАНДА'
|
||||||
|
```
|
||||||
Локальная папка `~/remote_dev/` примонтирована через sshfs к `~/terra/` на ВМ `5.172.178.213`.
|
|
||||||
Это **одна и та же файловая система**:
|
|
||||||
|
|
||||||
| Локально (VS Code) | На ВМ |
|
|
||||||
|----------------------------------|-------------------------------|
|
|
||||||
| `/home/naeel/remote_dev/fission` | `/home/naeel/terra/fission` |
|
|
||||||
| `/home/naeel/remote_dev/sless` | `/home/naeel/terra/sless` |
|
|
||||||
| `/home/naeel/remote_dev/IoT` | `/home/naeel/terra/IoT` |
|
|
||||||
|
|
||||||
Любой файл, сохранённый локально через VS Code, **мгновенно виден на ВМ**. SCP не нужен.
|
|
||||||
|
|
||||||
### Что можно делать локально
|
|
||||||
|
|
||||||
- **Редактировать файлы** — через VS Code, replace_string_in_file, create_file и т.д. Изменения сразу на ВМ.
|
|
||||||
- **Читать файлы** — read_file, grep_search, file_search, semantic_search — всё разрешено.
|
|
||||||
|
|
||||||
### Что ЗАПРЕЩЕНО локально
|
|
||||||
|
|
||||||
**Все команды выполнять ИСКЛЮЧИТЕЛЬНО через SSH на ВМ:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 'КОМАНДА'
|
|
||||||
```
|
|
||||||
|
|
||||||
**Причина:** локально может быть активен VPN, что вызывает сбои при выполнении сетевых команд, обращениях к кластеру, Docker и пр.
|
|
||||||
|
|
||||||
Запрещено запускать локально (без ssh):
|
|
||||||
- `go build`, `go test`, `go mod tidy`
|
|
||||||
- `docker build`, `docker push`
|
|
||||||
- `kubectl`, `helm`
|
|
||||||
- `terraform`
|
|
||||||
- `curl`, `wget` к кластерным сервисам
|
|
||||||
- `git push`, `git pull` (git операции — через ssh на ВМ)
|
|
||||||
- Любые bash-скрипты проекта
|
|
||||||
|
|
||||||
### Формат работы
|
|
||||||
|
|
||||||
1. Отредактировать файлы локально (VS Code / инструменты агента)
|
|
||||||
2. Запустить команды через SSH на ВМ
|
|
||||||
3. Ждать результата
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Документация
|
|
||||||
|
|
||||||
Всё важное фиксировать в `doc/`:
|
|
||||||
- `doc/thinking/` — лог рассуждений агента (обязательно)
|
|
||||||
- `doc/progress.md` — трекер задач
|
|
||||||
- Обновлять после каждого значимого изменения.
|
|
||||||
|
|
||||||
## Git
|
|
||||||
|
|
||||||
Коммитить и пушить после каждого завершённого этапа.
|
|
||||||
|
|
||||||
### Версионирование тегами
|
|
||||||
|
|
||||||
После каждого коммита с изменениями — поднимать версию тега:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Посмотреть текущий тег
|
|
||||||
git describe --tags --abbrev=0 2>/dev/null || echo "v0.0.0"
|
|
||||||
|
|
||||||
# Поднять patch-версию (v0.1.0 → v0.1.1, v0.1.1 → v0.1.2 и т.д.)
|
|
||||||
git tag vX.Y.Z && git push origin vX.Y.Z
|
|
||||||
```
|
|
||||||
|
|
||||||
**Правила:**
|
|
||||||
- Patch (Z) — любое изменение: правка кода, новая функция, фикс
|
|
||||||
- Minor (Y) — новая фича/компонент (новый ресурс провайдера, новый модуль консоли)
|
|
||||||
- Major (X) — breaking change
|
|
||||||
- Тег ставить ПОСЛЕ успешного коммита и пуша
|
|
||||||
- Формат: `vMAJOR.MINOR.PATCH` (например `v0.2.3`)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Как создать и задеплоить новую Fission-функцию через Terraform
|
|
||||||
|
|
||||||
### Пошаговая инструкция (ОБЯЗАТЕЛЬНО следовать)
|
|
||||||
|
|
||||||
#### Шаг 1: Создать папку с функцией
|
|
||||||
|
|
||||||
Создать папку в `examples/` по шаблону. Пример: `examples/my-test/`
|
|
||||||
|
|
||||||
Структура:
|
|
||||||
```
|
|
||||||
examples/my-test/
|
|
||||||
├── code/
|
|
||||||
│ └── main.py # Код функции
|
|
||||||
└── main.tf # Terraform манифест
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Шаг 2: Написать код функции
|
|
||||||
|
|
||||||
Файл `code/main.py` — обязательно функция `main()`:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def main():
|
|
||||||
return "hello from my-test"
|
|
||||||
```
|
|
||||||
|
|
||||||
Можно сложнее — с аргументами, JSON, вычислениями:
|
|
||||||
|
|
||||||
```python
|
|
||||||
import json
|
|
||||||
|
|
||||||
def main():
|
|
||||||
result = {"status": "ok", "data": [1, 2, 3]}
|
|
||||||
return json.dumps(result)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Шаг 3: Написать Terraform манифест
|
|
||||||
|
|
||||||
Файл `main.tf` — КОПИРОВАТЬ этот шаблон и менять только имена и URL:
|
|
||||||
|
|
||||||
```hcl
|
|
||||||
terraform {
|
|
||||||
required_providers {
|
|
||||||
fission = {
|
|
||||||
source = "nail/fission"
|
|
||||||
version = "~> 0.1.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
provider "fission" {
|
|
||||||
kubeconfig_path = "/home/naeel/.kube/config"
|
|
||||||
namespace = "default"
|
|
||||||
}
|
|
||||||
|
|
||||||
resource "fission_environment" "python" {
|
|
||||||
name = "УНИКАЛЬНОЕ-ИМЯ-env"
|
|
||||||
image = "ghcr.io/fission/python-env"
|
|
||||||
version = 3
|
|
||||||
}
|
|
||||||
|
|
||||||
resource "fission_package" "pkg" {
|
|
||||||
name = "УНИКАЛЬНОЕ-ИМЯ-pkg"
|
|
||||||
environment = fission_environment.python.name
|
|
||||||
source_dir = "${path.module}/code"
|
|
||||||
}
|
|
||||||
|
|
||||||
resource "fission_function" "fn" {
|
|
||||||
name = "УНИКАЛЬНОЕ-ИМЯ-fn"
|
|
||||||
environment = fission_environment.python.name
|
|
||||||
package_name = fission_package.pkg.name
|
|
||||||
entrypoint = "main.main"
|
|
||||||
}
|
|
||||||
|
|
||||||
resource "fission_http_trigger" "route" {
|
|
||||||
name = "УНИКАЛЬНОЕ-ИМЯ-route"
|
|
||||||
function = fission_function.fn.name
|
|
||||||
url = "/УНИКАЛЬНЫЙ-URL"
|
|
||||||
methods = ["GET"]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**ВАЖНО:** Все имена ресурсов (name) должны быть **уникальными** по всему кластеру.
|
|
||||||
Используй префикс, например `tf-mytest-env`, `tf-mytest-pkg`, `tf-mytest-fn`, `tf-mytest-route`.
|
|
||||||
|
|
||||||
#### Шаг 4: Задеплоить через SSH
|
|
||||||
|
|
||||||
```bash
|
|
||||||
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 \
|
|
||||||
'cd ~/terra/fission/examples/my-test && TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission terraform apply -auto-approve'
|
|
||||||
```
|
|
||||||
|
|
||||||
**ОБЯЗАТЕЛЬНО:**
|
|
||||||
- Переменная `TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission` — ВСЕГДА нужна (dev override провайдера)
|
|
||||||
- `terraform init` НЕ нужен (dev_overrides пропускает init)
|
|
||||||
- Выполнять ТОЛЬКО через SSH
|
|
||||||
|
|
||||||
#### Шаг 5: Проверить функцию через curl
|
|
||||||
|
|
||||||
Роутер требует JWT. Паттерн:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 '
|
|
||||||
PASSWORD=$(kubectl -n fission get secret router -o jsonpath={.data.password} | base64 -d)
|
|
||||||
TOKEN=$(curl -sk -X POST https://fission.kube5s.ru/auth/login \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d "{\"username\":\"admin\",\"password\":\"$PASSWORD\"}" \
|
|
||||||
| python3 -c "import sys,json; print(json.load(sys.stdin)[\"accesstoken\"])")
|
|
||||||
curl -sk -H "Authorization: Bearer $TOKEN" https://fission.kube5s.ru/УНИКАЛЬНЫЙ-URL
|
|
||||||
'
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Шаг 6: Удалить (если нужно)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 \
|
|
||||||
'cd ~/terra/fission/examples/my-test && TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission terraform destroy -auto-approve'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Уже задеплоенные функции (НЕ ТРОГАТЬ без явного указания)
|
|
||||||
|
|
||||||
| Папка | Endpoint | Ответ |
|
|
||||||
|-------|----------|-------|
|
|
||||||
| `examples/hello-python/` | `GET /tf-hello` | `hello from fission via terraform` |
|
|
||||||
| `examples/stress-suite/` | `GET /stress/fast` | `fast-ok` |
|
|
||||||
| `examples/stress-suite/` | `GET /stress/cpu` | `cpu-ok:NUMBER` |
|
|
||||||
| `examples/stress-suite/` | `GET /stress/json` | `{"status":"ok","service":"json"}` |
|
|
||||||
|
|
||||||
### Частые ошибки
|
|
||||||
|
|
||||||
| Ошибка | Причина | Решение |
|
|
||||||
|--------|---------|---------|
|
|
||||||
| `unauthorized: malformed token` | curl без JWT | Добавить JWT (см. шаг 5) |
|
|
||||||
| `terraform init required` | Забыт `TF_CLI_CONFIG_FILE` | Добавить `TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission` |
|
|
||||||
| `resource already exists` | Имя не уникальное | Сменить имена на уникальные с префиксом |
|
|
||||||
| `Error: connection refused` | Команда запущена локально | Выполнять ТОЛЬКО через SSH |
|
|
||||||
| `package not found` | Опечатка в `source_dir` | Проверить path.module/code и файл main.py |
|
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# Правила работы агента
|
||||||
|
|
||||||
|
## Файловая система
|
||||||
|
|
||||||
|
`~/remote_dev/` (локально) примонтирован через sshfs к `~/terra/` на ВМ — **одна ФС**.
|
||||||
|
Файлы, сохранённые локально, мгновенно видны на ВМ. SCP не нужен.
|
||||||
|
|
||||||
|
Монтирование может слетать. Признак: файлы рассинхронизированы.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Размонтировать
|
||||||
|
fusermount -u ~/remote_dev
|
||||||
|
# Если завис: sudo umount -l /home/naeel/remote_dev
|
||||||
|
|
||||||
|
# Примонтировать
|
||||||
|
sshfs naeel@5.172.178.213:/home/naeel/terra ~/remote_dev \
|
||||||
|
-o cache=no -o no_readahead -o reconnect \
|
||||||
|
-o ServerAliveInterval=15 -o ServerAliveCountMax=3 \
|
||||||
|
-o IdentityFile=~/.ssh/naeel_vm_id_ed25519
|
||||||
|
```
|
||||||
|
|
||||||
|
## SSH
|
||||||
|
|
||||||
|
Все команды — только через SSH на ВМ. Локально — только читать и редактировать файлы.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 'КОМАНДА'
|
||||||
|
```
|
||||||
|
|
||||||
|
Запрещено локально: `go`, `docker`, `kubectl`, `helm`, `terraform`, `curl/wget`, `git push/pull`, любые скрипты проекта.
|
||||||
|
|
||||||
|
## Документация
|
||||||
|
|
||||||
|
- `doc/thinking/` — лог рассуждений агента (обязательно)
|
||||||
|
- `doc/progress.md` — трекер задач
|
||||||
|
- Старые файлы `doc/` не перезаписывать — новое в новых файлах с датой
|
||||||
|
|
||||||
|
## Git
|
||||||
|
|
||||||
|
Коммитить и пушить через SSH после каждого завершённого этапа.
|
||||||
|
|
||||||
|
Версионирование тегами: `vMAJOR.MINOR.PATCH`
|
||||||
|
- Patch — любое изменение кода
|
||||||
|
- Minor — новая фича / компонент
|
||||||
|
- Major — breaking change
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag vX.Y.Z && git push origin vX.Y.Z
|
||||||
|
```
|
||||||
|
|
||||||
|
## Поведение агента
|
||||||
|
|
||||||
|
- Не трогать рабочий код без явного указания
|
||||||
|
- Не делать ничего сверх того, о чём явно попросили
|
||||||
|
- Деструктивные операции (`kubectl delete`, `rm -rf`, `terraform destroy` и др.) — только после явного подтверждения с указанием конкретных объектов
|
||||||
|
- Отвечать кратко, без вступлений, извинений, благодарностей и прочей воды
|
||||||
@@ -14,3 +14,4 @@ examples/*/dist/
|
|||||||
# Provider binaries
|
# Provider binaries
|
||||||
terraform-provider-fission
|
terraform-provider-fission
|
||||||
terraform-provider-fission_*
|
terraform-provider-fission_*
|
||||||
|
console/fission-console
|
||||||
|
|||||||
+219
-18
@@ -40,6 +40,12 @@ var (
|
|||||||
|
|
||||||
const defaultSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
|
const defaultSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
|
||||||
|
|
||||||
|
var deckAPIs = map[string]string{
|
||||||
|
"prod": "https://deck-api.ngcloud.ru/api/v1",
|
||||||
|
"dev": "https://deck-api-dev.ngcloud.ru/api/v1",
|
||||||
|
"test": "https://deck-api-test.ngcloud.ru/api/v1",
|
||||||
|
}
|
||||||
|
|
||||||
type server struct {
|
type server struct {
|
||||||
dyn dynamic.Interface
|
dyn dynamic.Interface
|
||||||
ns string
|
ns string
|
||||||
@@ -54,10 +60,12 @@ type server struct {
|
|||||||
tokenMu sync.Mutex
|
tokenMu sync.Mutex
|
||||||
cachedJWT string
|
cachedJWT string
|
||||||
tokenExpAt time.Time
|
tokenExpAt time.Time
|
||||||
|
tokenCache sync.Map
|
||||||
}
|
}
|
||||||
|
|
||||||
type createFunctionRequest struct {
|
type createFunctionRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
Language string `json:"language"`
|
||||||
Environment string `json:"environment"`
|
Environment string `json:"environment"`
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
Entrypoint string `json:"entrypoint"`
|
Entrypoint string `json:"entrypoint"`
|
||||||
@@ -65,6 +73,20 @@ type createFunctionRequest struct {
|
|||||||
Methods []string `json:"methods"`
|
Methods []string `json:"methods"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type langEnvDef struct {
|
||||||
|
Image string
|
||||||
|
BuilderImage string
|
||||||
|
}
|
||||||
|
|
||||||
|
var langEnvMap = map[string]langEnvDef{
|
||||||
|
"python": {Image: "ghcr.io/fission/python-env"},
|
||||||
|
"nodejs": {Image: "ghcr.io/fission/node-env"},
|
||||||
|
"go": {Image: "ghcr.io/fission/go-env", BuilderImage: "ghcr.io/fission/go-builder"},
|
||||||
|
"php": {Image: "ghcr.io/fission/php-env"},
|
||||||
|
"ruby": {Image: "ghcr.io/fission/ruby-env"},
|
||||||
|
"perl": {Image: "ghcr.io/fission/perl-env"},
|
||||||
|
}
|
||||||
|
|
||||||
type updateCodeRequest struct {
|
type updateCodeRequest struct {
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
}
|
}
|
||||||
@@ -123,12 +145,32 @@ func main() {
|
|||||||
mux.HandleFunc("/api/httptriggers", s.handleList(httpTrigGVR))
|
mux.HandleFunc("/api/httptriggers", s.handleList(httpTrigGVR))
|
||||||
mux.HandleFunc("/api/timetriggers", s.handleList(timeTrigGVR))
|
mux.HandleFunc("/api/timetriggers", s.handleList(timeTrigGVR))
|
||||||
|
|
||||||
mux.HandleFunc("/console/api/environments", s.handleList(environmentGVR))
|
auth := func(h http.HandlerFunc) http.HandlerFunc {
|
||||||
mux.HandleFunc("/console/api/packages", s.handleList(packageGVR))
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
mux.HandleFunc("/console/api/functions", s.handleFunctionsRoot)
|
token := strings.TrimSpace(r.Header.Get("X-Auth-Token"))
|
||||||
mux.HandleFunc("/console/api/functions/", s.handleFunctionsAction)
|
env := strings.TrimSpace(strings.ToLower(r.Header.Get("X-Auth-Env")))
|
||||||
mux.HandleFunc("/console/api/httptriggers", s.handleList(httpTrigGVR))
|
if _, ok := deckAPIs[env]; !ok {
|
||||||
mux.HandleFunc("/console/api/timetriggers", s.handleList(timeTrigGVR))
|
env = "test"
|
||||||
|
}
|
||||||
|
if token == "" {
|
||||||
|
writeJSONError(w, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := s.validateDeckToken(token, env); err != nil {
|
||||||
|
writeJSONError(w, http.StatusUnauthorized, "unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mux.HandleFunc("/console/api/auth", s.handleAuth)
|
||||||
|
mux.HandleFunc("/console/api/environments", auth(s.handleList(environmentGVR)))
|
||||||
|
mux.HandleFunc("/console/api/packages", auth(s.handleList(packageGVR)))
|
||||||
|
mux.HandleFunc("/console/api/functions", auth(s.handleFunctionsRoot))
|
||||||
|
mux.HandleFunc("/console/api/functions/", auth(s.handleFunctionsAction))
|
||||||
|
mux.HandleFunc("/console/api/httptriggers", auth(s.handleList(httpTrigGVR)))
|
||||||
|
mux.HandleFunc("/console/api/timetriggers", auth(s.handleList(timeTrigGVR)))
|
||||||
|
|
||||||
httpServer := &http.Server{
|
httpServer := &http.Server{
|
||||||
Addr: ":" + port,
|
Addr: ":" + port,
|
||||||
@@ -202,13 +244,38 @@ func (s *server) handleCreateFunction(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
req.Name = strings.TrimSpace(req.Name)
|
req.Name = strings.TrimSpace(req.Name)
|
||||||
|
req.Language = strings.TrimSpace(req.Language)
|
||||||
req.Environment = strings.TrimSpace(req.Environment)
|
req.Environment = strings.TrimSpace(req.Environment)
|
||||||
req.Code = strings.TrimSpace(req.Code)
|
req.Code = strings.TrimSpace(req.Code)
|
||||||
req.Entrypoint = strings.TrimSpace(req.Entrypoint)
|
req.Entrypoint = strings.TrimSpace(req.Entrypoint)
|
||||||
req.Route = strings.TrimSpace(req.Route)
|
req.Route = strings.TrimSpace(req.Route)
|
||||||
|
|
||||||
|
// Resolve language → environment (auto-create if needed)
|
||||||
|
if req.Language != "" {
|
||||||
|
langDef, ok := langEnvMap[req.Language]
|
||||||
|
if !ok {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("unsupported language: %q", req.Language))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
envName := "console-" + req.Language + "-env"
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_, err := s.dyn.Resource(environmentGVR).Namespace(s.ns).Get(ctx, envName, metav1.GetOptions{})
|
||||||
|
if apierrors.IsNotFound(err) {
|
||||||
|
env := s.buildLangEnvironment(envName, langDef)
|
||||||
|
if _, err := s.dyn.Resource(environmentGVR).Namespace(s.ns).Create(ctx, env, metav1.CreateOptions{}); err != nil {
|
||||||
|
writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("create environment %q: %v", envName, err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else if err != nil {
|
||||||
|
writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("check environment: %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Environment = envName
|
||||||
|
}
|
||||||
|
|
||||||
if req.Name == "" || req.Environment == "" || req.Code == "" {
|
if req.Name == "" || req.Environment == "" || req.Code == "" {
|
||||||
writeJSONError(w, http.StatusBadRequest, "name, environment and code are required")
|
writeJSONError(w, http.StatusBadRequest, "name, environment/language and code are required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if req.Entrypoint == "" {
|
if req.Entrypoint == "" {
|
||||||
@@ -237,15 +304,30 @@ func (s *server) handleCreateFunction(w http.ResponseWriter, r *http.Request) {
|
|||||||
methodValues = append(methodValues, method)
|
methodValues = append(methodValues, method)
|
||||||
}
|
}
|
||||||
|
|
||||||
literal := base64.StdEncoding.EncodeToString([]byte(req.Code))
|
// Build the package spec: Go uses source archive (builder), others use literal deployment
|
||||||
pkg := &unstructured.Unstructured{Object: map[string]any{
|
var pkgSpec map[string]any
|
||||||
"apiVersion": "fission.io/v1",
|
if req.Language == "go" {
|
||||||
"kind": "Package",
|
srcZip, err := s.buildGoSourceZip(req.Code)
|
||||||
"metadata": map[string]any{
|
if err != nil {
|
||||||
"name": pkgName,
|
writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("build go source archive: %v", err))
|
||||||
"namespace": s.ns,
|
return
|
||||||
},
|
}
|
||||||
"spec": map[string]any{
|
literal := base64.StdEncoding.EncodeToString(srcZip)
|
||||||
|
pkgSpec = map[string]any{
|
||||||
|
"source": map[string]any{
|
||||||
|
"type": "literal",
|
||||||
|
"literal": literal,
|
||||||
|
},
|
||||||
|
"deployment": map[string]any{},
|
||||||
|
"environment": map[string]any{
|
||||||
|
"name": req.Environment,
|
||||||
|
"namespace": s.ns,
|
||||||
|
},
|
||||||
|
"buildcommand": "build",
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
literal := base64.StdEncoding.EncodeToString([]byte(req.Code))
|
||||||
|
pkgSpec = map[string]any{
|
||||||
"deployment": map[string]any{
|
"deployment": map[string]any{
|
||||||
"type": "literal",
|
"type": "literal",
|
||||||
"literal": literal,
|
"literal": literal,
|
||||||
@@ -255,7 +337,17 @@ func (s *server) handleCreateFunction(w http.ResponseWriter, r *http.Request) {
|
|||||||
"namespace": s.ns,
|
"namespace": s.ns,
|
||||||
},
|
},
|
||||||
"source": map[string]any{},
|
"source": map[string]any{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pkg := &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Package",
|
||||||
|
"metadata": map[string]any{
|
||||||
|
"name": pkgName,
|
||||||
|
"namespace": s.ns,
|
||||||
},
|
},
|
||||||
|
"spec": pkgSpec,
|
||||||
}}
|
}}
|
||||||
|
|
||||||
if _, err := s.dyn.Resource(packageGVR).Namespace(s.ns).Create(ctx, pkg, metav1.CreateOptions{}); err != nil {
|
if _, err := s.dyn.Resource(packageGVR).Namespace(s.ns).Create(ctx, pkg, metav1.CreateOptions{}); err != nil {
|
||||||
@@ -325,6 +417,58 @@ func (s *server) handleCreateFunction(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *server) buildLangEnvironment(name string, def langEnvDef) *unstructured.Unstructured {
|
||||||
|
spec := map[string]any{
|
||||||
|
"version": int64(3),
|
||||||
|
"runtime": map[string]any{
|
||||||
|
"image": def.Image,
|
||||||
|
},
|
||||||
|
"poolsize": int64(1),
|
||||||
|
}
|
||||||
|
if def.BuilderImage != "" {
|
||||||
|
spec["builder"] = map[string]any{
|
||||||
|
"image": def.BuilderImage,
|
||||||
|
"command": "build",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Environment",
|
||||||
|
"metadata": map[string]any{
|
||||||
|
"name": name,
|
||||||
|
"namespace": s.ns,
|
||||||
|
},
|
||||||
|
"spec": spec,
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *server) buildGoSourceZip(code string) ([]byte, error) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
zw := zip.NewWriter(&buf)
|
||||||
|
|
||||||
|
fw, err := zw.Create("handler.go")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, err := fw.Write([]byte(code)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
goMod := "module github.com/user/fn\n\ngo 1.23\n"
|
||||||
|
fw2, err := zw.Create("go.mod")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, err := fw2.Write([]byte(goMod)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return buf.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *server) handleGetFunction(w http.ResponseWriter, r *http.Request, name string) {
|
func (s *server) handleGetFunction(w http.ResponseWriter, r *http.Request, name string) {
|
||||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -597,6 +741,63 @@ func (s *server) getRouterToken() string {
|
|||||||
return s.cachedJWT
|
return s.cachedJWT
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *server) validateDeckToken(token, env string) error {
|
||||||
|
cacheKey := env + ":" + token
|
||||||
|
if v, ok := s.tokenCache.Load(cacheKey); ok {
|
||||||
|
if time.Now().Before(v.(time.Time)) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
s.tokenCache.Delete(cacheKey)
|
||||||
|
}
|
||||||
|
apiBase, ok := deckAPIs[env]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("unknown env: %s", env)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/index.cfm/instances", nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
resp, err := s.http.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
_, _ = io.ReadAll(resp.Body)
|
||||||
|
if resp.StatusCode == http.StatusUnauthorized {
|
||||||
|
return fmt.Errorf("invalid token")
|
||||||
|
}
|
||||||
|
s.tokenCache.Store(cacheKey, time.Now().Add(5*time.Minute))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
Env string `json:"env"`
|
||||||
|
}
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || strings.TrimSpace(body.Token) == "" {
|
||||||
|
writeJSONError(w, http.StatusBadRequest, "token required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
env := strings.TrimSpace(strings.ToLower(body.Env))
|
||||||
|
if _, ok := deckAPIs[env]; !ok {
|
||||||
|
env = "test"
|
||||||
|
}
|
||||||
|
if err := s.validateDeckToken(body.Token, env); err != nil {
|
||||||
|
writeJSONError(w, http.StatusUnauthorized, "invalid token")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "env": env})
|
||||||
|
}
|
||||||
|
|
||||||
func (s *server) handleDeleteFunction(w http.ResponseWriter, r *http.Request, name string) {
|
func (s *server) handleDeleteFunction(w http.ResponseWriter, r *http.Request, name string) {
|
||||||
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -700,7 +901,7 @@ func withCORS(next http.Handler) http.Handler {
|
|||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
|
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
|
||||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Auth-Token, X-Auth-Env")
|
||||||
if r.Method == http.MethodOptions {
|
if r.Method == http.MethodOptions {
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
@@ -851,7 +1052,7 @@ func decodeZipSource(zipBytes []byte) (string, error) {
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
preferred := []string{"main.py", "main.js", "main.go"}
|
preferred := []string{"main.py", "main.js", "main.go", "handler.go", "handler.js", "handler.py"}
|
||||||
for _, name := range preferred {
|
for _, name := range preferred {
|
||||||
for _, file := range reader.File {
|
for _, file := range reader.File {
|
||||||
if strings.EqualFold(file.Name, name) {
|
if strings.EqualFold(file.Name, name) {
|
||||||
|
|||||||
+191
-54
@@ -4,7 +4,7 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>NUBES Fission Console</title>
|
<title>NUBES Fission Console</title>
|
||||||
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA4ZJREFUeJztm8+Lm0UYxz/fySZUoWIrVtbmXfyBP05Fa3e3rogsglJRK0p7E2svnrz6B3gQ8eRJFooXET14KKJ4FUQo3UQQ9CRC6W4WQW0VXZduTd7HQ9c22bzbTCY/ZpO8n0syb56Z+c437zPvhMzIzJhkXGwBsckNiC0gNrkBsQXEZsonSJLj4GNPgb2ACo9j9gDOvrSV6qkB6+sJ6WSJ5MIxUo4h5sDuI9U7tlZ57/+YTAN0zyOPUi+9jOxJxMOUj9wJOBBg117QvqGMwhNpcQ/J+rOkPIc0j+xeytyGsaWXa2+kvc312gxQMleHYgFtrQ9GYJmgmSfup3z15xuDNW/dGXOAjd680NgshlYdvcH2mfEwQIU0tOp4GNADuQGxBcRmPAyQgh/W42FAD+QGxBYQm/EwIF8HhJMbEFtAX3DreQqEkhsQW0BsxsMAlz8Gg8kNiC0gNuNhgJvK54BQcgNiC+gLhUlPgcuTbkAP5AbEFhCbcAOM4LyLitIW3eEGyP7qWUwMHFdaixNO1v4Av5pG8H/yfWfvesk7tq5GczHDAHnmtu727nTQbJYe8o51+qOl2BYgNv1a0iHvTgeNGq94x6buYnOx3YCU3/1asn06ePQZ744HiXTCO3a6/m1zsd0Ax/f+HTc+kU76598AUDL/LpjfjjWxYdXqRvOljDvAfezfO3dQvvCDtLjHu04f0czsaSx9y7uC8eP2S20GWO38Z+A7DwDwIOX135TMvylpKI9VJQv7lcx+hfEhurELsCPOfdDWVtZ5ASWzZ4GXArQ1QJfA/kTW6BhtLgX+7qL9IqTTmKa7GjgAumKry7dsv5q9Vfbfq29QLL1I9wulAtgB4ADmoy9kY4fodugAODuT2dpOJ0aUzH8E6asBXe0+zP5h7bvbzay+/aOdv+Ha8mnE5YEKGxqF17MGDzcxwMzqTBUWgc65vKuxT7cm9kx2TIHrATOzxzHOEpZ5sanYamXuZgEdJzlbqXyOmzrO6N0J56hVj3YK8prl7eK5L6g3DmFc6l3XEDCWbLWyYGYdf9h1TIGWYMmRHDlDaqcY0qKnO/Qr4oStLH/jXSPk4KSShf2ovoTZ80Db4iICv2D2ttWqS91WDDKgpYHy4adR8TWww8BdmN2KrOg5Zwoo+PV0/ThICmyArWHua9D7Vjv/U5j6Phgw6uzCPB4uuQGxBcRm4g34D1IN9ODV8oQpAAAAAElFTkSuQmCC">
|
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA4ZJREFUeJztm8+Lm0UYxz/fySZUoWIrVtbmXfyBP05Fa3e3rogsglJRK0p7E2svnrz6B3gQ8eRJFooXET14KKJ4FUQo3UQQ9CRC6W4WQW0VXZduTd7HQ9c22bzbTCY/ZpO8n0syb56Z+c437zPvhMzIzJhkXGwBsckNiC0gNrkBsQXEZsonSJLj4GNPgb2ACo9j9gDOvrSV6qkB6+sJ6WSJ5MIxUo4h5sDuI9U7tlZ57/+YTAN0zyOPUi+9jOxJxMOUj9wJOBBg117QvqGMwhNpcQ/J+rOkPIc0j+xeytyGsaWXa2+kvc312gxQMleHYgFtrQ9GYJmgmSfup3z15xuDNW/dGXOAjd680NgshlYdvcH2mfEwQIU0tOp4GNADuQGxBcRmPAyQgh/W42FAD+QGxBYQm/EwIF8HhJMbEFtAX3DreQqEkhsQW0BsxsMAlz8Gg8kNiC0gNuNhgJvK54BQcgNiC+gLhUlPgcuTbkAP5AbEFhCbcAOM4LyLitIW3eEGyP7qWUwMHFdaixNO1v4Av5pG8H/yfWfvesk7tq5GczHDAHnmtu727nTQbJYe8o51+qOl2BYgNv1a0iHvTgeNGq94x6buYnOx3YCU3/1asn06ePQZ744HiXTCO3a6/m1zsd0Ax/f+HTc+kU76598AUDL/LpjfjjWxYdXqRvOljDvAfezfO3dQvvCDtLjHu04f0czsaSx9y7uC8eP2S20GWO38Z+A7DwDwIOX135TMvylpKI9VJQv7lcx+hfEhurELsCPOfdDWVtZ5ASWzZ4GXArQ1QJfA/kTW6BhtLgX+7qL9IqTTmKa7GjgAumKry7dsv5q9Vfbfq29QLL1I9wulAtgB4ADmoy9kY4fodugAODuT2dpOJ0aUzH8E6asBXe0+zP5h7bvbzay+/aOdv+Ha8mnE5YEKGxqF17MGDzcxwMzqTBUWgc65vKuxT7cm9kx2TIHrATOzxzHOEpZ5sanYamXuZgEdJzlbqXyOmzrO6N0J56hVj3YK8prl7eK5L6g3DmFc6l3XEDCWbLWyYGYdf9h1TIGWYMmRHDlDaqcY0qKnO/Qr4oStLH/jXSPk4KSShf2ovoTZ80Db4iICv2D2ttWqS91WDDKgpYHy4adR8TWww8BdmN2KrOg5Zwoo+PV0">
|
||||||
<script>
|
<script>
|
||||||
if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
|
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);
|
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);
|
||||||
@@ -287,6 +287,31 @@
|
|||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<div id="login-overlay" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.85); z-index:999; align-items:center; justify-content:center; padding:16px;">
|
||||||
|
<div class="panel" style="width:min(440px,100%);">
|
||||||
|
<div class="brand" style="margin-bottom:24px;">
|
||||||
|
<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="flex-direction:column; gap:6px; margin-bottom:12px;">
|
||||||
|
<label style="font-size:12px; color:#999;">Стенд</label>
|
||||||
|
<select id="l-env" style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px;">
|
||||||
|
<option value="dev">Dev</option>
|
||||||
|
<option value="test" selected>Test</option>
|
||||||
|
<option value="prod">Prod</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="row" style="flex-direction:column; gap:6px; margin-bottom:12px;">
|
||||||
|
<label style="font-size:12px; color:#999;">Токен</label>
|
||||||
|
<textarea id="l-token" rows="5" style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px; font-family:monospace; font-size:12px; resize:vertical; width:100%; box-sizing:border-box;" placeholder="Введите токен..."></textarea>
|
||||||
|
</div>
|
||||||
|
<div id="l-error" style="display:none; color:#ff6b6b; font-size:13px; margin-bottom:10px;"></div>
|
||||||
|
<button id="l-btn" class="btn" style="width:100%;" onclick="doLogin()">Войти</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="navbar">
|
<div class="navbar">
|
||||||
<div class="brand">
|
<div class="brand">
|
||||||
<div class="brand-mark">N</div>
|
<div class="brand-mark">N</div>
|
||||||
@@ -297,27 +322,28 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="row" style="margin:0;">
|
<div class="row" style="margin:0;">
|
||||||
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
|
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
|
||||||
<button class="btn" onclick="openCreate()">+ Create Function</button>
|
<button class="btn" onclick="openCreate()">+ Создать функцию</button>
|
||||||
|
<button class="btn ghost" onclick="doLogout()" style="margin-left:8px;">Выход</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="wrap">
|
<div class="wrap">
|
||||||
<div class="grid">
|
<div class="grid">
|
||||||
<div class="card"><div class="k">Environments</div><div id="env-count" class="v">-</div></div>
|
<div class="card"><div class="k">Окружения</div><div id="env-count" class="v">-</div></div>
|
||||||
<div class="card"><div class="k">Packages</div><div id="pkg-count" class="v">-</div></div>
|
<div class="card"><div class="k">Пакеты</div><div id="pkg-count" class="v">-</div></div>
|
||||||
<div class="card"><div class="k">Functions</div><div id="fn-count" class="v">-</div></div>
|
<div class="card"><div class="k">Функции</div><div id="fn-count" class="v">-</div></div>
|
||||||
<div class="card"><div class="k">HTTP Triggers</div><div id="http-count" class="v">-</div></div>
|
<div class="card"><div class="k">HTTP-триггеры</div><div id="http-count" class="v">-</div></div>
|
||||||
<div class="card"><div class="k">Time Triggers</div><div id="time-count" class="v">-</div></div>
|
<div class="card"><div class="k">Тайм-триггеры</div><div id="time-count" class="v">-</div></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="box">
|
<div class="box">
|
||||||
<div class="toolbar">
|
<div class="toolbar">
|
||||||
<div style="font-weight:600;">Functions</div>
|
<div style="font-weight:600;">Функции</div>
|
||||||
<div class="hint">Actions: view, edit code, invoke, delete</div>
|
<div class="hint">Actions: view, edit code, invoke, delete</div>
|
||||||
</div>
|
</div>
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>Name</th><th>Environment</th><th>Package</th><th>Route</th><th>Methods</th><th class="nowrap">Actions</th></tr>
|
<tr><th>Имя</th><th>Окружение</th><th>Пакет</th><th>Маршрут</th><th>Методы</th><th class="nowrap">Действия</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="fn-rows"></tbody>
|
<tbody id="fn-rows"></tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -328,15 +354,21 @@
|
|||||||
|
|
||||||
<div id="create-modal" class="modal">
|
<div id="create-modal" class="modal">
|
||||||
<div class="panel">
|
<div class="panel">
|
||||||
<h3>Create Function</h3>
|
<h3>Создать функцию</h3>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Name</label>
|
<label>Name</label>
|
||||||
<input id="c-name" placeholder="demo-fn">
|
<input id="c-name" placeholder="demo-fn">
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Environment</label>
|
<label>Language</label>
|
||||||
<select id="c-env"></select>
|
<select id="c-lang" onchange="onLangChange()">
|
||||||
|
<option value="python">Python</option>
|
||||||
|
<option value="nodejs">Node.js</option>
|
||||||
|
<option value="php">PHP</option>
|
||||||
|
<option value="ruby">Ruby</option>
|
||||||
|
<option value="perl">Perl</option>
|
||||||
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Entrypoint</label>
|
<label>Entrypoint</label>
|
||||||
@@ -349,26 +381,27 @@
|
|||||||
<input id="c-route" placeholder="/demo-fn">
|
<input id="c-route" placeholder="/demo-fn">
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Methods (comma separated)</label>
|
<label>Методы (через запятую)</label>
|
||||||
<input id="c-methods" value="GET">
|
<input id="c-methods" value="GET">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label>Code</label>
|
<label>Код</label>
|
||||||
<textarea id="c-code">def main(ctx):
|
<textarea id="c-code">def main(ctx):
|
||||||
return {"ok": True, "msg": "hello from fission console"}
|
return {"ok": True, "msg": "hello from fission console"}
|
||||||
</textarea>
|
</textarea>
|
||||||
</div>
|
</div>
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn ghost" onclick="closeCreate()">Cancel</button>
|
<button class="btn ghost" onclick="closeCreate()">Отмена</button>
|
||||||
<button id="c-submit" class="btn" onclick="submitCreate()">Create</button>
|
<button id="c-submit" class="btn" onclick="submitCreate()">Создать</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="edit-modal" class="modal">
|
<div id="edit-modal" class="modal">
|
||||||
<div class="panel">
|
<div class="panel">
|
||||||
<h3 id="e-title">Edit Code</h3>
|
<h3 id="e-title">Редактирование кода</h3>
|
||||||
|
<div id="e-tf-warn" style="display:none;background:#553300;color:#ffa;padding:8px 12px;border-radius:6px;margin-bottom:10px;font-size:13px;">\u26a0\ufe0f Эта функция управляется Terraform. Изменения могут быть перезаписаны при следующем <code>terraform apply</code>.</div>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>Name</label>
|
<label>Name</label>
|
||||||
@@ -384,26 +417,26 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label>Code</label>
|
<label>Код</label>
|
||||||
<textarea id="e-code"></textarea>
|
<textarea id="e-code"></textarea>
|
||||||
</div>
|
</div>
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn ghost" onclick="closeEdit()">Cancel</button>
|
<button class="btn ghost" onclick="closeEdit()">Отмена</button>
|
||||||
<button id="e-submit" class="btn" onclick="submitEdit()">Save</button>
|
<button id="e-submit" class="btn" onclick="submitEdit()">Сохранить</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="invoke-modal" class="modal">
|
<div id="invoke-modal" class="modal">
|
||||||
<div class="panel">
|
<div class="panel">
|
||||||
<h3 id="i-title">Invoke</h3>
|
<h3 id="i-title">Вызов</h3>
|
||||||
<div>
|
<div>
|
||||||
<label>JSON payload</label>
|
<label>JSON тело запроса</label>
|
||||||
<textarea id="i-body">{"name":"world"}</textarea>
|
<textarea id="i-body">{"name":"world"}</textarea>
|
||||||
</div>
|
</div>
|
||||||
<div class="actions">
|
<div class="actions">
|
||||||
<button class="btn ghost" onclick="closeInvoke()">Cancel</button>
|
<button class="btn ghost" onclick="closeInvoke()">Отмена</button>
|
||||||
<button id="i-submit" class="btn" onclick="submitInvoke()">Invoke</button>
|
<button id="i-submit" class="btn" onclick="submitInvoke()">Вызвать</button>
|
||||||
</div>
|
</div>
|
||||||
<div style="margin-top:10px;">
|
<div style="margin-top:10px;">
|
||||||
<label>Response</label>
|
<label>Response</label>
|
||||||
@@ -423,8 +456,16 @@
|
|||||||
currentInvoke: null
|
currentInvoke: null
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function authHeaders() {
|
||||||
|
return {
|
||||||
|
'X-Auth-Token': localStorage.getItem('auth_token') || '',
|
||||||
|
'X-Auth-Env': localStorage.getItem('auth_env') || 'test'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async function getJSON(url) {
|
async function getJSON(url) {
|
||||||
const r = await fetch(url);
|
const r = await fetch(url, {headers: authHeaders()});
|
||||||
|
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||||
if (!r.ok) {
|
if (!r.ok) {
|
||||||
let msg = '';
|
let msg = '';
|
||||||
try {
|
try {
|
||||||
@@ -441,9 +482,10 @@
|
|||||||
async function requestJSON(url, method, body) {
|
async function requestJSON(url, method, body) {
|
||||||
const r = await fetch(url, {
|
const r = await fetch(url, {
|
||||||
method: method,
|
method: method,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: Object.assign({'Content-Type': 'application/json'}, authHeaders()),
|
||||||
body: body ? JSON.stringify(body) : undefined
|
body: body ? JSON.stringify(body) : undefined
|
||||||
});
|
});
|
||||||
|
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||||
let data = {};
|
let data = {};
|
||||||
try { data = await r.json(); } catch (_) {}
|
try { data = await r.json(); } catch (_) {}
|
||||||
if (!r.ok) {
|
if (!r.ok) {
|
||||||
@@ -490,12 +532,45 @@
|
|||||||
.replaceAll("'", ''');
|
.replaceAll("'", ''');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const LANG_TEMPLATES = {
|
||||||
|
python: {
|
||||||
|
entrypoint: 'main.main',
|
||||||
|
code: 'def main():\n return "hello from fission"'
|
||||||
|
},
|
||||||
|
nodejs: {
|
||||||
|
entrypoint: 'handler',
|
||||||
|
code: 'module.exports = async function(context) {\n return {\n status: 200,\n body: "hello from fission"\n };\n}'
|
||||||
|
},
|
||||||
|
go: {
|
||||||
|
entrypoint: 'Handler',
|
||||||
|
code: 'package main\n\nimport (\n "fmt"\n "net/http"\n)\n\nfunc Handler(w http.ResponseWriter, r *http.Request) {\n fmt.Fprintf(w, "hello from fission")\n}'
|
||||||
|
},
|
||||||
|
php: {
|
||||||
|
entrypoint: 'main.php::handler',
|
||||||
|
code: '<?php\nfunction handler($context)\n{\n $response = $context["response"];\n $response->getBody()->write("hello from fission");\n}'
|
||||||
|
},
|
||||||
|
ruby: {
|
||||||
|
entrypoint: 'handler',
|
||||||
|
code: '# frozen_string_literal: true\n\ndef handler\n "hello from fission"\nend'
|
||||||
|
},
|
||||||
|
perl: {
|
||||||
|
entrypoint: 'handler',
|
||||||
|
code: 'sub {\n return "hello from fission";\n}'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
function onLangChange() {
|
||||||
|
var lang = document.getElementById('c-lang').value;
|
||||||
|
var t = LANG_TEMPLATES[lang];
|
||||||
|
if (t) {
|
||||||
|
document.getElementById('c-entry').value = t.entrypoint;
|
||||||
|
document.getElementById('c-code').value = t.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function openCreate() {
|
function openCreate() {
|
||||||
const envSel = document.getElementById('c-env');
|
document.getElementById('c-lang').value = 'python';
|
||||||
envSel.innerHTML = (S.envs || []).map(function (e) {
|
onLangChange();
|
||||||
const n = (e.metadata && e.metadata.name) || '';
|
|
||||||
return '<option value="' + h(n) + '">' + h(n) + '</option>';
|
|
||||||
}).join('');
|
|
||||||
document.getElementById('create-modal').classList.add('open');
|
document.getElementById('create-modal').classList.add('open');
|
||||||
document.getElementById('c-name').focus();
|
document.getElementById('c-name').focus();
|
||||||
}
|
}
|
||||||
@@ -510,12 +585,12 @@
|
|||||||
try {
|
try {
|
||||||
const name = document.getElementById('c-name').value.trim();
|
const name = document.getElementById('c-name').value.trim();
|
||||||
if (!name) throw new Error('name is required');
|
if (!name) throw new Error('name is required');
|
||||||
const env = document.getElementById('c-env').value.trim();
|
const lang = document.getElementById('c-lang').value.trim();
|
||||||
if (!env) throw new Error('environment is required');
|
if (!lang) throw new Error('language is required');
|
||||||
|
|
||||||
await requestJSON(API_BASE + '/functions', 'POST', {
|
await requestJSON(API_BASE + '/functions', 'POST', {
|
||||||
name: name,
|
name: name,
|
||||||
environment: env,
|
language: lang,
|
||||||
entrypoint: document.getElementById('c-entry').value.trim(),
|
entrypoint: document.getElementById('c-entry').value.trim(),
|
||||||
route: document.getElementById('c-route').value.trim(),
|
route: document.getElementById('c-route').value.trim(),
|
||||||
methods: parseMethods(document.getElementById('c-methods').value),
|
methods: parseMethods(document.getElementById('c-methods').value),
|
||||||
@@ -523,10 +598,10 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
closeCreate();
|
closeCreate();
|
||||||
showStatus('Function created: ' + name, 'ok');
|
showStatus('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0430: ' + name, 'ok');
|
||||||
await reloadAll();
|
await reloadAll();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showStatus('Create failed: ' + e.message, 'err');
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f: ' + e.message, 'err');
|
||||||
} finally {
|
} finally {
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
}
|
}
|
||||||
@@ -536,14 +611,19 @@
|
|||||||
try {
|
try {
|
||||||
const fn = await getJSON(API_BASE + '/functions/' + encodeURIComponent(name));
|
const fn = await getJSON(API_BASE + '/functions/' + encodeURIComponent(name));
|
||||||
S.currentEdit = fn;
|
S.currentEdit = fn;
|
||||||
document.getElementById('e-title').textContent = 'Edit Code: ' + name;
|
document.getElementById('e-title').textContent = '\u0420\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435: ' + name;
|
||||||
document.getElementById('e-name').value = name;
|
document.getElementById('e-name').value = name;
|
||||||
document.getElementById('e-env').value = fn.environment || '';
|
document.getElementById('e-env').value = fn.environment || '';
|
||||||
document.getElementById('e-entry').value = fn.entrypoint || '';
|
document.getElementById('e-entry').value = fn.entrypoint || '';
|
||||||
document.getElementById('e-code').value = fn.code || '';
|
document.getElementById('e-code').value = fn.code || '';
|
||||||
|
var warnEl = document.getElementById('e-tf-warn');
|
||||||
|
if (warnEl) {
|
||||||
|
var isTf = /^tf-/.test(name) || /go[-_]env/.test(fn.environment || '');
|
||||||
|
warnEl.style.display = isTf ? 'block' : 'none';
|
||||||
|
}
|
||||||
document.getElementById('edit-modal').classList.add('open');
|
document.getElementById('edit-modal').classList.add('open');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showStatus('Load function failed: ' + e.message, 'err');
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438 \u0444\u0443\u043d\u043a\u0446\u0438\u0438: ' + e.message, 'err');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -562,9 +642,9 @@
|
|||||||
code: document.getElementById('e-code').value
|
code: document.getElementById('e-code').value
|
||||||
});
|
});
|
||||||
closeEdit();
|
closeEdit();
|
||||||
showStatus('Code updated: ' + name, 'ok');
|
showStatus('\u041a\u043e\u0434 \u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d: ' + name, 'ok');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showStatus('Update failed: ' + e.message, 'err');
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||||
} finally {
|
} finally {
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
}
|
}
|
||||||
@@ -572,7 +652,7 @@
|
|||||||
|
|
||||||
function openInvoke(name) {
|
function openInvoke(name) {
|
||||||
S.currentInvoke = name;
|
S.currentInvoke = name;
|
||||||
document.getElementById('i-title').textContent = 'Invoke: ' + name;
|
document.getElementById('i-title').textContent = '\u0412\u044b\u0437\u043e\u0432: ' + name;
|
||||||
document.getElementById('i-resp').value = '';
|
document.getElementById('i-resp').value = '';
|
||||||
document.getElementById('invoke-modal').classList.add('open');
|
document.getElementById('invoke-modal').classList.add('open');
|
||||||
}
|
}
|
||||||
@@ -593,20 +673,21 @@
|
|||||||
const result = await requestJSON(API_BASE + '/functions/' + encodeURIComponent(S.currentInvoke) + '/invoke', 'POST', parsed);
|
const result = await requestJSON(API_BASE + '/functions/' + encodeURIComponent(S.currentInvoke) + '/invoke', 'POST', parsed);
|
||||||
document.getElementById('i-resp').value = JSON.stringify(result, null, 2);
|
document.getElementById('i-resp').value = JSON.stringify(result, null, 2);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('i-resp').value = 'Invoke failed: ' + e.message;
|
document.getElementById('i-resp').value = '\u041e\u0448\u0438\u0431\u043a\u0430 \u0432\u044b\u0437\u043e\u0432\u0430: ' + e.message;
|
||||||
} finally {
|
} finally {
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function removeFn(name) {
|
async function removeFn(name) {
|
||||||
if (!confirm('Delete function ' + name + '?')) return;
|
var tfWarn = (/^tf-/.test(name)) ? '\n\n\u26a0\ufe0f \u042d\u0442\u0430 \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0443\u043f\u0440\u0430\u0432\u043b\u044f\u0435\u0442\u0441\u044f Terraform. \u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u0438\u0432\u0435\u0434\u0451\u0442 \u043a \u0440\u0430\u0441\u0441\u0438\u043d\u0445\u0440\u043e\u043d\u0438\u0437\u0430\u0446\u0438\u0438 state!' : '';
|
||||||
|
if (!confirm('\u0423\u0434\u0430\u043b\u0438\u0442\u044c \u0444\u0443\u043d\u043a\u0446\u0438\u044e ' + name + '?' + tfWarn)) return;
|
||||||
try {
|
try {
|
||||||
await requestJSON(API_BASE + '/functions/' + encodeURIComponent(name), 'DELETE');
|
await requestJSON(API_BASE + '/functions/' + encodeURIComponent(name), 'DELETE');
|
||||||
showStatus('Function deleted: ' + name, 'ok');
|
showStatus('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0443\u0434\u0430\u043b\u0435\u043d\u0430: ' + name, 'ok');
|
||||||
await reloadAll();
|
await reloadAll();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showStatus('Delete failed: ' + e.message, 'err');
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0443\u0434\u0430\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -639,11 +720,13 @@
|
|||||||
const route = (trig.spec && trig.spec.relativeurl) || '-';
|
const route = (trig.spec && trig.spec.relativeurl) || '-';
|
||||||
const methods = (trig.spec && trig.spec.methods) || [];
|
const methods = (trig.spec && trig.spec.methods) || [];
|
||||||
const chips = methods.map(function (m) { return '<span class="chip">' + h(m) + '</span>'; }).join('');
|
const chips = methods.map(function (m) { return '<span class="chip">' + h(m) + '</span>'; }).join('');
|
||||||
const actions = [
|
var isGo = /go[-_]env/.test(env);
|
||||||
'<button class="btn ghost" onclick="openEdit(\'' + h(name) + '\')">Edit</button>',
|
var isTf = /^tf-/.test(name);
|
||||||
'<button class="btn ghost" onclick="openInvoke(\'' + h(name) + '\')">Invoke</button>',
|
var tfBadge = (isGo || isTf) ? '<span class="chip" style="background:#555;color:#ffa" title="Управляется Terraform. Изменения могут быть перезаписаны при terraform apply.">TF</span> ' : '';
|
||||||
'<button class="btn danger" onclick="removeFn(\'' + h(name) + '\')">Delete</button>'
|
var actions = tfBadge +
|
||||||
].join(' ');
|
'<button class="btn ghost" onclick="openEdit(\'' + h(name) + '\')">\u0420\u0435\u0434.</button> ' +
|
||||||
|
'<button class="btn ghost" onclick="openInvoke(\'' + h(name) + '\')">\u0412\u044b\u0437\u043e\u0432</button> ' +
|
||||||
|
'<button class="btn danger" onclick="removeFn(\'' + h(name) + '\')">\u0423\u0434\u0430\u043b\u0438\u0442\u044c</button>';
|
||||||
return '<tr>' +
|
return '<tr>' +
|
||||||
'<td class="mono">' + h(name) + '</td>' +
|
'<td class="mono">' + h(name) + '</td>' +
|
||||||
'<td>' + h(env) + '</td>' +
|
'<td>' + h(env) + '</td>' +
|
||||||
@@ -654,17 +737,71 @@
|
|||||||
'</tr>';
|
'</tr>';
|
||||||
}).join('');
|
}).join('');
|
||||||
|
|
||||||
document.getElementById('fn-rows').innerHTML = rows || '<tr><td colspan="3">No functions</td></tr>';
|
document.getElementById('fn-rows').innerHTML = rows || '<tr><td colspan="3">\u041d\u0435\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0439</td></tr>';
|
||||||
if (!rows) {
|
if (!rows) {
|
||||||
document.getElementById('fn-rows').innerHTML = '<tr><td colspan="6">No functions</td></tr>';
|
document.getElementById('fn-rows').innerHTML = '<tr><td colspan="6">\u041d\u0435\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0439</td></tr>';
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('fn-rows').innerHTML = '<tr><td colspan="6">Load error: ' + e.message + '</td></tr>';
|
document.getElementById('fn-rows').innerHTML = '<tr><td colspan="6">Load error: ' + e.message + '</td></tr>';
|
||||||
showStatus('Reload failed: ' + e.message, 'err');
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438: ' + e.message, 'err');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reloadAll();
|
function showLoginOverlay() {
|
||||||
|
document.getElementById('login-overlay').style.display = 'flex';
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideLoginOverlay() {
|
||||||
|
document.getElementById('login-overlay').style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doLogin() {
|
||||||
|
var btn = document.getElementById('l-btn');
|
||||||
|
var errEl = document.getElementById('l-error');
|
||||||
|
var token = (document.getElementById('l-token').value || '').trim();
|
||||||
|
var env = document.getElementById('l-env').value;
|
||||||
|
if (!token) { errEl.textContent = 'Введите токен'; errEl.style.display = 'block'; return; }
|
||||||
|
btn.disabled = true;
|
||||||
|
errEl.style.display = 'none';
|
||||||
|
try {
|
||||||
|
const res = await fetch(API_BASE + '/auth', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({token: token, env: env})
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const d = await res.json().catch(function() { return {}; });
|
||||||
|
throw new Error(d.error || 'Ошибка входа');
|
||||||
|
}
|
||||||
|
localStorage.setItem('auth_token', token);
|
||||||
|
localStorage.setItem('auth_env', env);
|
||||||
|
hideLoginOverlay();
|
||||||
|
reloadAll();
|
||||||
|
} catch(e) {
|
||||||
|
errEl.textContent = e.message;
|
||||||
|
errEl.style.display = 'block';
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function doLogout() {
|
||||||
|
localStorage.removeItem('auth_token');
|
||||||
|
localStorage.removeItem('auth_env');
|
||||||
|
try { document.getElementById('l-token').value = ''; } catch(_) {}
|
||||||
|
showLoginOverlay();
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkAuth() {
|
||||||
|
if (!localStorage.getItem('auth_token')) {
|
||||||
|
showLoginOverlay();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hideLoginOverlay();
|
||||||
|
reloadAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
checkAuth();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,473 @@
|
|||||||
|
# Аудит: Terraform Provider vs Fission Canonical CRD
|
||||||
|
|
||||||
|
**Дата:** 2026-06-03
|
||||||
|
**Ветка:** `feat/provider-audit`
|
||||||
|
**Предыдущая версия:** v0.2.4 (ветка `feat/console`)
|
||||||
|
|
||||||
|
## Методология
|
||||||
|
|
||||||
|
Сравнение производилось по трём источникам:
|
||||||
|
1. **Наш код** — `/terraform/provider/internal/resources/*.go` и `/terraform/provider/internal/client/client.go`
|
||||||
|
2. **Fission CRD types.go** — `github.com/fission/fission/pkg/apis/core/v1/types.go` (канонические Go-структуры)
|
||||||
|
3. **Реальные CRD объекты в кластере** — `kubectl get` для environments/packages/functions/httptriggers (наши vs CLI-созданные)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. ENVIRONMENT (fission_environment)
|
||||||
|
|
||||||
|
### 1.1 Что у нас
|
||||||
|
|
||||||
|
```go
|
||||||
|
// environmentResourceModel
|
||||||
|
ID, Name, Image, Version(default=3), PoolSize(default=3), Namespace, UID
|
||||||
|
```
|
||||||
|
|
||||||
|
`environmentToUnstructured` генерирует:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"version": 3,
|
||||||
|
"runtime": { "image": "..." },
|
||||||
|
"poolsize": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 Что делает Fission CLI (`fission env create`)
|
||||||
|
|
||||||
|
Fission CLI (из `environment/create.go`) создает полный `EnvironmentSpec`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"version": 3,
|
||||||
|
"runtime": {
|
||||||
|
"image": "ghcr.io/fission/python-env",
|
||||||
|
"container": { "name": "env-name", "resources": {} },
|
||||||
|
"podspec": { "containers": [{"name": "env-name", "resources": {}}] }
|
||||||
|
},
|
||||||
|
"builder": {
|
||||||
|
"image": "ghcr.io/fission/go-builder",
|
||||||
|
"command": "build",
|
||||||
|
"container": { "name": "builder", "resources": {} },
|
||||||
|
"podspec": { "containers": [{"name": "builder", "resources": {}}] }
|
||||||
|
},
|
||||||
|
"poolsize": 3,
|
||||||
|
"resources": {},
|
||||||
|
"imagepullsecret": "",
|
||||||
|
"keeparchive": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.3 Реальное сравнение в кластере
|
||||||
|
|
||||||
|
| Поле | Наш (tf-python-env) | CLI (python) | Вердикт |
|
||||||
|
|------|---------------------|--------------|---------|
|
||||||
|
| `spec.version` | 3 | 3 | ✅ OK |
|
||||||
|
| `spec.runtime.image` | ✅ | ✅ | ✅ OK |
|
||||||
|
| `spec.runtime.container` | ❌ отсутствует | `{name, resources}` | ⚠️ Fission заполняет defaults — не критично |
|
||||||
|
| `spec.runtime.podspec` | ❌ отсутствует | `{containers}` | ⚠️ Fission заполняет defaults — не критично |
|
||||||
|
| `spec.builder` | ❌ ОТСУТСТВУЕТ | `{image, command, container, podspec}` | 🔴 **КРИТИЧНО для Go** |
|
||||||
|
| `spec.poolsize` | 3 | 3 | ✅ OK |
|
||||||
|
| `spec.resources` | ❌ отсутствует | `{}` | ⚠️ Defaults — не критично |
|
||||||
|
| `spec.imagepullsecret` | ❌ | `""` | ⚠️ Можно добавить позже |
|
||||||
|
| `spec.keeparchive` | ❌ | `false` | ⚠️ Нужно для JVM — не критично сейчас |
|
||||||
|
|
||||||
|
### 1.4 Выводы по Environment
|
||||||
|
|
||||||
|
**Критичный баг:** Невозможно создать environment с builder (нет полей `builder_image`, `builder_command`). Это блокирует Go, любой язык с build step.
|
||||||
|
|
||||||
|
**Что добавить (приоритетно):**
|
||||||
|
- `builder_image` (string, optional) → `spec.builder.image`
|
||||||
|
- `builder_command` (string, optional) → `spec.builder.command`
|
||||||
|
|
||||||
|
**Что можно добавить позже:**
|
||||||
|
- `resources` (object) → `spec.resources`
|
||||||
|
- `imagepullsecret` (string) → `spec.imagepullsecret`
|
||||||
|
- `keeparchive` (bool) → `spec.keeparchive`
|
||||||
|
- `runtime_container_name` — Fission автозаполняет, мы не ставим, k8s принимает без него
|
||||||
|
|
||||||
|
**Что НЕ нужно (Fission автозаполняет):**
|
||||||
|
- `spec.runtime.container`, `spec.runtime.podspec` — заливаются defaults на стороне сервера
|
||||||
|
- `spec.builder.container`, `spec.builder.podspec` — аналогично
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. PACKAGE (fission_package)
|
||||||
|
|
||||||
|
### 2.1 Что у нас
|
||||||
|
|
||||||
|
```go
|
||||||
|
// packageResourceModel
|
||||||
|
ID, Name, Environment, SourceDir, CodePath, CodeHash, BuildCmd, Namespace, UID, BuildStatus, BuildLog
|
||||||
|
```
|
||||||
|
|
||||||
|
`packageToUnstructured` генерирует:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"deployment": {
|
||||||
|
"type": "literal",
|
||||||
|
"literal": "base64..."
|
||||||
|
},
|
||||||
|
"environment": { "name": "...", "namespace": "..." },
|
||||||
|
"source": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Что делает Fission CLI
|
||||||
|
|
||||||
|
Для **deploy-only** (literal):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"deployment": {
|
||||||
|
"type": "literal",
|
||||||
|
"literal": "base64...",
|
||||||
|
"checksum": {}
|
||||||
|
},
|
||||||
|
"environment": { "name": "...", "namespace": "..." },
|
||||||
|
"source": { "checksum": {} }
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"buildstatus": "none"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Для **source-with-builder** (Go, Node с build):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"source": {
|
||||||
|
"type": "literal",
|
||||||
|
"literal": "base64-of-zip...",
|
||||||
|
"checksum": {}
|
||||||
|
},
|
||||||
|
"environment": { "name": "...", "namespace": "..." },
|
||||||
|
"buildcmd": "build"
|
||||||
|
},
|
||||||
|
"status": {
|
||||||
|
"buildstatus": "pending"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Для **large archives** (>256KB):
|
||||||
|
- Загрузка через StorageSvc `/v1/archive` (multipart POST)
|
||||||
|
- В CRD сохраняется `type: "url"`, `url: "http://storagesvc/v1/archive?id=..."`
|
||||||
|
|
||||||
|
### 2.3 Реальное сравнение в кластере
|
||||||
|
|
||||||
|
| Поле | Наш (tf-hello-pkg) | CLI (hello-*) | Вердикт |
|
||||||
|
|------|---------------------|---------------|---------|
|
||||||
|
| `spec.deployment.type` | `"literal"` | `"literal"` | ✅ OK |
|
||||||
|
| `spec.deployment.literal` | ✅ base64 | ✅ base64 | ✅ OK |
|
||||||
|
| `spec.deployment.checksum` | ❌ отсутствует | `{}` | ⚠️ K8s принимает без, но лучше добавить |
|
||||||
|
| `spec.environment` | ✅ | ✅ | ✅ OK |
|
||||||
|
| `spec.source` | `{}` (пустая map) | `{"checksum":{}}` | 🟡 **БАГ**: мы ставим пустой source — не мешает, но мусор |
|
||||||
|
| `spec.buildcmd` | ✅ (если задан) | ✅ | ✅ OK |
|
||||||
|
| `status.buildstatus` | `"none"` (от k8s default) | `"none"` | ✅ OK (k8s сам ставит) |
|
||||||
|
|
||||||
|
### 2.4 Что ОТСУТСТВУЕТ для builder pipeline (Go)
|
||||||
|
|
||||||
|
Для Go-функций нужен **source** package (не deployment):
|
||||||
|
1. Код упаковывается в zip
|
||||||
|
2. zip кодируется в base64 → `spec.source.literal` (если <256KB)
|
||||||
|
3. `spec.source.type` = `"literal"`
|
||||||
|
4. `spec.deployment` = пусто
|
||||||
|
5. `spec.buildcmd` = `"build"` (или пользовательская)
|
||||||
|
6. `status.buildstatus` = `"pending"` → builder собирает → `"succeeded"`/`"failed"`
|
||||||
|
7. После build: `spec.deployment` заполняется builder'ом (url на StorageSvc)
|
||||||
|
|
||||||
|
### 2.5 Выводы по Package
|
||||||
|
|
||||||
|
**Баг (некритичный):** Мы ВСЕГДА ставим `"source": {}` — пустой объект. Fission ставит `"source": {"checksum": {}}`. Оба варианта работают, но чистый вариант — не ставить source вообще если нет source archive.
|
||||||
|
|
||||||
|
**Что добавить (приоритетно):**
|
||||||
|
- **Режим source archive** — для Go и языков с build step. Нужно:
|
||||||
|
- Флаг/переключатель: deployment-only vs source-with-build
|
||||||
|
- Упаковка source_dir в zip → base64 → `spec.source.literal`
|
||||||
|
- Проверка размера <256KB (лимит ArchiveLiteralSizeLimit)
|
||||||
|
- Очистка `spec.deployment` при source mode
|
||||||
|
- `status.buildstatus` = `"pending"` на create
|
||||||
|
|
||||||
|
**Что можно добавить позже:**
|
||||||
|
- StorageSvc загрузка для >256KB архивов
|
||||||
|
- `spec.source.checksum`
|
||||||
|
- Поддержка `type: "url"` (для уже загруженных архивов)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. FUNCTION (fission_function)
|
||||||
|
|
||||||
|
### 3.1 Что у нас
|
||||||
|
|
||||||
|
```go
|
||||||
|
// functionResourceModel
|
||||||
|
ID, Name, Environment, PackageName, Entrypoint, Namespace, UID
|
||||||
|
```
|
||||||
|
|
||||||
|
`functionToUnstructured` генерирует:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"environment": { "name": "...", "namespace": "..." },
|
||||||
|
"InvokeStrategy": {
|
||||||
|
"ExecutionStrategy": { "ExecutorType": "poolmgr" },
|
||||||
|
"StrategyType": "execution"
|
||||||
|
},
|
||||||
|
"package": {
|
||||||
|
"packageref": { "name": "...", "namespace": "..." },
|
||||||
|
"functionName": "main.main"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Что делает Fission CLI (`fission fn create`)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"environment": { "name": "...", "namespace": "..." },
|
||||||
|
"InvokeStrategy": {
|
||||||
|
"ExecutionStrategy": {
|
||||||
|
"ExecutorType": "poolmgr",
|
||||||
|
"MaxScale": 0,
|
||||||
|
"MinScale": 0,
|
||||||
|
"SpecializationTimeout": 120,
|
||||||
|
"TargetCPUPercent": 0
|
||||||
|
},
|
||||||
|
"StrategyType": "execution"
|
||||||
|
},
|
||||||
|
"package": {
|
||||||
|
"packageref": {
|
||||||
|
"name": "...",
|
||||||
|
"namespace": "...",
|
||||||
|
"resourceversion": "6000598"
|
||||||
|
},
|
||||||
|
"functionName": ""
|
||||||
|
},
|
||||||
|
"functionTimeout": 60,
|
||||||
|
"idletimeout": 120,
|
||||||
|
"concurrency": 500,
|
||||||
|
"requestsPerPod": 1,
|
||||||
|
"resources": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 Реальное сравнение в кластере
|
||||||
|
|
||||||
|
| Поле | Наш (tf-hello-fn) | CLI (fn-js-acc) | Вердикт |
|
||||||
|
|------|---------------------|-----------------|---------|
|
||||||
|
| `spec.environment` | ✅ | ✅ | ✅ OK |
|
||||||
|
| `spec.InvokeStrategy.ExecutionStrategy.ExecutorType` | `"poolmgr"` | `"poolmgr"` | ✅ OK |
|
||||||
|
| `spec.InvokeStrategy.ExecutionStrategy.MaxScale` | ❌ отсутствует | `0` | ⚠️ Defaults работают, но лучше ставить |
|
||||||
|
| `spec.InvokeStrategy.ExecutionStrategy.MinScale` | ❌ | `0` | ⚠️ |
|
||||||
|
| `spec.InvokeStrategy.ExecutionStrategy.SpecializationTimeout` | ❌ | `120` | ⚠️ |
|
||||||
|
| `spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent` | ❌ | `0` | ⚠️ Не критично |
|
||||||
|
| `spec.InvokeStrategy.StrategyType` | `"execution"` | `"execution"` | ✅ OK |
|
||||||
|
| `spec.package.packageref.resourceversion` | ❌ отсутствует | ✅ | 🟡 CLI ставит для оптимизации, мы — нет |
|
||||||
|
| `spec.package.functionName` | ✅ `"main.main"` | `""` (или функция) | ✅ OK |
|
||||||
|
| `spec.functionTimeout` | ❌ | `60` | 🟡 Полезно для управления таймаутами |
|
||||||
|
| `spec.idletimeout` | ❌ | `120` | 🟡 Полезно для scale-to-zero |
|
||||||
|
| `spec.concurrency` | ❌ | `500` | ⚠️ |
|
||||||
|
| `spec.requestsPerPod` | ❌ | `1` | ⚠️ |
|
||||||
|
| `spec.resources` | ❌ | `{}` | ⚠️ |
|
||||||
|
|
||||||
|
### 3.4 Выводы по Function
|
||||||
|
|
||||||
|
**Критичных багов нет.** Наши функции работают, потому что k8s/Fission подставляет defaults. НО:
|
||||||
|
|
||||||
|
**Что добавить (приоритетно):**
|
||||||
|
- `executor_type` (string, optional, default="poolmgr") → для newdeploy/container strategies
|
||||||
|
- `function_timeout` (int, optional) → `spec.functionTimeout` — важно для долгих функций
|
||||||
|
- `idle_timeout` (int, optional) → `spec.idletimeout` — управление scale-to-zero
|
||||||
|
- `min_scale` / `max_scale` (int, optional) → ExecutionStrategy — для newdeploy
|
||||||
|
|
||||||
|
**Что можно добавить позже:**
|
||||||
|
- `concurrency` (int) → `spec.concurrency`
|
||||||
|
- `requests_per_pod` (int) → `spec.requestsPerPod`
|
||||||
|
- `specialization_timeout` (int) → `spec.InvokeStrategy.ExecutionStrategy.SpecializationTimeout`
|
||||||
|
- `resources` (object) → CPU/MEM limits
|
||||||
|
- `secrets`, `configmaps` (list) → volume mounts
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. HTTP TRIGGER (fission_http_trigger)
|
||||||
|
|
||||||
|
### 4.1 Что у нас
|
||||||
|
|
||||||
|
```go
|
||||||
|
// httpTriggerResourceModel
|
||||||
|
ID, Name, Function, URL, Methods, CreateIngress, Host, Namespace, UID
|
||||||
|
```
|
||||||
|
|
||||||
|
`httpTriggerToUnstructured` генерирует:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"relativeurl": "/tf-hello",
|
||||||
|
"methods": ["GET"],
|
||||||
|
"functionref": { "type": "name", "name": "tf-hello-fn" },
|
||||||
|
"createingress": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Что делает Fission CLI
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"spec": {
|
||||||
|
"relativeurl": "/hello",
|
||||||
|
"methods": ["GET"],
|
||||||
|
"functionref": {
|
||||||
|
"type": "name",
|
||||||
|
"name": "hello",
|
||||||
|
"functionweights": null
|
||||||
|
},
|
||||||
|
"createingress": false,
|
||||||
|
"host": "",
|
||||||
|
"ingressconfig": {
|
||||||
|
"annotations": null,
|
||||||
|
"host": "*",
|
||||||
|
"path": "/hello",
|
||||||
|
"tls": ""
|
||||||
|
},
|
||||||
|
"method": "",
|
||||||
|
"prefix": ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Реальное сравнение в кластере
|
||||||
|
|
||||||
|
| Поле | Наш (tf-hello-route) | CLI (hello-route) | Вердикт |
|
||||||
|
|------|----------------------|-------------------|---------|
|
||||||
|
| `spec.relativeurl` | ✅ | ✅ | ✅ OK |
|
||||||
|
| `spec.methods` | ✅ | ✅ | ✅ OK |
|
||||||
|
| `spec.functionref.type` | `"name"` | `"name"` | ✅ OK |
|
||||||
|
| `spec.functionref.name` | ✅ | ✅ | ✅ OK |
|
||||||
|
| `spec.functionref.functionweights` | ❌ | `null` | ✅ Не нужно |
|
||||||
|
| `spec.createingress` | ✅ | ✅ | ✅ OK |
|
||||||
|
| `spec.host` | ❌ (если пусто) | `""` | ✅ Не критично |
|
||||||
|
| `spec.ingressconfig` | Частично (host) | Полный | ⚠️ IngressConfig неполный |
|
||||||
|
| `spec.method` | ❌ | `""` | ✅ Legacy, не нужно |
|
||||||
|
| `spec.prefix` | ❌ | `""` | ⚠️ Для prefix routing — добавить |
|
||||||
|
|
||||||
|
### 4.4 Выводы по HTTPTrigger
|
||||||
|
|
||||||
|
**Багов нет.** Работает корректно. Мелкие расхождения не влияют.
|
||||||
|
|
||||||
|
**Что можно добавить позже:**
|
||||||
|
- `prefix` (string) → `spec.prefix` — для prefix-based routing
|
||||||
|
- `keep_prefix` (bool) → `spec.keepPrefix`
|
||||||
|
- Полный `ingressconfig` (annotations, path, tls) — при `create_ingress=true`
|
||||||
|
- `function_weights` (map) → для canary deployments
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. CLIENT (client.go)
|
||||||
|
|
||||||
|
### 5.1 Оценка
|
||||||
|
|
||||||
|
**Код корректный.** Чистый CRUD через `dynamic.Interface`:
|
||||||
|
- 4 GVR определения (environments, packages, functions, httptriggers)
|
||||||
|
- CRUD для каждого: Create/Get/Update/Delete
|
||||||
|
- `IsNotFound()` для обработки 404
|
||||||
|
- `New()` строит config из kubeconfig + context
|
||||||
|
|
||||||
|
**Расхождений с Fission нет** — это наш собственный low-level клиент для работы с CRD.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. VALIDATION (validation_helpers.go, entrypoint validation)
|
||||||
|
|
||||||
|
### 6.1 Оценка
|
||||||
|
|
||||||
|
- `ensureEnvironmentExists` — ✅ корректно (проверяет наличие env перед созданием pkg/fn)
|
||||||
|
- `ensurePackageExists` — ✅ корректно
|
||||||
|
- `validateEntrypointAgainstPackageSource` — ⚠️ Проверяет только Python `def funcname(`. Не проверяет:
|
||||||
|
- Node: `module.exports` или `export function`
|
||||||
|
- Go: plugin symbol
|
||||||
|
- PHP: `function handler(`
|
||||||
|
- Ruby: `def handler`
|
||||||
|
|
||||||
|
**Это допустимо** — избыточная валидация может мешать. Лучше валидировать только точно известные паттерны.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. СВОДНАЯ ТАБЛИЦА ПРИОРИТЕТОВ
|
||||||
|
|
||||||
|
### 🔴 Критично (блокирует функционал)
|
||||||
|
|
||||||
|
| # | Ресурс | Проблема | Решение |
|
||||||
|
|---|--------|----------|---------|
|
||||||
|
| 1 | Environment | Нет builder support | Добавить `builder_image`, `builder_command` |
|
||||||
|
| 2 | Package | Нет source archive mode | Добавить zip-упаковку source_dir → `spec.source.literal` |
|
||||||
|
|
||||||
|
### 🟡 Важно (улучшает пользовательский опыт)
|
||||||
|
|
||||||
|
| # | Ресурс | Проблема | Решение |
|
||||||
|
|---|--------|----------|---------|
|
||||||
|
| 3 | Function | Захардкожен poolmgr | Добавить `executor_type` с optional default |
|
||||||
|
| 4 | Function | Нет пользовательских таймаутов | Добавить `function_timeout`, `idle_timeout` |
|
||||||
|
| 5 | Function | Нет min/max scale | Добавить `min_scale`, `max_scale` |
|
||||||
|
| 6 | Package | Пустой `source: {}` мусор | Убрать пустой source из payload |
|
||||||
|
|
||||||
|
### ⚪ Не критично (можно позже)
|
||||||
|
|
||||||
|
| # | Ресурс | Проблема |
|
||||||
|
|---|--------|----------|
|
||||||
|
| 7 | Environment | Нет resources, imagepullsecret, keeparchive |
|
||||||
|
| 8 | Function | Нет concurrency, requestsPerPod, resources, secrets, configmaps |
|
||||||
|
| 9 | HTTPTrigger | Нет prefix, keepPrefix, полного ingressconfig |
|
||||||
|
| 10 | Package | Нет StorageSvc загрузки (>256KB) |
|
||||||
|
| 11 | Package | Нет checksum |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. ПЛАН РЕАЛИЗАЦИИ (предлагаемый)
|
||||||
|
|
||||||
|
### Этап 1: Builder support (Environment + Package)
|
||||||
|
|
||||||
|
**environment_resource.go:**
|
||||||
|
- Добавить поля `builder_image` и `builder_command` в модель и schema
|
||||||
|
- Добавить `spec.builder` в `environmentToUnstructured` (если builder_image задан)
|
||||||
|
- Обновить `unstructuredToEnvironmentModel` для чтения builder полей
|
||||||
|
|
||||||
|
**package_resource.go:**
|
||||||
|
- Добавить поле `deploy_type` (string: `"literal"` или `"source"`, default `"literal"`)
|
||||||
|
- При `deploy_type = "source"`: zip source_dir → base64 → `spec.source.literal`, `spec.deployment` пустой
|
||||||
|
- Убрать пустой `"source": {}` при deploy_type = "literal"
|
||||||
|
- Добавить base64 size check (<256KB) при literal mode
|
||||||
|
|
||||||
|
### Этап 2: Function tuning
|
||||||
|
|
||||||
|
**function_resource.go:**
|
||||||
|
- Добавить optional поля: `executor_type`, `function_timeout`, `idle_timeout`, `min_scale`, `max_scale`
|
||||||
|
- Обновить `functionToUnstructured` для заполнения ExecutionStrategy полностью
|
||||||
|
- Обновить `unstructuredToFunctionModel` для чтения новых полей
|
||||||
|
|
||||||
|
### Этап 3: Мелкие улучшения
|
||||||
|
- HTTPTrigger: prefix, keepPrefix
|
||||||
|
- Package: checksum
|
||||||
|
- Environment: resources, imagepullsecret
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. ВЫВОД
|
||||||
|
|
||||||
|
Наш провайдер **работает корректно для основного сценария**: Python/Node/PHP/Ruby/Perl literal deployment + poolmgr executor. Все критические поля (version, runtime.image, poolsize, deployment.literal, functionName, relativeurl, methods) генерируются правильно.
|
||||||
|
|
||||||
|
**Главные пробелы:**
|
||||||
|
1. Нет builder support → Go и любые compiled languages не работают через builder pipeline
|
||||||
|
2. Нет source archive → только deployment-only (literal из одного файла)
|
||||||
|
3. Function executor hardcoded to poolmgr → нет newdeploy/container strategy
|
||||||
|
4. Нет пользовательских таймаутов
|
||||||
|
|
||||||
|
Ни один из пробелов не является **ошибкой** в существующем коде — это **недостающий функционал**. То, что есть, соответствует канону Fission.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Тест auth v0.5.0 — 2026-04-19
|
||||||
|
|
||||||
|
## Что проверено
|
||||||
|
|
||||||
|
| Тест | Ожидание | Результат |
|
||||||
|
|------|----------|-----------|
|
||||||
|
| GET /console/ | 200 | ✅ 200 |
|
||||||
|
| POST /console/api/auth {token: "badtoken"} | {"error":"invalid token"} | ✅ |
|
||||||
|
| GET /console/api/functions без токена | 401 | ✅ 401 |
|
||||||
|
| Логин с реальным YC IAM токеном | {"ok":true,"env":"test"} | ⏳ не проверено — нет токена |
|
||||||
|
|
||||||
|
## Что не проверено
|
||||||
|
|
||||||
|
- Полный flow: логин → появление UI → CRUD функций
|
||||||
|
- Logout → блокировка доступа
|
||||||
|
- Проверка `env` (dev/prod)
|
||||||
|
|
||||||
|
## Итог
|
||||||
|
|
||||||
|
Защита работает: без токена — 401, плохой токен — ошибка. Полный flow нужно проверить вручную в браузере после получения YC IAM токена.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# Thinking Log — Аудит провайдера, 2026-06-03
|
||||||
|
|
||||||
|
## Задача
|
||||||
|
Тщательное сравнение нашего Terraform provider для Fission с каноническим поведением Fission CLI и CRD types.
|
||||||
|
|
||||||
|
## Что было сделано
|
||||||
|
|
||||||
|
### 1. Чтение нашего кода
|
||||||
|
Прочитаны все 10 .go файлов (~1500 строк):
|
||||||
|
- `environment_resource.go` (136 строк)
|
||||||
|
- `package_resource.go` (460 строк)
|
||||||
|
- `function_resource.go` (350 строк)
|
||||||
|
- `http_trigger_resource.go` (310 строк)
|
||||||
|
- `client.go` (295 строк)
|
||||||
|
- `validation_helpers.go`, `import_helpers.go`
|
||||||
|
- 3 тест-файла
|
||||||
|
|
||||||
|
### 2. Чтение канонических исходников Fission
|
||||||
|
- `pkg/apis/core/v1/types.go` — все CRD Go-структуры
|
||||||
|
- `pkg/apis/core/v1/const.go` — константы (ArchiveLiteralSizeLimit=256KB, BuildStatus*, ExecutorType*)
|
||||||
|
- CLI: `environment/create.go`, `package/create.go`, `package/util/util.go`
|
||||||
|
- StorageSvc: `storagesvc/client/client.go`
|
||||||
|
|
||||||
|
### 3. Дамп реальных CRD из кластера
|
||||||
|
Через kubectl получены ВСЕ объекты всех 4 типов из кластера:
|
||||||
|
- 20+ environments (наши tf-* и CLI-созданные)
|
||||||
|
- 15+ functions (наши tf-* и CLI-созданные)
|
||||||
|
- 15+ packages (наши и CLI)
|
||||||
|
- 15+ httptriggers
|
||||||
|
|
||||||
|
### 4. Сравнительный анализ
|
||||||
|
Для каждого ресурса: поле-за-полем наш payload vs CLI payload vs канон types.go.
|
||||||
|
|
||||||
|
## Ключевые находки
|
||||||
|
|
||||||
|
### Что правильно
|
||||||
|
- environment: version, runtime.image, poolsize — ок
|
||||||
|
- package: deployment.literal base64 — ок
|
||||||
|
- function: InvokeStrategy structure, package.functionName — ок
|
||||||
|
- httptrigger: relativeurl, methods, functionref, createingress — ок
|
||||||
|
- client.go: чистый CRUD, GVR правильные — ок
|
||||||
|
|
||||||
|
### Что отсутствует (критично)
|
||||||
|
1. **Environment.builder** — нет builder_image/builder_command → Go не работает через builder pipeline
|
||||||
|
2. **Package source archive** — только deployment-only, нет source+build flow
|
||||||
|
|
||||||
|
### Что отсутствует (важно)
|
||||||
|
3. **Function executor_type** — hardcoded poolmgr, нет newdeploy/container
|
||||||
|
4. **Function timeouts** — нет functionTimeout, idleTimeout
|
||||||
|
5. **Function scaling** — нет minScale, maxScale
|
||||||
|
|
||||||
|
### Что отсутствует (некритично)
|
||||||
|
6. Package: пустой `source: {}` — мусор но не bug
|
||||||
|
7. Environment: resources, imagepullsecret, keeparchive
|
||||||
|
8. Function: concurrency, requestsPerPod, resources, secrets
|
||||||
|
9. HTTPTrigger: prefix, keepPrefix, полный ingressconfig
|
||||||
|
|
||||||
|
## Решение
|
||||||
|
Написан полный аудит-документ: `doc/AUDIT_PROVIDER_VS_FISSION_2026-06-03.md`
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
def good_function():
|
||||||
|
return "correct"
|
||||||
|
|
||||||
|
def main():
|
||||||
|
return "this is main"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-bad-entry-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-bad-entry-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-bad-entry-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.nonexistent_function" # Wrong entrypoint
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-bad-entry-route"
|
||||||
|
url = "/bad-entrypoint"
|
||||||
|
methods = ["GET"]
|
||||||
|
function = fission_function.fn.name
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
def fib(n):
|
||||||
|
if n <= 1:
|
||||||
|
return n
|
||||||
|
return fib(n-1) + fib(n-2)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
return f"fib(100)={fib(100)}"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-deep-recursion-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-deep-recursion-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-deep-recursion-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-deep-recursion-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/deep-recursion"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
def main(): return "env-1"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
def main(): return "env-2"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
def main(): return "env-3"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
def main(): return "env-4"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
def main(): return "env-5"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
def main(): return "v10"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-freq-update-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-freq-update-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-freq-update-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-freq-update-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/freq-update"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
module github.com/user/fn
|
||||||
|
|
||||||
|
go 1.23
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handler — точка входа для Fission go-env.
|
||||||
|
// Go builder компилирует этот файл в .so плагин,
|
||||||
|
// go-env загружает его через plugin.Open().
|
||||||
|
func Handler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/plain")
|
||||||
|
fmt.Fprintf(w, "Hello from real Go in Fission (builder pipeline)")
|
||||||
|
}
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
// Handler используется binary-env: binary получает HTTP request через stdin,
|
|
||||||
// stdout является HTTP response body.
|
|
||||||
//
|
|
||||||
// Для деплоя нужно скомпилировать перед terraform apply:
|
|
||||||
// CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o ../dist/handler .
|
|
||||||
//
|
|
||||||
// Compiled size: ~1.6MB (слишком велико для literal deployment).
|
|
||||||
// Используется shell-based handler в dist/handler (см. ниже).
|
|
||||||
func main() {
|
|
||||||
fmt.Print("Hello from Go in Fission")
|
|
||||||
}
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Handler(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", "text/plain")
|
|
||||||
fmt.Fprintf(w, "Hello from Go in Fission")
|
|
||||||
}
|
|
||||||
+14
-10
@@ -12,26 +12,30 @@ provider "fission" {
|
|||||||
namespace = "default"
|
namespace = "default"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Go использует binary-env: функция является скомпилированным Linux-бинарником.
|
# Настоящий Go через builder pipeline:
|
||||||
# Перед apply необходимо скомпилировать:
|
# go-builder компилирует handler.go → .so плагин
|
||||||
# CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o dist/handler code/
|
# go-env загружает .so через plugin.Open()
|
||||||
resource "fission_environment" "go" {
|
resource "fission_environment" "go" {
|
||||||
name = "tf-go-hello-env"
|
name = "tf-go-hello-env"
|
||||||
image = "ghcr.io/fission/binary-env"
|
image = "ghcr.io/fission/go-env"
|
||||||
version = 3
|
builder_image = "ghcr.io/fission/go-builder"
|
||||||
|
builder_command = "build"
|
||||||
|
version = 3
|
||||||
}
|
}
|
||||||
|
|
||||||
resource "fission_package" "pkg" {
|
resource "fission_package" "pkg" {
|
||||||
name = "tf-go-hello-pkg"
|
name = "tf-go-hello-pkg"
|
||||||
environment = fission_environment.go.name
|
environment = fission_environment.go.name
|
||||||
code_path = "${path.module}/dist/handler"
|
source_dir = "${path.module}/code"
|
||||||
|
deploy_type = "source"
|
||||||
|
build_command = "build"
|
||||||
}
|
}
|
||||||
|
|
||||||
resource "fission_function" "fn" {
|
resource "fission_function" "fn" {
|
||||||
name = "tf-go-hello-fn"
|
name = "tf-go-hello-fn"
|
||||||
environment = fission_environment.go.name
|
environment = fission_environment.go.name
|
||||||
package_name = fission_package.pkg.name
|
package_name = fission_package.pkg.name
|
||||||
entrypoint = "handler"
|
entrypoint = "Handler"
|
||||||
}
|
}
|
||||||
|
|
||||||
resource "fission_http_trigger" "route" {
|
resource "fission_http_trigger" "route" {
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "test"
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Missing image — should fail
|
||||||
|
resource "fission_environment" "bad_env" {
|
||||||
|
name = "tf-invalid-env"
|
||||||
|
# image = "..." # MISSING REQUIRED FIELD
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-invalid-pkg"
|
||||||
|
environment = fission_environment.bad_env.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-invalid-fn"
|
||||||
|
environment = fission_environment.bad_env.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "test"
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-missing-ref-route"
|
||||||
|
url = "/missing-ref"
|
||||||
|
methods = ["GET"]
|
||||||
|
function = "tf-missing-ref-fn"
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "env-1"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "env-2"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "env-3"
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import nonexistent_module_xyz_12345
|
||||||
|
|
||||||
|
def main():
|
||||||
|
return nonexistent_module_xyz_12345.do_something()
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-neg-badimport-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-neg-badimport-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-neg-badimport-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-neg-badimport-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/neg/badimport"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Пытаемся создать environment с именем, которое уже существует (tf-python-env из hello-python)
|
||||||
|
resource "fission_environment" "conflict" {
|
||||||
|
name = "tf-python-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def not_main():
|
||||||
|
return "there is no main() here, Fission will fail to invoke"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-neg-nomain-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-neg-nomain-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-neg-nomain-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-neg-nomain-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/neg/nomain"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
def main():
|
||||||
|
x = 1 / 0
|
||||||
|
return f"result: {x}"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-neg-rterr-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-neg-rterr-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-neg-rterr-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-neg-rterr-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/neg/rterr"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main(:
|
||||||
|
return "this should never work"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-neg-syntax-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-neg-syntax-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-neg-syntax-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-neg-syntax-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/neg/syntax"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "orphan-test"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "python" {
|
||||||
|
name = "tf-orphan-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-orphan-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-orphan-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-orphan-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/orphan-test"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def exists():
|
||||||
|
return "x"
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_environment" "env" {
|
||||||
|
name = "tf-validate-bad-entry-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-validate-bad-entry-pkg"
|
||||||
|
environment = fission_environment.env.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-validate-bad-entry-fn"
|
||||||
|
environment = fission_environment.env.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "x"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-validate-missing-env-pkg"
|
||||||
|
environment = "env-does-not-exist-xyz"
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
@@ -24,13 +24,15 @@ type EnvironmentResource struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type environmentResourceModel struct {
|
type environmentResourceModel struct {
|
||||||
ID types.String `tfsdk:"id"`
|
ID types.String `tfsdk:"id"`
|
||||||
Name types.String `tfsdk:"name"`
|
Name types.String `tfsdk:"name"`
|
||||||
Image types.String `tfsdk:"image"`
|
Image types.String `tfsdk:"image"`
|
||||||
Version types.Int64 `tfsdk:"version"`
|
Version types.Int64 `tfsdk:"version"`
|
||||||
PoolSize types.Int64 `tfsdk:"poolsize"`
|
PoolSize types.Int64 `tfsdk:"poolsize"`
|
||||||
Namespace types.String `tfsdk:"namespace"`
|
BuilderImage types.String `tfsdk:"builder_image"`
|
||||||
UID types.String `tfsdk:"uid"`
|
BuilderCommand types.String `tfsdk:"builder_command"`
|
||||||
|
Namespace types.String `tfsdk:"namespace"`
|
||||||
|
UID types.String `tfsdk:"uid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewEnvironmentResource() resource.Resource {
|
func NewEnvironmentResource() resource.Resource {
|
||||||
@@ -68,6 +70,14 @@ func (r *EnvironmentResource) Schema(_ context.Context, _ resource.SchemaRequest
|
|||||||
Default: int64default.StaticInt64(3),
|
Default: int64default.StaticInt64(3),
|
||||||
Description: "Размер пула pre-warmed контейнеров.",
|
Description: "Размер пула pre-warmed контейнеров.",
|
||||||
},
|
},
|
||||||
|
"builder_image": schema.StringAttribute{
|
||||||
|
Optional: true,
|
||||||
|
Description: "Builder image для Environment (например ghcr.io/fission/go-builder). Нужен для языков с build step (Go и др.).",
|
||||||
|
},
|
||||||
|
"builder_command": schema.StringAttribute{
|
||||||
|
Optional: true,
|
||||||
|
Description: "Команда сборки в builder контейнере (например 'build').",
|
||||||
|
},
|
||||||
"namespace": schema.StringAttribute{
|
"namespace": schema.StringAttribute{
|
||||||
Optional: true,
|
Optional: true,
|
||||||
Computed: true,
|
Computed: true,
|
||||||
@@ -216,6 +226,26 @@ func (r *EnvironmentResource) ImportState(ctx context.Context, req resource.Impo
|
|||||||
|
|
||||||
// environmentToUnstructured преобразует Terraform model в Kubernetes CRD payload.
|
// environmentToUnstructured преобразует Terraform model в Kubernetes CRD payload.
|
||||||
func environmentToUnstructured(model environmentResourceModel, namespace string) *unstructured.Unstructured {
|
func environmentToUnstructured(model environmentResourceModel, namespace string) *unstructured.Unstructured {
|
||||||
|
spec := map[string]interface{}{
|
||||||
|
"version": model.Version.ValueInt64(),
|
||||||
|
"runtime": map[string]interface{}{
|
||||||
|
"image": model.Image.ValueString(),
|
||||||
|
},
|
||||||
|
"poolsize": model.PoolSize.ValueInt64(),
|
||||||
|
}
|
||||||
|
|
||||||
|
builderImage := model.BuilderImage.ValueString()
|
||||||
|
if builderImage != "" {
|
||||||
|
builder := map[string]interface{}{
|
||||||
|
"image": builderImage,
|
||||||
|
}
|
||||||
|
builderCmd := model.BuilderCommand.ValueString()
|
||||||
|
if builderCmd != "" {
|
||||||
|
builder["command"] = builderCmd
|
||||||
|
}
|
||||||
|
spec["builder"] = builder
|
||||||
|
}
|
||||||
|
|
||||||
return &unstructured.Unstructured{Object: map[string]interface{}{
|
return &unstructured.Unstructured{Object: map[string]interface{}{
|
||||||
"apiVersion": "fission.io/v1",
|
"apiVersion": "fission.io/v1",
|
||||||
"kind": "Environment",
|
"kind": "Environment",
|
||||||
@@ -223,13 +253,7 @@ func environmentToUnstructured(model environmentResourceModel, namespace string)
|
|||||||
"name": model.Name.ValueString(),
|
"name": model.Name.ValueString(),
|
||||||
"namespace": namespace,
|
"namespace": namespace,
|
||||||
},
|
},
|
||||||
"spec": map[string]interface{}{
|
"spec": spec,
|
||||||
"version": model.Version.ValueInt64(),
|
|
||||||
"runtime": map[string]interface{}{
|
|
||||||
"image": model.Image.ValueString(),
|
|
||||||
},
|
|
||||||
"poolsize": model.PoolSize.ValueInt64(),
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,6 +262,8 @@ func unstructuredToEnvironmentModel(environmentObject *unstructured.Unstructured
|
|||||||
imageValue, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "runtime", "image")
|
imageValue, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "runtime", "image")
|
||||||
versionValue, _, _ := unstructured.NestedInt64(environmentObject.Object, "spec", "version")
|
versionValue, _, _ := unstructured.NestedInt64(environmentObject.Object, "spec", "version")
|
||||||
poolsizeValue, _, _ := unstructured.NestedInt64(environmentObject.Object, "spec", "poolsize")
|
poolsizeValue, _, _ := unstructured.NestedInt64(environmentObject.Object, "spec", "poolsize")
|
||||||
|
builderImage, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "builder", "image")
|
||||||
|
builderCommand, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "builder", "command")
|
||||||
|
|
||||||
state := base
|
state := base
|
||||||
state.Name = types.StringValue(environmentObject.GetName())
|
state.Name = types.StringValue(environmentObject.GetName())
|
||||||
@@ -254,6 +280,12 @@ func unstructuredToEnvironmentModel(environmentObject *unstructured.Unstructured
|
|||||||
if poolsizeValue != 0 {
|
if poolsizeValue != 0 {
|
||||||
state.PoolSize = types.Int64Value(poolsizeValue)
|
state.PoolSize = types.Int64Value(poolsizeValue)
|
||||||
}
|
}
|
||||||
|
if builderImage != "" {
|
||||||
|
state.BuilderImage = types.StringValue(builderImage)
|
||||||
|
}
|
||||||
|
if builderCommand != "" {
|
||||||
|
state.BuilderCommand = types.StringValue(builderCommand)
|
||||||
|
}
|
||||||
|
|
||||||
return state
|
return state
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||||
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestEnvironmentToUnstructuredAndBack(t *testing.T) {
|
func TestEnvironmentToUnstructuredAndBack(t *testing.T) {
|
||||||
@@ -33,3 +34,51 @@ func TestEnvironmentToUnstructuredAndBack(t *testing.T) {
|
|||||||
t.Fatalf("unexpected poolsize: %d", state.PoolSize.ValueInt64())
|
t.Fatalf("unexpected poolsize: %d", state.PoolSize.ValueInt64())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEnvironmentToUnstructuredWithBuilder(t *testing.T) {
|
||||||
|
input := environmentResourceModel{
|
||||||
|
Name: types.StringValue("go-env"),
|
||||||
|
Image: types.StringValue("ghcr.io/fission/go-env"),
|
||||||
|
Version: types.Int64Value(3),
|
||||||
|
PoolSize: types.Int64Value(3),
|
||||||
|
BuilderImage: types.StringValue("ghcr.io/fission/go-builder"),
|
||||||
|
BuilderCommand: types.StringValue("build"),
|
||||||
|
}
|
||||||
|
|
||||||
|
obj := environmentToUnstructured(input, "default")
|
||||||
|
state := unstructuredToEnvironmentModel(obj, input)
|
||||||
|
|
||||||
|
if state.BuilderImage.ValueString() != "ghcr.io/fission/go-builder" {
|
||||||
|
t.Fatalf("unexpected builder_image: %q", state.BuilderImage.ValueString())
|
||||||
|
}
|
||||||
|
if state.BuilderCommand.ValueString() != "build" {
|
||||||
|
t.Fatalf("unexpected builder_command: %q", state.BuilderCommand.ValueString())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify the unstructured object has builder section
|
||||||
|
builderImage, found, _ := unstructured.NestedString(obj.Object, "spec", "builder", "image")
|
||||||
|
if !found || builderImage != "ghcr.io/fission/go-builder" {
|
||||||
|
t.Fatalf("builder.image not set correctly in unstructured: %q", builderImage)
|
||||||
|
}
|
||||||
|
builderCmd, found, _ := unstructured.NestedString(obj.Object, "spec", "builder", "command")
|
||||||
|
if !found || builderCmd != "build" {
|
||||||
|
t.Fatalf("builder.command not set correctly in unstructured: %q", builderCmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnvironmentToUnstructuredWithoutBuilder(t *testing.T) {
|
||||||
|
input := environmentResourceModel{
|
||||||
|
Name: types.StringValue("py-env"),
|
||||||
|
Image: types.StringValue("ghcr.io/fission/python-env"),
|
||||||
|
Version: types.Int64Value(3),
|
||||||
|
PoolSize: types.Int64Value(3),
|
||||||
|
}
|
||||||
|
|
||||||
|
obj := environmentToUnstructured(input, "default")
|
||||||
|
|
||||||
|
// Verify no builder section when builder_image is not set
|
||||||
|
_, found, _ := unstructured.NestedString(obj.Object, "spec", "builder", "image")
|
||||||
|
if found {
|
||||||
|
t.Fatalf("builder should not be present when builder_image is not set")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||||
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
|
||||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||||
|
|
||||||
@@ -26,13 +27,18 @@ type FunctionResource struct {
|
|||||||
|
|
||||||
// functionResourceModel описывает состояние terraform ресурса fission_function.
|
// functionResourceModel описывает состояние terraform ресурса fission_function.
|
||||||
type functionResourceModel struct {
|
type functionResourceModel struct {
|
||||||
ID types.String `tfsdk:"id"`
|
ID types.String `tfsdk:"id"`
|
||||||
Name types.String `tfsdk:"name"`
|
Name types.String `tfsdk:"name"`
|
||||||
Environment types.String `tfsdk:"environment"`
|
Environment types.String `tfsdk:"environment"`
|
||||||
PackageName types.String `tfsdk:"package_name"`
|
PackageName types.String `tfsdk:"package_name"`
|
||||||
Entrypoint types.String `tfsdk:"entrypoint"`
|
Entrypoint types.String `tfsdk:"entrypoint"`
|
||||||
Namespace types.String `tfsdk:"namespace"`
|
ExecutorType types.String `tfsdk:"executor_type"`
|
||||||
UID types.String `tfsdk:"uid"`
|
FunctionTimeout types.Int64 `tfsdk:"function_timeout"`
|
||||||
|
IdleTimeout types.Int64 `tfsdk:"idle_timeout"`
|
||||||
|
MinScale types.Int64 `tfsdk:"min_scale"`
|
||||||
|
MaxScale types.Int64 `tfsdk:"max_scale"`
|
||||||
|
Namespace types.String `tfsdk:"namespace"`
|
||||||
|
UID types.String `tfsdk:"uid"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFunctionResource создает инстанс ресурса функции.
|
// NewFunctionResource создает инстанс ресурса функции.
|
||||||
@@ -69,6 +75,28 @@ func (r *FunctionResource) Schema(_ context.Context, _ resource.SchemaRequest, r
|
|||||||
Required: true,
|
Required: true,
|
||||||
Description: "Имя точки входа в пакете (например main.main).",
|
Description: "Имя точки входа в пакете (например main.main).",
|
||||||
},
|
},
|
||||||
|
"executor_type": schema.StringAttribute{
|
||||||
|
Optional: true,
|
||||||
|
Computed: true,
|
||||||
|
Default: stringdefault.StaticString("poolmgr"),
|
||||||
|
Description: "Тип executor: poolmgr (default), newdeploy или container.",
|
||||||
|
},
|
||||||
|
"function_timeout": schema.Int64Attribute{
|
||||||
|
Optional: true,
|
||||||
|
Description: "Таймаут выполнения функции в секундах (Fission default: 60).",
|
||||||
|
},
|
||||||
|
"idle_timeout": schema.Int64Attribute{
|
||||||
|
Optional: true,
|
||||||
|
Description: "Время простоя до scale-to-zero в секундах (Fission default: 120).",
|
||||||
|
},
|
||||||
|
"min_scale": schema.Int64Attribute{
|
||||||
|
Optional: true,
|
||||||
|
Description: "Минимальное число реплик (для newdeploy/container).",
|
||||||
|
},
|
||||||
|
"max_scale": schema.Int64Attribute{
|
||||||
|
Optional: true,
|
||||||
|
Description: "Максимальное число реплик (для newdeploy/container).",
|
||||||
|
},
|
||||||
"namespace": schema.StringAttribute{
|
"namespace": schema.StringAttribute{
|
||||||
Optional: true,
|
Optional: true,
|
||||||
Computed: true,
|
Computed: true,
|
||||||
@@ -235,6 +263,46 @@ func (r *FunctionResource) ImportState(ctx context.Context, req resource.ImportS
|
|||||||
|
|
||||||
// functionToUnstructured преобразует Terraform model в Kubernetes CRD payload.
|
// functionToUnstructured преобразует Terraform model в Kubernetes CRD payload.
|
||||||
func functionToUnstructured(model functionResourceModel, namespace string) *unstructured.Unstructured {
|
func functionToUnstructured(model functionResourceModel, namespace string) *unstructured.Unstructured {
|
||||||
|
executorType := "poolmgr"
|
||||||
|
if !model.ExecutorType.IsNull() && !model.ExecutorType.IsUnknown() && model.ExecutorType.ValueString() != "" {
|
||||||
|
executorType = model.ExecutorType.ValueString()
|
||||||
|
}
|
||||||
|
|
||||||
|
executionStrategy := map[string]interface{}{
|
||||||
|
"ExecutorType": executorType,
|
||||||
|
}
|
||||||
|
if !model.MinScale.IsNull() && !model.MinScale.IsUnknown() {
|
||||||
|
executionStrategy["MinScale"] = model.MinScale.ValueInt64()
|
||||||
|
}
|
||||||
|
if !model.MaxScale.IsNull() && !model.MaxScale.IsUnknown() {
|
||||||
|
executionStrategy["MaxScale"] = model.MaxScale.ValueInt64()
|
||||||
|
}
|
||||||
|
|
||||||
|
spec := map[string]interface{}{
|
||||||
|
"environment": map[string]interface{}{
|
||||||
|
"name": model.Environment.ValueString(),
|
||||||
|
"namespace": namespace,
|
||||||
|
},
|
||||||
|
"InvokeStrategy": map[string]interface{}{
|
||||||
|
"ExecutionStrategy": executionStrategy,
|
||||||
|
"StrategyType": "execution",
|
||||||
|
},
|
||||||
|
"package": map[string]interface{}{
|
||||||
|
"packageref": map[string]interface{}{
|
||||||
|
"name": model.PackageName.ValueString(),
|
||||||
|
"namespace": namespace,
|
||||||
|
},
|
||||||
|
"functionName": model.Entrypoint.ValueString(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if !model.FunctionTimeout.IsNull() && !model.FunctionTimeout.IsUnknown() {
|
||||||
|
spec["functionTimeout"] = model.FunctionTimeout.ValueInt64()
|
||||||
|
}
|
||||||
|
if !model.IdleTimeout.IsNull() && !model.IdleTimeout.IsUnknown() {
|
||||||
|
spec["idletimeout"] = model.IdleTimeout.ValueInt64()
|
||||||
|
}
|
||||||
|
|
||||||
return &unstructured.Unstructured{Object: map[string]interface{}{
|
return &unstructured.Unstructured{Object: map[string]interface{}{
|
||||||
"apiVersion": "fission.io/v1",
|
"apiVersion": "fission.io/v1",
|
||||||
"kind": "Function",
|
"kind": "Function",
|
||||||
@@ -242,25 +310,7 @@ func functionToUnstructured(model functionResourceModel, namespace string) *unst
|
|||||||
"name": model.Name.ValueString(),
|
"name": model.Name.ValueString(),
|
||||||
"namespace": namespace,
|
"namespace": namespace,
|
||||||
},
|
},
|
||||||
"spec": map[string]interface{}{
|
"spec": spec,
|
||||||
"environment": map[string]interface{}{
|
|
||||||
"name": model.Environment.ValueString(),
|
|
||||||
"namespace": namespace,
|
|
||||||
},
|
|
||||||
"InvokeStrategy": map[string]interface{}{
|
|
||||||
"ExecutionStrategy": map[string]interface{}{
|
|
||||||
"ExecutorType": "poolmgr",
|
|
||||||
},
|
|
||||||
"StrategyType": "execution",
|
|
||||||
},
|
|
||||||
"package": map[string]interface{}{
|
|
||||||
"packageref": map[string]interface{}{
|
|
||||||
"name": model.PackageName.ValueString(),
|
|
||||||
"namespace": namespace,
|
|
||||||
},
|
|
||||||
"functionName": model.Entrypoint.ValueString(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,6 +319,11 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base
|
|||||||
environmentName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "environment", "name")
|
environmentName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "environment", "name")
|
||||||
packageName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "package", "packageref", "name")
|
packageName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "package", "packageref", "name")
|
||||||
entrypoint, _, _ := unstructured.NestedString(functionObject.Object, "spec", "package", "functionName")
|
entrypoint, _, _ := unstructured.NestedString(functionObject.Object, "spec", "package", "functionName")
|
||||||
|
executorType, _, _ := unstructured.NestedString(functionObject.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "ExecutorType")
|
||||||
|
functionTimeout, foundFT, _ := unstructured.NestedInt64(functionObject.Object, "spec", "functionTimeout")
|
||||||
|
idleTimeout, foundIT, _ := unstructured.NestedInt64(functionObject.Object, "spec", "idletimeout")
|
||||||
|
minScale, foundMin, _ := unstructured.NestedInt64(functionObject.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "MinScale")
|
||||||
|
maxScale, foundMax, _ := unstructured.NestedInt64(functionObject.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "MaxScale")
|
||||||
|
|
||||||
state := base
|
state := base
|
||||||
state.Name = types.StringValue(functionObject.GetName())
|
state.Name = types.StringValue(functionObject.GetName())
|
||||||
@@ -285,6 +340,21 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base
|
|||||||
if entrypoint != "" {
|
if entrypoint != "" {
|
||||||
state.Entrypoint = types.StringValue(entrypoint)
|
state.Entrypoint = types.StringValue(entrypoint)
|
||||||
}
|
}
|
||||||
|
if executorType != "" {
|
||||||
|
state.ExecutorType = types.StringValue(executorType)
|
||||||
|
}
|
||||||
|
if foundFT {
|
||||||
|
state.FunctionTimeout = types.Int64Value(functionTimeout)
|
||||||
|
}
|
||||||
|
if foundIT {
|
||||||
|
state.IdleTimeout = types.Int64Value(idleTimeout)
|
||||||
|
}
|
||||||
|
if foundMin {
|
||||||
|
state.MinScale = types.Int64Value(minScale)
|
||||||
|
}
|
||||||
|
if foundMax {
|
||||||
|
state.MaxScale = types.Int64Value(maxScale)
|
||||||
|
}
|
||||||
|
|
||||||
return state
|
return state
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ func TestFunctionToUnstructuredAndBack(t *testing.T) {
|
|||||||
if state.Entrypoint.ValueString() != "main.main" {
|
if state.Entrypoint.ValueString() != "main.main" {
|
||||||
t.Fatalf("unexpected entrypoint: %q", state.Entrypoint.ValueString())
|
t.Fatalf("unexpected entrypoint: %q", state.Entrypoint.ValueString())
|
||||||
}
|
}
|
||||||
|
if state.ExecutorType.ValueString() != "poolmgr" {
|
||||||
|
t.Fatalf("unexpected executor_type: %q", state.ExecutorType.ValueString())
|
||||||
|
}
|
||||||
|
|
||||||
invoke, found, err := unstructured.NestedMap(obj.Object, "spec", "InvokeStrategy")
|
invoke, found, err := unstructured.NestedMap(obj.Object, "spec", "InvokeStrategy")
|
||||||
if err != nil || !found || len(invoke) == 0 {
|
if err != nil || !found || len(invoke) == 0 {
|
||||||
@@ -38,6 +41,45 @@ func TestFunctionToUnstructuredAndBack(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestFunctionToUnstructuredWithTimeouts(t *testing.T) {
|
||||||
|
input := functionResourceModel{
|
||||||
|
Name: types.StringValue("fn-b"),
|
||||||
|
Environment: types.StringValue("env-a"),
|
||||||
|
PackageName: types.StringValue("pkg-a"),
|
||||||
|
Entrypoint: types.StringValue("main.main"),
|
||||||
|
ExecutorType: types.StringValue("newdeploy"),
|
||||||
|
FunctionTimeout: types.Int64Value(120),
|
||||||
|
IdleTimeout: types.Int64Value(60),
|
||||||
|
MinScale: types.Int64Value(1),
|
||||||
|
MaxScale: types.Int64Value(5),
|
||||||
|
}
|
||||||
|
|
||||||
|
obj := functionToUnstructured(input, "default")
|
||||||
|
state := unstructuredToFunctionModel(obj, input)
|
||||||
|
|
||||||
|
if state.ExecutorType.ValueString() != "newdeploy" {
|
||||||
|
t.Fatalf("unexpected executor_type: %q", state.ExecutorType.ValueString())
|
||||||
|
}
|
||||||
|
if state.FunctionTimeout.ValueInt64() != 120 {
|
||||||
|
t.Fatalf("unexpected function_timeout: %d", state.FunctionTimeout.ValueInt64())
|
||||||
|
}
|
||||||
|
if state.IdleTimeout.ValueInt64() != 60 {
|
||||||
|
t.Fatalf("unexpected idle_timeout: %d", state.IdleTimeout.ValueInt64())
|
||||||
|
}
|
||||||
|
if state.MinScale.ValueInt64() != 1 {
|
||||||
|
t.Fatalf("unexpected min_scale: %d", state.MinScale.ValueInt64())
|
||||||
|
}
|
||||||
|
if state.MaxScale.ValueInt64() != 5 {
|
||||||
|
t.Fatalf("unexpected max_scale: %d", state.MaxScale.ValueInt64())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify executor type in unstructured
|
||||||
|
et, _, _ := unstructured.NestedString(obj.Object, "spec", "InvokeStrategy", "ExecutionStrategy", "ExecutorType")
|
||||||
|
if et != "newdeploy" {
|
||||||
|
t.Fatalf("unexpected ExecutorType in unstructured: %q", et)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestValidateEntrypointAgainstPackageSourcePythonOK(t *testing.T) {
|
func TestValidateEntrypointAgainstPackageSourcePythonOK(t *testing.T) {
|
||||||
source := "def main():\n return 'ok'\n"
|
source := "def main():\n return 'ok'\n"
|
||||||
pkg := &unstructured.Unstructured{Object: map[string]interface{}{
|
pkg := &unstructured.Unstructured{Object: map[string]interface{}{
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
package resources
|
package resources
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
@@ -12,6 +15,7 @@ import (
|
|||||||
"github.com/hashicorp/terraform-plugin-framework/path"
|
"github.com/hashicorp/terraform-plugin-framework/path"
|
||||||
"github.com/hashicorp/terraform-plugin-framework/resource"
|
"github.com/hashicorp/terraform-plugin-framework/resource"
|
||||||
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
||||||
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
|
||||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||||
|
|
||||||
@@ -37,6 +41,7 @@ type packageResourceModel struct {
|
|||||||
CodePath types.String `tfsdk:"code_path"`
|
CodePath types.String `tfsdk:"code_path"`
|
||||||
CodeHash types.String `tfsdk:"code_hash"`
|
CodeHash types.String `tfsdk:"code_hash"`
|
||||||
BuildCmd types.String `tfsdk:"build_command"`
|
BuildCmd types.String `tfsdk:"build_command"`
|
||||||
|
DeployType types.String `tfsdk:"deploy_type"`
|
||||||
Namespace types.String `tfsdk:"namespace"`
|
Namespace types.String `tfsdk:"namespace"`
|
||||||
UID types.String `tfsdk:"uid"`
|
UID types.String `tfsdk:"uid"`
|
||||||
BuildStatus types.String `tfsdk:"build_status"`
|
BuildStatus types.String `tfsdk:"build_status"`
|
||||||
@@ -86,6 +91,12 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
|
|||||||
Optional: true,
|
Optional: true,
|
||||||
Description: "Команда сборки пакета в Fission.",
|
Description: "Команда сборки пакета в Fission.",
|
||||||
},
|
},
|
||||||
|
"deploy_type": schema.StringAttribute{
|
||||||
|
Optional: true,
|
||||||
|
Computed: true,
|
||||||
|
Default: stringdefault.StaticString("literal"),
|
||||||
|
Description: "Тип деплоя: 'literal' (default) — код в deployment.literal, 'source' — код в source.literal (для Go и языков с build step).",
|
||||||
|
},
|
||||||
"namespace": schema.StringAttribute{
|
"namespace": schema.StringAttribute{
|
||||||
Optional: true,
|
Optional: true,
|
||||||
Computed: true,
|
Computed: true,
|
||||||
@@ -137,7 +148,7 @@ func (r *PackageResource) ModifyPlan(ctx context.Context, req resource.ModifyPla
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
|
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
|
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
|
||||||
return
|
return
|
||||||
@@ -183,7 +194,7 @@ func (r *PackageResource) Create(ctx context.Context, req resource.CreateRequest
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
|
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
|
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
|
||||||
return
|
return
|
||||||
@@ -246,7 +257,7 @@ func (r *PackageResource) Update(ctx context.Context, req resource.UpdateRequest
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
|
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
|
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
|
||||||
return
|
return
|
||||||
@@ -329,7 +340,7 @@ func resolveNamespace(resourceNamespace types.String, providerNamespace string)
|
|||||||
return namespace
|
return namespace
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadPackageLiteral читает bytes для spec.deployment.literal.
|
// loadPackageLiteral читает bytes для literal deployment (один файл).
|
||||||
func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) {
|
func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) {
|
||||||
if sourceDir != "" {
|
if sourceDir != "" {
|
||||||
mainFilePath, err := resolveMainSourceFile(sourceDir)
|
mainFilePath, err := resolveMainSourceFile(sourceDir)
|
||||||
@@ -353,6 +364,57 @@ func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) {
|
|||||||
return literalBytes, nil
|
return literalBytes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// loadPackageSourceArchive создает zip-архив из source_dir для builder pipeline.
|
||||||
|
func loadPackageSourceArchive(sourceDir string) ([]byte, error) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
zipWriter := zip.NewWriter(&buf)
|
||||||
|
|
||||||
|
err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
relPath, err := filepath.Rel(sourceDir, path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("compute relative path for %q: %w", path, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
writer, err := zipWriter.Create(relPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create zip entry %q: %w", relPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("open file %q: %w", path, err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
_, err = io.Copy(writer, file)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("zip source_dir %q: %w", sourceDir, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := zipWriter.Close(); err != nil {
|
||||||
|
return nil, fmt.Errorf("close zip writer: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return buf.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadPackageContent загружает содержимое пакета в зависимости от deploy_type.
|
||||||
|
func loadPackageContent(sourceDir, codePath, deployType string) ([]byte, error) {
|
||||||
|
if deployType == "source" && sourceDir != "" {
|
||||||
|
return loadPackageSourceArchive(sourceDir)
|
||||||
|
}
|
||||||
|
return loadPackageLiteral(sourceDir, codePath)
|
||||||
|
}
|
||||||
|
|
||||||
// resolveMainSourceFile выбирает основной файл исходника из source_dir.
|
// resolveMainSourceFile выбирает основной файл исходника из source_dir.
|
||||||
func resolveMainSourceFile(sourceDir string) (string, error) {
|
func resolveMainSourceFile(sourceDir string) (string, error) {
|
||||||
candidates := []string{"main.py", "main.js", "main.go", "main.php", "main.rb", "main.pl"}
|
candidates := []string{"main.py", "main.js", "main.go", "main.php", "main.rb", "main.pl"}
|
||||||
@@ -371,6 +433,36 @@ func resolveMainSourceFile(sourceDir string) (string, error) {
|
|||||||
func packageToUnstructured(model packageResourceModel, namespace string, literalBytes []byte) *unstructured.Unstructured {
|
func packageToUnstructured(model packageResourceModel, namespace string, literalBytes []byte) *unstructured.Unstructured {
|
||||||
literalSource := base64.StdEncoding.EncodeToString(literalBytes)
|
literalSource := base64.StdEncoding.EncodeToString(literalBytes)
|
||||||
|
|
||||||
|
deployType := "literal"
|
||||||
|
if !model.DeployType.IsNull() && !model.DeployType.IsUnknown() && model.DeployType.ValueString() != "" {
|
||||||
|
deployType = model.DeployType.ValueString()
|
||||||
|
}
|
||||||
|
|
||||||
|
spec := map[string]interface{}{
|
||||||
|
"environment": map[string]interface{}{
|
||||||
|
"name": model.Environment.ValueString(),
|
||||||
|
"namespace": namespace,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if deployType == "source" {
|
||||||
|
// Source mode: код в spec.source (для builder pipeline — Go и др.)
|
||||||
|
spec["source"] = map[string]interface{}{
|
||||||
|
"type": "literal",
|
||||||
|
"literal": literalSource,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Literal/deployment mode: код в spec.deployment (Python, Node, PHP, Ruby, Perl)
|
||||||
|
spec["deployment"] = map[string]interface{}{
|
||||||
|
"type": "literal",
|
||||||
|
"literal": literalSource,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if buildCommand := model.BuildCmd.ValueString(); buildCommand != "" {
|
||||||
|
spec["buildcmd"] = buildCommand
|
||||||
|
}
|
||||||
|
|
||||||
object := map[string]interface{}{
|
object := map[string]interface{}{
|
||||||
"apiVersion": "fission.io/v1",
|
"apiVersion": "fission.io/v1",
|
||||||
"kind": "Package",
|
"kind": "Package",
|
||||||
@@ -378,21 +470,7 @@ func packageToUnstructured(model packageResourceModel, namespace string, literal
|
|||||||
"name": model.Name.ValueString(),
|
"name": model.Name.ValueString(),
|
||||||
"namespace": namespace,
|
"namespace": namespace,
|
||||||
},
|
},
|
||||||
"spec": map[string]interface{}{
|
"spec": spec,
|
||||||
"deployment": map[string]interface{}{
|
|
||||||
"type": "literal",
|
|
||||||
"literal": literalSource,
|
|
||||||
},
|
|
||||||
"environment": map[string]interface{}{
|
|
||||||
"name": model.Environment.ValueString(),
|
|
||||||
"namespace": namespace,
|
|
||||||
},
|
|
||||||
"source": map[string]interface{}{},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
if buildCommand := model.BuildCmd.ValueString(); buildCommand != "" {
|
|
||||||
_ = unstructured.SetNestedField(object, buildCommand, "spec", "buildcmd")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &unstructured.Unstructured{Object: object}
|
return &unstructured.Unstructured{Object: object}
|
||||||
@@ -405,6 +483,7 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
|
|||||||
buildStatus, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildstatus")
|
buildStatus, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildstatus")
|
||||||
buildLog, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildlog")
|
buildLog, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildlog")
|
||||||
deploymentLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "deployment", "literal")
|
deploymentLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "deployment", "literal")
|
||||||
|
sourceLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "source", "literal")
|
||||||
|
|
||||||
state := packageResourceModel{
|
state := packageResourceModel{
|
||||||
ID: types.StringValue(fmt.Sprintf("%s/%s", packageObject.GetNamespace(), packageObject.GetName())),
|
ID: types.StringValue(fmt.Sprintf("%s/%s", packageObject.GetNamespace(), packageObject.GetName())),
|
||||||
@@ -414,6 +493,7 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
|
|||||||
CodePath: base.CodePath,
|
CodePath: base.CodePath,
|
||||||
CodeHash: base.CodeHash,
|
CodeHash: base.CodeHash,
|
||||||
BuildCmd: base.BuildCmd,
|
BuildCmd: base.BuildCmd,
|
||||||
|
DeployType: base.DeployType,
|
||||||
Namespace: types.StringValue(packageObject.GetNamespace()),
|
Namespace: types.StringValue(packageObject.GetNamespace()),
|
||||||
UID: types.StringValue(string(packageObject.GetUID())),
|
UID: types.StringValue(string(packageObject.GetUID())),
|
||||||
BuildStatus: types.StringNull(),
|
BuildStatus: types.StringNull(),
|
||||||
@@ -433,8 +513,13 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
|
|||||||
state.BuildLog = types.StringValue(buildLog)
|
state.BuildLog = types.StringValue(buildLog)
|
||||||
}
|
}
|
||||||
|
|
||||||
if deploymentLiteral != "" {
|
// Определить hash из содержимого (deployment или source)
|
||||||
if literalBytes, err := base64.StdEncoding.DecodeString(deploymentLiteral); err == nil {
|
literalForHash := deploymentLiteral
|
||||||
|
if literalForHash == "" {
|
||||||
|
literalForHash = sourceLiteral
|
||||||
|
}
|
||||||
|
if literalForHash != "" {
|
||||||
|
if literalBytes, err := base64.StdEncoding.DecodeString(literalForHash); err == nil {
|
||||||
state.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
|
state.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package resources
|
package resources
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
@@ -104,6 +106,47 @@ func TestPackageToUnstructured(t *testing.T) {
|
|||||||
if string(decoded) != "print('hi')" {
|
if string(decoded) != "print('hi')" {
|
||||||
t.Fatalf("unexpected decoded literal: %q", string(decoded))
|
t.Fatalf("unexpected decoded literal: %q", string(decoded))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Verify no empty source map is generated
|
||||||
|
_, sourceFound, _ := unstructured.NestedMap(obj.Object, "spec", "source")
|
||||||
|
if sourceFound {
|
||||||
|
t.Fatalf("empty source should not be present in deployment mode")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPackageToUnstructuredSourceMode(t *testing.T) {
|
||||||
|
input := packageResourceModel{
|
||||||
|
Name: types.StringValue("pkg-go"),
|
||||||
|
Environment: types.StringValue("go-env"),
|
||||||
|
DeployType: types.StringValue("source"),
|
||||||
|
BuildCmd: types.StringValue("build"),
|
||||||
|
}
|
||||||
|
|
||||||
|
obj := packageToUnstructured(input, "default", []byte("zip-content"))
|
||||||
|
sourceLiteral, found, err := unstructured.NestedString(obj.Object, "spec", "source", "literal")
|
||||||
|
if err != nil || !found {
|
||||||
|
t.Fatalf("source.literal not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
decoded, err := base64.StdEncoding.DecodeString(sourceLiteral)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode source literal: %v", err)
|
||||||
|
}
|
||||||
|
if string(decoded) != "zip-content" {
|
||||||
|
t.Fatalf("unexpected source literal: %q", string(decoded))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify no deployment section in source mode
|
||||||
|
_, deployFound, _ := unstructured.NestedMap(obj.Object, "spec", "deployment")
|
||||||
|
if deployFound {
|
||||||
|
t.Fatalf("deployment should not be present in source mode")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify buildcmd is set
|
||||||
|
buildCmd, _, _ := unstructured.NestedString(obj.Object, "spec", "buildcmd")
|
||||||
|
if buildCmd != "build" {
|
||||||
|
t.Fatalf("unexpected buildcmd: %q", buildCmd)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestResolveNamespace(t *testing.T) {
|
func TestResolveNamespace(t *testing.T) {
|
||||||
@@ -179,3 +222,39 @@ func TestHTTPTriggerRoundTrip(t *testing.T) {
|
|||||||
t.Fatalf("unexpected url: %q", state.URL.ValueString())
|
t.Fatalf("unexpected url: %q", state.URL.ValueString())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoadPackageSourceArchive(t *testing.T) {
|
||||||
|
tempDir := t.TempDir()
|
||||||
|
// Create multiple files to zip
|
||||||
|
files := map[string]string{
|
||||||
|
"main.go": "package main\n\nimport \"net/http\"\n\nfunc Handler(w http.ResponseWriter, r *http.Request) {}\n",
|
||||||
|
"go.mod": "module example.com/fn\n\ngo 1.21\n",
|
||||||
|
}
|
||||||
|
for name, content := range files {
|
||||||
|
if err := os.WriteFile(filepath.Join(tempDir, name), []byte(content), 0o600); err != nil {
|
||||||
|
t.Fatalf("write %s: %v", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
zipBytes, err := loadPackageSourceArchive(tempDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("loadPackageSourceArchive error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify it's a valid zip
|
||||||
|
reader, err := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("invalid zip: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
foundFiles := map[string]bool{}
|
||||||
|
for _, f := range reader.File {
|
||||||
|
foundFiles[f.Name] = true
|
||||||
|
}
|
||||||
|
if !foundFiles["main.go"] {
|
||||||
|
t.Fatalf("main.go not found in zip")
|
||||||
|
}
|
||||||
|
if !foundFiles["go.mod"] {
|
||||||
|
t.Fatalf("go.mod not found in zip")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user