Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
50ba09e1b6 | ||
|
|
903610bf71 | ||
|
|
0a1708e682 | ||
|
|
579bf97e17 | ||
|
|
c40fc47025 |
+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,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,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" {
|
||||||
|
|||||||
Reference in New Issue
Block a user