Merge feat/console-auth: auth через deck API, login overlay, logout
This commit is contained in:
@@ -0,0 +1,14 @@
|
|||||||
|
# Правила
|
||||||
|
|
||||||
|
## ⛔ ОТВЕЧАТЬ КРАТКО — АБСОЛЮТНОЕ ПРАВИЛО
|
||||||
|
- Вопрос → короткий ответ → СТОП. Не рассуждать, не исследовать без команды.
|
||||||
|
- НЕ делать ничего "попутно" без явной просьбы. Сделал — стоп — ждёшь команды.
|
||||||
|
|
||||||
|
> Подробные правила: [`.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 'КОМАНДА'
|
||||||
|
```
|
||||||
@@ -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` и др.) — только после явного подтверждения с указанием конкретных объектов
|
||||||
|
- Отвечать кратко, без вступлений, извинений, благодарностей и прочей воды
|
||||||
@@ -8,6 +8,10 @@ bin/
|
|||||||
*.test
|
*.test
|
||||||
*.out
|
*.out
|
||||||
|
|
||||||
|
# Compiled function binaries (generated, not versioned)
|
||||||
|
examples/*/dist/
|
||||||
|
|
||||||
# Provider binaries
|
# Provider binaries
|
||||||
terraform-provider-fission
|
terraform-provider-fission
|
||||||
terraform-provider-fission_*
|
terraform-provider-fission_*
|
||||||
|
console/fission-console
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FROM golang:1.26-alpine AS builder
|
||||||
|
WORKDIR /build
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o fission-console .
|
||||||
|
|
||||||
|
FROM alpine:3.20
|
||||||
|
RUN apk add --no-cache ca-certificates
|
||||||
|
COPY --from=builder /build/fission-console /fission-console
|
||||||
|
EXPOSE 8090
|
||||||
|
ENTRYPOINT ["/fission-console"]
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: ServiceAccount
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
---
|
||||||
|
apiVersion: rbac.authorization.k8s.io/v1
|
||||||
|
kind: ClusterRole
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
rules:
|
||||||
|
- apiGroups: ["fission.io"]
|
||||||
|
resources: ["environments", "packages", "functions", "httptriggers", "timetriggers"]
|
||||||
|
verbs: ["get", "list", "create", "update", "patch", "delete"]
|
||||||
|
---
|
||||||
|
apiVersion: rbac.authorization.k8s.io/v1
|
||||||
|
kind: ClusterRoleBinding
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
subjects:
|
||||||
|
- kind: ServiceAccount
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
roleRef:
|
||||||
|
kind: ClusterRole
|
||||||
|
name: fission-console
|
||||||
|
apiGroup: rbac.authorization.k8s.io
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
labels:
|
||||||
|
app: fission-console
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: fission-console
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: fission-console
|
||||||
|
spec:
|
||||||
|
serviceAccountName: fission-console
|
||||||
|
containers:
|
||||||
|
- name: console
|
||||||
|
image: naeel/fission-console:v0.3.4
|
||||||
|
ports:
|
||||||
|
- containerPort: 8090
|
||||||
|
env:
|
||||||
|
- name: FISSION_NAMESPACE
|
||||||
|
value: "default"
|
||||||
|
- name: FISSION_ROUTER_URL
|
||||||
|
value: "http://router.fission.svc.cluster.local"
|
||||||
|
- name: PORT
|
||||||
|
value: "8090"
|
||||||
|
- name: FISSION_HTTP_TIMEOUT
|
||||||
|
value: "30s"
|
||||||
|
- name: FISSION_INVOKE_TIMEOUT
|
||||||
|
value: "20s"
|
||||||
|
- name: FISSION_AUTH_USERNAME
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: router
|
||||||
|
key: username
|
||||||
|
- name: FISSION_AUTH_PASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: router
|
||||||
|
key: password
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: 8090
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 20
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: 8090
|
||||||
|
initialDelaySeconds: 3
|
||||||
|
periodSeconds: 10
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 20m
|
||||||
|
memory: 32Mi
|
||||||
|
limits:
|
||||||
|
cpu: 200m
|
||||||
|
memory: 128Mi
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
app: fission-console
|
||||||
|
ports:
|
||||||
|
- port: 8090
|
||||||
|
targetPort: 8090
|
||||||
|
---
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: Ingress
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
annotations:
|
||||||
|
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
|
||||||
|
cert-manager.io/cluster-issuer: "letsencrypt-prod"
|
||||||
|
spec:
|
||||||
|
ingressClassName: nginx
|
||||||
|
rules:
|
||||||
|
- host: fission.kube5s.ru
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
- path: /console
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: fission-console
|
||||||
|
port:
|
||||||
|
number: 8090
|
||||||
|
tls:
|
||||||
|
- hosts:
|
||||||
|
- fission.kube5s.ru
|
||||||
|
secretName: fission-tls
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
module fission-console
|
||||||
|
|
||||||
|
go 1.25.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
k8s.io/apimachinery v0.34.1
|
||||||
|
k8s.io/client-go v0.34.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
|
||||||
|
github.com/go-logr/logr v1.4.3 // indirect
|
||||||
|
github.com/go-openapi/jsonpointer v0.21.0 // indirect
|
||||||
|
github.com/go-openapi/jsonreference v0.20.2 // indirect
|
||||||
|
github.com/go-openapi/swag v0.23.0 // indirect
|
||||||
|
github.com/gogo/protobuf v1.3.2 // indirect
|
||||||
|
github.com/google/gnostic-models v0.7.0 // indirect
|
||||||
|
github.com/josharian/intern v1.0.0 // indirect
|
||||||
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
|
github.com/mailru/easyjson v0.7.7 // indirect
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
|
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
|
github.com/spf13/pflag v1.0.9 // indirect
|
||||||
|
github.com/x448/float16 v0.8.4 // indirect
|
||||||
|
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||||
|
golang.org/x/net v0.47.0 // indirect
|
||||||
|
golang.org/x/oauth2 v0.30.0 // indirect
|
||||||
|
golang.org/x/sys v0.38.0 // indirect
|
||||||
|
golang.org/x/term v0.37.0 // indirect
|
||||||
|
golang.org/x/text v0.31.0 // indirect
|
||||||
|
golang.org/x/time v0.9.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.5 // indirect
|
||||||
|
gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
|
||||||
|
gopkg.in/inf.v0 v0.9.1 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
k8s.io/klog/v2 v2.130.1 // indirect
|
||||||
|
k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 // indirect
|
||||||
|
k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 // indirect
|
||||||
|
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
|
||||||
|
sigs.k8s.io/randfill v1.0.0 // indirect
|
||||||
|
sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect
|
||||||
|
sigs.k8s.io/yaml v1.6.0 // indirect
|
||||||
|
)
|
||||||
+156
@@ -0,0 +1,156 @@
|
|||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/emicklei/go-restful/v3 v3.12.2 h1:DhwDP0vY3k8ZzE0RunuJy8GhNpPL6zqLkDf9B/a0/xU=
|
||||||
|
github.com/emicklei/go-restful/v3 v3.12.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
|
||||||
|
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
|
||||||
|
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
|
||||||
|
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||||
|
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs=
|
||||||
|
github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ=
|
||||||
|
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
|
||||||
|
github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE=
|
||||||
|
github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=
|
||||||
|
github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
|
||||||
|
github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE=
|
||||||
|
github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ=
|
||||||
|
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
|
||||||
|
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
|
||||||
|
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||||
|
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||||
|
github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo=
|
||||||
|
github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgYQBbFN4U4JNXUNYpxael3UzMyo=
|
||||||
|
github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||||
|
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||||
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
|
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||||
|
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||||
|
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||||
|
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
|
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=
|
||||||
|
github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||||
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||||
|
github.com/onsi/ginkgo/v2 v2.21.0 h1:7rg/4f3rB88pb5obDgNZrNHrQ4e6WpjonchcpuBRnZM=
|
||||||
|
github.com/onsi/ginkgo/v2 v2.21.0/go.mod h1:7Du3c42kxCUegi0IImZ1wUQzMBVecgIHjR1C+NkhLQo=
|
||||||
|
github.com/onsi/gomega v1.35.1 h1:Cwbd75ZBPxFSuZ6T+rN/WCb/gOc6YgFBXLlZLhC7Ds4=
|
||||||
|
github.com/onsi/gomega v1.35.1/go.mod h1:PvZbdDc8J6XJEpDK4HCuRBm8a6Fzp9/DmhC9C7yFlog=
|
||||||
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||||
|
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||||
|
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||||
|
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||||
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||||
|
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||||
|
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
|
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
|
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||||
|
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||||
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
|
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
|
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||||
|
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||||
|
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||||
|
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||||
|
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||||
|
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
|
||||||
|
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||||
|
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||||
|
golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY=
|
||||||
|
golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||||
|
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||||
|
golang.org/x/tools v0.38.0 h1:Hx2Xv8hISq8Lm16jvBZ2VQf+RLmbd7wVUsALibYI/IQ=
|
||||||
|
golang.org/x/tools v0.38.0/go.mod h1:yEsQ/d/YK8cjh0L6rZlY8tgtlKiBNTL14pGDJPJpYQs=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
|
||||||
|
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSPG+6V4=
|
||||||
|
gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M=
|
||||||
|
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
|
||||||
|
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
k8s.io/api v0.34.1 h1:jC+153630BMdlFukegoEL8E/yT7aLyQkIVuwhmwDgJM=
|
||||||
|
k8s.io/api v0.34.1/go.mod h1:SB80FxFtXn5/gwzCoN6QCtPD7Vbu5w2n1S0J5gFfTYk=
|
||||||
|
k8s.io/apimachinery v0.34.1 h1:dTlxFls/eikpJxmAC7MVE8oOeP1zryV7iRyIjB0gky4=
|
||||||
|
k8s.io/apimachinery v0.34.1/go.mod h1:/GwIlEcWuTX9zKIg2mbw0LRFIsXwrfoVxn+ef0X13lw=
|
||||||
|
k8s.io/client-go v0.34.1 h1:ZUPJKgXsnKwVwmKKdPfw4tB58+7/Ik3CrjOEhsiZ7mY=
|
||||||
|
k8s.io/client-go v0.34.1/go.mod h1:kA8v0FP+tk6sZA0yKLRG67LWjqufAoSHA2xVGKw9Of8=
|
||||||
|
k8s.io/klog/v2 v2.130.1 h1:n9Xl7H1Xvksem4KFG4PYbdQCQxqc/tTUyrgXaOhHSzk=
|
||||||
|
k8s.io/klog/v2 v2.130.1/go.mod h1:3Jpz1GvMt720eyJH1ckRHK1EDfpxISzJ7I9OYgaDtPE=
|
||||||
|
k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 h1:Y3gxNAuB0OBLImH611+UDZcmKS3g6CthxToOb37KgwE=
|
||||||
|
k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912/go.mod h1:kdmbQkyfwUagLfXIad1y2TdrjPFWp2Q89B3qkRwf/pQ=
|
||||||
|
k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 h1:SjGebBtkBqHFOli+05xYbK8YF1Dzkbzn+gDM4X9T4Ck=
|
||||||
|
k8s.io/utils v0.0.0-20251002143259-bc988d571ff4/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
|
||||||
|
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg=
|
||||||
|
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
|
||||||
|
sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU=
|
||||||
|
sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY=
|
||||||
|
sigs.k8s.io/structured-merge-diff/v6 v6.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/fXCbTiQEco=
|
||||||
|
sigs.k8s.io/structured-merge-diff/v6 v6.3.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE=
|
||||||
|
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
|
||||||
|
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
|
||||||
+1102
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,284 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||||
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||||
|
"k8s.io/apimachinery/pkg/runtime"
|
||||||
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
||||||
|
dynamicfake "k8s.io/client-go/dynamic/fake"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newTestServer(objs ...runtime.Object) *server {
|
||||||
|
listKinds := map[schema.GroupVersionResource]string{
|
||||||
|
environmentGVR: "EnvironmentList",
|
||||||
|
packageGVR: "PackageList",
|
||||||
|
functionGVR: "FunctionList",
|
||||||
|
httpTrigGVR: "HTTPTriggerList",
|
||||||
|
timeTrigGVR: "TimeTriggerList",
|
||||||
|
}
|
||||||
|
dyn := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), listKinds, objs...)
|
||||||
|
return &server{dyn: dyn, ns: "default", routerURL: "http://example.invalid", http: &http.Client{}, saTokenPath: ""}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeMethods(t *testing.T) {
|
||||||
|
got := normalizeMethods([]string{"get", " POST ", "get", ""})
|
||||||
|
if len(got) != 2 || got[0] != "GET" || got[1] != "POST" {
|
||||||
|
t.Fatalf("unexpected methods: %#v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
fallback := normalizeMethods([]string{"", " "})
|
||||||
|
if len(fallback) != 1 || fallback[0] != "GET" {
|
||||||
|
t.Fatalf("expected default GET, got %#v", fallback)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateFunctionValidation(t *testing.T) {
|
||||||
|
s := newTestServer()
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/functions", strings.NewReader(`{"name":""}`))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
|
||||||
|
s.handleCreateFunction(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusBadRequest {
|
||||||
|
t.Fatalf("expected 400, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateFunctionSuccessAndGetDetails(t *testing.T) {
|
||||||
|
env := &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Environment",
|
||||||
|
"metadata": map[string]any{
|
||||||
|
"name": "python",
|
||||||
|
"namespace": "default",
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
s := newTestServer(env)
|
||||||
|
|
||||||
|
body := `{"name":"t-fn","environment":"python","code":"def main(ctx):\n return {\"ok\": True}","entrypoint":"main.main","route":"/t-fn","methods":["get"]}`
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/api/functions", strings.NewReader(body))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
s.handleCreateFunction(rec, req)
|
||||||
|
if rec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("expected 201, got %d: %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
pkg, err := s.dyn.Resource(packageGVR).Namespace("default").Get(ctx, "t-fn-pkg", metav1.GetOptions{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("package not created: %v", err)
|
||||||
|
}
|
||||||
|
literal, _, _ := unstructured.NestedString(pkg.Object, "spec", "deployment", "literal")
|
||||||
|
decoded, err := base64.StdEncoding.DecodeString(literal)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode literal: %v", err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(decoded), "def main") {
|
||||||
|
t.Fatalf("unexpected package code: %q", string(decoded))
|
||||||
|
}
|
||||||
|
|
||||||
|
getReq := httptest.NewRequest(http.MethodGet, "/api/functions/t-fn", nil)
|
||||||
|
getRec := httptest.NewRecorder()
|
||||||
|
s.handleGetFunction(getRec, getReq, "t-fn")
|
||||||
|
if getRec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", getRec.Code, getRec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(getRec.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("decode get response: %v", err)
|
||||||
|
}
|
||||||
|
if out["name"] != "t-fn" {
|
||||||
|
t.Fatalf("unexpected name: %#v", out["name"])
|
||||||
|
}
|
||||||
|
if out["environment"] != "python" {
|
||||||
|
t.Fatalf("unexpected environment: %#v", out["environment"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateFunctionCode(t *testing.T) {
|
||||||
|
env := &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Environment",
|
||||||
|
"metadata": map[string]any{"name": "python", "namespace": "default"},
|
||||||
|
}}
|
||||||
|
s := newTestServer(env)
|
||||||
|
|
||||||
|
createReq := httptest.NewRequest(http.MethodPost, "/api/functions", strings.NewReader(`{"name":"upd-fn","environment":"python","code":"old","entrypoint":"main.main"}`))
|
||||||
|
createRec := httptest.NewRecorder()
|
||||||
|
s.handleCreateFunction(createRec, createReq)
|
||||||
|
if createRec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("create failed: %d %s", createRec.Code, createRec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
updReq := httptest.NewRequest(http.MethodPut, "/api/functions/upd-fn/code", bytes.NewBufferString(`{"code":"new-code"}`))
|
||||||
|
updRec := httptest.NewRecorder()
|
||||||
|
s.handleUpdateFunctionCode(updRec, updReq, "upd-fn")
|
||||||
|
if updRec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("update failed: %d %s", updRec.Code, updRec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
pkg, err := s.dyn.Resource(packageGVR).Namespace("default").Get(ctx, "upd-fn-pkg", metav1.GetOptions{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("get package: %v", err)
|
||||||
|
}
|
||||||
|
literal, _, _ := unstructured.NestedString(pkg.Object, "spec", "deployment", "literal")
|
||||||
|
decoded, err := base64.StdEncoding.DecodeString(literal)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode literal: %v", err)
|
||||||
|
}
|
||||||
|
if string(decoded) != "new-code" {
|
||||||
|
t.Fatalf("expected new-code, got %q", string(decoded))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFunctionUsesSourceLiteralWhenDeploymentLiteralMissing(t *testing.T) {
|
||||||
|
env := &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Environment",
|
||||||
|
"metadata": map[string]any{"name": "go-acc", "namespace": "default"},
|
||||||
|
}}
|
||||||
|
|
||||||
|
s := newTestServer(env)
|
||||||
|
|
||||||
|
pkg := &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Package",
|
||||||
|
"metadata": map[string]any{
|
||||||
|
"name": "fn-go-acc-pkg",
|
||||||
|
"namespace": "default",
|
||||||
|
},
|
||||||
|
"spec": map[string]any{
|
||||||
|
"source": map[string]any{
|
||||||
|
"literal": base64.StdEncoding.EncodeToString([]byte("package main\n\nfunc Handler() {}\n")),
|
||||||
|
},
|
||||||
|
"deployment": map[string]any{
|
||||||
|
"type": "url",
|
||||||
|
"url": "http://storagesvc.fission/v1/archive?id=dummy",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
|
||||||
|
fn := &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Function",
|
||||||
|
"metadata": map[string]any{
|
||||||
|
"name": "fn-go-acc",
|
||||||
|
"namespace": "default",
|
||||||
|
},
|
||||||
|
"spec": map[string]any{
|
||||||
|
"environment": map[string]any{"name": "go-acc", "namespace": "default"},
|
||||||
|
"package": map[string]any{
|
||||||
|
"functionName": "Handler",
|
||||||
|
"packageref": map[string]any{
|
||||||
|
"name": "fn-go-acc-pkg",
|
||||||
|
"namespace": "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
|
||||||
|
if _, err := s.dyn.Resource(packageGVR).Namespace("default").Create(context.Background(), pkg, metav1.CreateOptions{}); err != nil {
|
||||||
|
t.Fatalf("create package: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := s.dyn.Resource(functionGVR).Namespace("default").Create(context.Background(), fn, metav1.CreateOptions{}); err != nil {
|
||||||
|
t.Fatalf("create function: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
getReq := httptest.NewRequest(http.MethodGet, "/api/functions/fn-go-acc", nil)
|
||||||
|
getRec := httptest.NewRecorder()
|
||||||
|
s.handleGetFunction(getRec, getReq, "fn-go-acc")
|
||||||
|
if getRec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", getRec.Code, getRec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(getRec.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("decode get response: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, _ := out["code"].(string)
|
||||||
|
if !strings.Contains(code, "func Handler") {
|
||||||
|
t.Fatalf("expected source code from spec.source.literal, got %q", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeFunctionWithJWTAuth(t *testing.T) {
|
||||||
|
// Mock router: /auth/login returns JWT, /inv-fn returns hello
|
||||||
|
var gotAuth string
|
||||||
|
mockRouter := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.URL.Path == "/auth/login" && r.Method == http.MethodPost {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"accesstoken":"fake-jwt-token-xyz","tokentype":"Bearer"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
gotAuth = r.Header.Get("Authorization")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte(`{"hello":"world"}`))
|
||||||
|
}))
|
||||||
|
defer mockRouter.Close()
|
||||||
|
|
||||||
|
env := &unstructured.Unstructured{Object: map[string]any{
|
||||||
|
"apiVersion": "fission.io/v1",
|
||||||
|
"kind": "Environment",
|
||||||
|
"metadata": map[string]any{"name": "python", "namespace": "default"},
|
||||||
|
}}
|
||||||
|
|
||||||
|
listKinds := map[schema.GroupVersionResource]string{
|
||||||
|
environmentGVR: "EnvironmentList",
|
||||||
|
packageGVR: "PackageList",
|
||||||
|
functionGVR: "FunctionList",
|
||||||
|
httpTrigGVR: "HTTPTriggerList",
|
||||||
|
timeTrigGVR: "TimeTriggerList",
|
||||||
|
}
|
||||||
|
dyn := dynamicfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), listKinds, env)
|
||||||
|
s := &server{
|
||||||
|
dyn: dyn,
|
||||||
|
ns: "default",
|
||||||
|
routerURL: mockRouter.URL,
|
||||||
|
http: mockRouter.Client(),
|
||||||
|
authUser: "admin",
|
||||||
|
authPass: "pass",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create function first
|
||||||
|
createBody := `{"name":"inv-fn","environment":"python","code":"print(1)","route":"/inv-fn","methods":["GET"]}`
|
||||||
|
createRec := httptest.NewRecorder()
|
||||||
|
s.handleCreateFunction(createRec, httptest.NewRequest(http.MethodPost, "/api/functions", strings.NewReader(createBody)))
|
||||||
|
if createRec.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("create: %d %s", createRec.Code, createRec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invoke
|
||||||
|
invokeRec := httptest.NewRecorder()
|
||||||
|
s.handleInvokeFunction(invokeRec, httptest.NewRequest(http.MethodPost, "/api/functions/inv-fn/invoke", strings.NewReader(`{}`)), "inv-fn")
|
||||||
|
if invokeRec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("invoke: %d %s", invokeRec.Code, invokeRec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify JWT was obtained via login and sent
|
||||||
|
if gotAuth != "Bearer fake-jwt-token-xyz" {
|
||||||
|
t.Fatalf("expected 'Bearer fake-jwt-token-xyz', got %q", gotAuth)
|
||||||
|
}
|
||||||
|
|
||||||
|
var out map[string]any
|
||||||
|
if err := json.Unmarshal(invokeRec.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if out["status"] != float64(200) {
|
||||||
|
t.Fatalf("expected status 200, got %v", out["status"])
|
||||||
|
}
|
||||||
|
if !strings.Contains(out["response_raw"].(string), "hello") {
|
||||||
|
t.Fatalf("unexpected response: %v", out["response_raw"])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package ui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed index.html
|
||||||
|
var content embed.FS
|
||||||
|
|
||||||
|
func Handler() http.Handler {
|
||||||
|
return http.FileServer(http.FS(content))
|
||||||
|
}
|
||||||
@@ -0,0 +1,807 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<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">
|
||||||
|
<script>
|
||||||
|
if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
|
||||||
|
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg-page: #001120;
|
||||||
|
--bg-surface: #001929;
|
||||||
|
--bg-navbar: #001c34;
|
||||||
|
--border: #0b2d50;
|
||||||
|
--accent: #1a7fd4;
|
||||||
|
--text-primary: #e2ecf6;
|
||||||
|
--text-secondary: #6b8eaa;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
|
||||||
|
background: var(--bg-page);
|
||||||
|
color: var(--text-primary);
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar {
|
||||||
|
height: 56px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0 20px;
|
||||||
|
background: var(--bg-navbar);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.title {
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: .3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-mark {
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: linear-gradient(135deg, #009dff 0%, #0055d4 100%);
|
||||||
|
color: #fff;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: .02em;
|
||||||
|
box-shadow: 0 6px 18px rgba(0, 125, 255, .35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-text {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
line-height: 1.08;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-text .nubes {
|
||||||
|
font-size: 12px;
|
||||||
|
letter-spacing: .22em;
|
||||||
|
font-weight: 800;
|
||||||
|
color: #8bc7ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.brand-text .product {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: .04em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
background: var(--accent);
|
||||||
|
color: #fff;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: .6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn.danger {
|
||||||
|
background: #b43232;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn.ghost {
|
||||||
|
background: #0c2b49;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wrap {
|
||||||
|
max-width: 1100px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: var(--bg-surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.k {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 12px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: .06em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.v {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 700;
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.box {
|
||||||
|
background: var(--bg-surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 14px;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: 13px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
th, td {
|
||||||
|
text-align: left;
|
||||||
|
padding: 8px;
|
||||||
|
border-bottom: 1px solid #0b2a48;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mono {
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status {
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 9px 10px;
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
background: #0c2b49;
|
||||||
|
border: 1px solid #1d486d;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status.ok {
|
||||||
|
background: #103625;
|
||||||
|
border-color: #236843;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status.err {
|
||||||
|
background: #411d1d;
|
||||||
|
border-color: #7a2f2f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 7px;
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 1px solid #1d486d;
|
||||||
|
background: #0c2b49;
|
||||||
|
font-size: 11px;
|
||||||
|
margin-right: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0,0,0,.45);
|
||||||
|
display: none;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal.open { display: flex; }
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
width: min(820px, 100%);
|
||||||
|
max-height: 90vh;
|
||||||
|
overflow: auto;
|
||||||
|
background: var(--bg-surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel h3 {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 180px;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
input, select, textarea {
|
||||||
|
width: 100%;
|
||||||
|
border: 1px solid #1d486d;
|
||||||
|
background: #03192c;
|
||||||
|
color: var(--text-primary);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
min-height: 220px;
|
||||||
|
resize: vertical;
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
justify-content: flex-end;
|
||||||
|
margin-top: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nowrap {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<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="brand">
|
||||||
|
<div class="brand-mark">N</div>
|
||||||
|
<div class="brand-text">
|
||||||
|
<div class="nubes">NUBES</div>
|
||||||
|
<div class="product">FISSION CONSOLE</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row" style="margin:0;">
|
||||||
|
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
|
||||||
|
<button class="btn" onclick="openCreate()">+ Создать функцию</button>
|
||||||
|
<button class="btn ghost" onclick="doLogout()" style="margin-left:8px;">Выход</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="wrap">
|
||||||
|
<div class="grid">
|
||||||
|
<div class="card"><div class="k">Окружения</div><div id="env-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">Функции</div><div id="fn-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">Тайм-триггеры</div><div id="time-count" class="v">-</div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="box">
|
||||||
|
<div class="toolbar">
|
||||||
|
<div style="font-weight:600;">Функции</div>
|
||||||
|
<div class="hint">Actions: view, edit code, invoke, delete</div>
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Имя</th><th>Окружение</th><th>Пакет</th><th>Маршрут</th><th>Методы</th><th class="nowrap">Действия</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="fn-rows"></tbody>
|
||||||
|
</table>
|
||||||
|
<div id="status" class="status"></div>
|
||||||
|
<div class="hint">Namespace: default. CRUD происходит напрямую через CRD Fission.</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="create-modal" class="modal">
|
||||||
|
<div class="panel">
|
||||||
|
<h3>Создать функцию</h3>
|
||||||
|
<div class="row">
|
||||||
|
<div class="field">
|
||||||
|
<label>Name</label>
|
||||||
|
<input id="c-name" placeholder="demo-fn">
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label>Language</label>
|
||||||
|
<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 class="field">
|
||||||
|
<label>Entrypoint</label>
|
||||||
|
<input id="c-entry" value="main.main">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<div class="field">
|
||||||
|
<label>Route</label>
|
||||||
|
<input id="c-route" placeholder="/demo-fn">
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label>Методы (через запятую)</label>
|
||||||
|
<input id="c-methods" value="GET">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Код</label>
|
||||||
|
<textarea id="c-code">def main(ctx):
|
||||||
|
return {"ok": True, "msg": "hello from fission console"}
|
||||||
|
</textarea>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="btn ghost" onclick="closeCreate()">Отмена</button>
|
||||||
|
<button id="c-submit" class="btn" onclick="submitCreate()">Создать</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="edit-modal" class="modal">
|
||||||
|
<div class="panel">
|
||||||
|
<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="field">
|
||||||
|
<label>Name</label>
|
||||||
|
<input id="e-name" disabled>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label>Environment</label>
|
||||||
|
<input id="e-env" disabled>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label>Entrypoint</label>
|
||||||
|
<input id="e-entry" disabled>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Код</label>
|
||||||
|
<textarea id="e-code"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="btn ghost" onclick="closeEdit()">Отмена</button>
|
||||||
|
<button id="e-submit" class="btn" onclick="submitEdit()">Сохранить</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="invoke-modal" class="modal">
|
||||||
|
<div class="panel">
|
||||||
|
<h3 id="i-title">Вызов</h3>
|
||||||
|
<div>
|
||||||
|
<label>JSON тело запроса</label>
|
||||||
|
<textarea id="i-body">{"name":"world"}</textarea>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="btn ghost" onclick="closeInvoke()">Отмена</button>
|
||||||
|
<button id="i-submit" class="btn" onclick="submitInvoke()">Вызвать</button>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:10px;">
|
||||||
|
<label>Response</label>
|
||||||
|
<textarea id="i-resp" readonly style="min-height:160px;"></textarea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const API_BASE = window.location.pathname.startsWith('/console') ? '/console/api' : '/api';
|
||||||
|
|
||||||
|
const S = {
|
||||||
|
envs: [],
|
||||||
|
fns: [],
|
||||||
|
triggers: [],
|
||||||
|
currentEdit: 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) {
|
||||||
|
const r = await fetch(url, {headers: authHeaders()});
|
||||||
|
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||||
|
if (!r.ok) {
|
||||||
|
let msg = '';
|
||||||
|
try {
|
||||||
|
const body = await r.json();
|
||||||
|
msg = body.error || JSON.stringify(body);
|
||||||
|
} catch (_) {
|
||||||
|
msg = await r.text();
|
||||||
|
}
|
||||||
|
throw new Error(url + ': ' + r.status + (msg ? ' - ' + msg : ''));
|
||||||
|
}
|
||||||
|
return r.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestJSON(url, method, body) {
|
||||||
|
const r = await fetch(url, {
|
||||||
|
method: method,
|
||||||
|
headers: Object.assign({'Content-Type': 'application/json'}, authHeaders()),
|
||||||
|
body: body ? JSON.stringify(body) : undefined
|
||||||
|
});
|
||||||
|
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||||
|
let data = {};
|
||||||
|
try { data = await r.json(); } catch (_) {}
|
||||||
|
if (!r.ok) {
|
||||||
|
throw new Error(data.error || (url + ': ' + r.status));
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setText(id, value) {
|
||||||
|
document.getElementById(id).textContent = String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showStatus(message, kind) {
|
||||||
|
const el = document.getElementById('status');
|
||||||
|
el.style.display = 'block';
|
||||||
|
el.className = 'status ' + (kind || '');
|
||||||
|
el.textContent = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearStatus() {
|
||||||
|
const el = document.getElementById('status');
|
||||||
|
el.style.display = 'none';
|
||||||
|
el.className = 'status';
|
||||||
|
el.textContent = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseMethods(v) {
|
||||||
|
const items = String(v || '').split(',').map(s => s.trim().toUpperCase()).filter(Boolean);
|
||||||
|
return items.length ? Array.from(new Set(items)) : ['GET'];
|
||||||
|
}
|
||||||
|
|
||||||
|
function triggerByFn(fnName) {
|
||||||
|
return (S.triggers || []).find(function (t) {
|
||||||
|
return t.spec && t.spec.functionref && t.spec.functionref.name === fnName;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function h(v) {
|
||||||
|
return String(v == null ? '' : v)
|
||||||
|
.replaceAll('&', '&')
|
||||||
|
.replaceAll('<', '<')
|
||||||
|
.replaceAll('>', '>')
|
||||||
|
.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() {
|
||||||
|
document.getElementById('c-lang').value = 'python';
|
||||||
|
onLangChange();
|
||||||
|
document.getElementById('create-modal').classList.add('open');
|
||||||
|
document.getElementById('c-name').focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeCreate() {
|
||||||
|
document.getElementById('create-modal').classList.remove('open');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitCreate() {
|
||||||
|
const btn = document.getElementById('c-submit');
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const name = document.getElementById('c-name').value.trim();
|
||||||
|
if (!name) throw new Error('name is required');
|
||||||
|
const lang = document.getElementById('c-lang').value.trim();
|
||||||
|
if (!lang) throw new Error('language is required');
|
||||||
|
|
||||||
|
await requestJSON(API_BASE + '/functions', 'POST', {
|
||||||
|
name: name,
|
||||||
|
language: lang,
|
||||||
|
entrypoint: document.getElementById('c-entry').value.trim(),
|
||||||
|
route: document.getElementById('c-route').value.trim(),
|
||||||
|
methods: parseMethods(document.getElementById('c-methods').value),
|
||||||
|
code: document.getElementById('c-code').value
|
||||||
|
});
|
||||||
|
|
||||||
|
closeCreate();
|
||||||
|
showStatus('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0441\u043e\u0437\u0434\u0430\u043d\u0430: ' + name, 'ok');
|
||||||
|
await reloadAll();
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0441\u043e\u0437\u0434\u0430\u043d\u0438\u044f: ' + e.message, 'err');
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openEdit(name) {
|
||||||
|
try {
|
||||||
|
const fn = await getJSON(API_BASE + '/functions/' + encodeURIComponent(name));
|
||||||
|
S.currentEdit = fn;
|
||||||
|
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-env').value = fn.environment || '';
|
||||||
|
document.getElementById('e-entry').value = fn.entrypoint || '';
|
||||||
|
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');
|
||||||
|
} catch (e) {
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeEdit() {
|
||||||
|
document.getElementById('edit-modal').classList.remove('open');
|
||||||
|
S.currentEdit = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitEdit() {
|
||||||
|
if (!S.currentEdit) return;
|
||||||
|
const btn = document.getElementById('e-submit');
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const name = S.currentEdit.name;
|
||||||
|
await requestJSON(API_BASE + '/functions/' + encodeURIComponent(name) + '/code', 'PUT', {
|
||||||
|
code: document.getElementById('e-code').value
|
||||||
|
});
|
||||||
|
closeEdit();
|
||||||
|
showStatus('\u041a\u043e\u0434 \u043e\u0431\u043d\u043e\u0432\u043b\u0451\u043d: ' + name, 'ok');
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u043e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openInvoke(name) {
|
||||||
|
S.currentInvoke = name;
|
||||||
|
document.getElementById('i-title').textContent = '\u0412\u044b\u0437\u043e\u0432: ' + name;
|
||||||
|
document.getElementById('i-resp').value = '';
|
||||||
|
document.getElementById('invoke-modal').classList.add('open');
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeInvoke() {
|
||||||
|
document.getElementById('invoke-modal').classList.remove('open');
|
||||||
|
S.currentInvoke = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitInvoke() {
|
||||||
|
if (!S.currentInvoke) return;
|
||||||
|
const btn = document.getElementById('i-submit');
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const raw = document.getElementById('i-body').value.trim();
|
||||||
|
let parsed = {};
|
||||||
|
if (raw) parsed = JSON.parse(raw);
|
||||||
|
const result = await requestJSON(API_BASE + '/functions/' + encodeURIComponent(S.currentInvoke) + '/invoke', 'POST', parsed);
|
||||||
|
document.getElementById('i-resp').value = JSON.stringify(result, null, 2);
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('i-resp').value = '\u041e\u0448\u0438\u0431\u043a\u0430 \u0432\u044b\u0437\u043e\u0432\u0430: ' + e.message;
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeFn(name) {
|
||||||
|
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 {
|
||||||
|
await requestJSON(API_BASE + '/functions/' + encodeURIComponent(name), 'DELETE');
|
||||||
|
showStatus('\u0424\u0443\u043d\u043a\u0446\u0438\u044f \u0443\u0434\u0430\u043b\u0435\u043d\u0430: ' + name, 'ok');
|
||||||
|
await reloadAll();
|
||||||
|
} catch (e) {
|
||||||
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0443\u0434\u0430\u043b\u0435\u043d\u0438\u044f: ' + e.message, 'err');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reloadAll() {
|
||||||
|
try {
|
||||||
|
const [envs, pkgs, fns, http, time] = await Promise.all([
|
||||||
|
getJSON(API_BASE + '/environments'),
|
||||||
|
getJSON(API_BASE + '/packages'),
|
||||||
|
getJSON(API_BASE + '/functions'),
|
||||||
|
getJSON(API_BASE + '/httptriggers'),
|
||||||
|
getJSON(API_BASE + '/timetriggers')
|
||||||
|
]);
|
||||||
|
|
||||||
|
S.envs = envs || [];
|
||||||
|
S.fns = fns || [];
|
||||||
|
S.triggers = http || [];
|
||||||
|
|
||||||
|
setText('env-count', envs.length || 0);
|
||||||
|
setText('pkg-count', pkgs.length || 0);
|
||||||
|
setText('fn-count', fns.length || 0);
|
||||||
|
setText('http-count', http.length || 0);
|
||||||
|
setText('time-count', time.length || 0);
|
||||||
|
|
||||||
|
const rows = (fns || []).map(function (f) {
|
||||||
|
const spec = f.spec || {};
|
||||||
|
const env = (spec.environment && spec.environment.name) || '-';
|
||||||
|
const pkg = (spec.package && spec.package.packageref && spec.package.packageref.name) || '-';
|
||||||
|
const name = (f.metadata && f.metadata.name) || '-';
|
||||||
|
const trig = triggerByFn(name) || {};
|
||||||
|
const route = (trig.spec && trig.spec.relativeurl) || '-';
|
||||||
|
const methods = (trig.spec && trig.spec.methods) || [];
|
||||||
|
const chips = methods.map(function (m) { return '<span class="chip">' + h(m) + '</span>'; }).join('');
|
||||||
|
var isGo = /go[-_]env/.test(env);
|
||||||
|
var isTf = /^tf-/.test(name);
|
||||||
|
var tfBadge = (isGo || isTf) ? '<span class="chip" style="background:#555;color:#ffa" title="Управляется Terraform. Изменения могут быть перезаписаны при terraform apply.">TF</span> ' : '';
|
||||||
|
var actions = tfBadge +
|
||||||
|
'<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>' +
|
||||||
|
'<td class="mono">' + h(name) + '</td>' +
|
||||||
|
'<td>' + h(env) + '</td>' +
|
||||||
|
'<td class="mono">' + h(pkg) + '</td>' +
|
||||||
|
'<td class="mono">' + h(route) + '</td>' +
|
||||||
|
'<td>' + chips + '</td>' +
|
||||||
|
'<td class="nowrap">' + actions + '</td>' +
|
||||||
|
'</tr>';
|
||||||
|
}).join('');
|
||||||
|
|
||||||
|
document.getElementById('fn-rows').innerHTML = rows || '<tr><td colspan="3">\u041d\u0435\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0439</td></tr>';
|
||||||
|
if (!rows) {
|
||||||
|
document.getElementById('fn-rows').innerHTML = '<tr><td colspan="6">\u041d\u0435\u0442 \u0444\u0443\u043d\u043a\u0446\u0438\u0439</td></tr>';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('fn-rows').innerHTML = '<tr><td colspan="6">Load error: ' + e.message + '</td></tr>';
|
||||||
|
showStatus('\u041e\u0448\u0438\u0431\u043a\u0430 \u0437\u0430\u0433\u0440\u0443\u0437\u043a\u0438: ' + e.message, 'err');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
|
</body>
|
||||||
|
</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,805 @@
|
|||||||
|
# Fission Console — план разработки UI
|
||||||
|
|
||||||
|
Дата: 2026-04-15
|
||||||
|
Автор: Claude Opus → план для GPT 5.3 Codex
|
||||||
|
Статус: ПЛАН (к реализации)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Создать веб-консоль для Fission — аналог `sless-funcs-service` из проекта sless.
|
||||||
|
Консоль позволяет: смотреть функции, создавать, редактировать код, вызывать, управлять триггерами.
|
||||||
|
|
||||||
|
## Референсные файлы (ОБЯЗАТЕЛЬНО ИЗУЧИТЬ)
|
||||||
|
|
||||||
|
Перед написанием кода — прочитай эти файлы из sless (монтирован рядом на VM):
|
||||||
|
|
||||||
|
| Файл | Зачем |
|
||||||
|
|------|-------|
|
||||||
|
| `~/terra/sless/services/funcs/main.go` (942 строки) | **Главный референс** — Go backend funcs-service. Роутинг, proxy к оператору, рендеринг HTML с JSON data injection |
|
||||||
|
| `~/terra/sless/services/funcs/index.html` (1146 строк) | **Главный референс** — UI. Vanilla JS SPA, карточки функций, создание, редактирование, highlight.js, build polling |
|
||||||
|
| `~/terra/sless/services/funcs/Dockerfile` | Multi-stage Go+embed сборка |
|
||||||
|
| `~/terra/sless/services/funcs/funcs-service.yaml` | K8s Deployment+Service+Ingress |
|
||||||
|
| `~/terra/sless/internal/api/ui/iot-console.html` (1330 строк) | Референс для IoT-стиля UI (Nubes branding, login, табы, модалки) |
|
||||||
|
| `~/terra/sless/shared-sqs/app/ui/embed.go` | Паттерн go:embed |
|
||||||
|
| `~/terra/sless/shared-sqs/app/ui/index.html` (932 строки) | Ещё один референс SPA (queue CRUD) |
|
||||||
|
| `~/terra/sless/doc/decisions/funcs_console_editor.md` | Архитектурные решения по редактору кода |
|
||||||
|
|
||||||
|
## Архитектура
|
||||||
|
|
||||||
|
### Компоненты
|
||||||
|
|
||||||
|
```
|
||||||
|
User Browser
|
||||||
|
└─► https://fission.kube5s.ru/console
|
||||||
|
└─► nginx Ingress (уже есть для fission router)
|
||||||
|
└─► fission-console:8090 (новый pod в namespace fission)
|
||||||
|
├─► GET /console → HTML SPA (go:embed)
|
||||||
|
├─► GET /api/environments → kubectl proxy → CRD list
|
||||||
|
├─► GET /api/functions → kubectl proxy → CRD list
|
||||||
|
├─► GET /api/packages → kubectl proxy → CRD list
|
||||||
|
├─► GET /api/triggers → kubectl proxy → CRD list
|
||||||
|
├─► POST /api/functions → create CRD
|
||||||
|
├─► POST /api/functions/{name}/code → update package literal
|
||||||
|
├─► POST /api/functions/{name}/invoke → proxy → router
|
||||||
|
├─► DELETE /api/functions/{name} → delete CRD
|
||||||
|
└─► GET /api/functions/{name}/status → pod status
|
||||||
|
```
|
||||||
|
|
||||||
|
### Технологии
|
||||||
|
|
||||||
|
- **Backend:** Go, net/http, k8s client-go (dynamic client)
|
||||||
|
- **Frontend:** Vanilla HTML/CSS/JS (один файл, go:embed)
|
||||||
|
- **Подсветка кода:** highlight.js (CDN)
|
||||||
|
- **Стиль:** Nubes dark theme (идентичный sless/IoT)
|
||||||
|
- **Деплой:** Docker multi-stage → K8s Deployment + Service + Ingress
|
||||||
|
|
||||||
|
### Почему dynamic client (не REST API):
|
||||||
|
|
||||||
|
Fission в нашем кластере НЕ имеет REST `/v2` API.
|
||||||
|
Все данные — через Kubernetes CRD (environments.fission.io, functions.fission.io итд).
|
||||||
|
Текущий Terraform provider уже работает через dynamic client — переиспользуем тот же подход.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Структура файлов (создать)
|
||||||
|
|
||||||
|
```
|
||||||
|
console/
|
||||||
|
├── main.go # HTTP server + API handlers + k8s client
|
||||||
|
├── ui/
|
||||||
|
│ ├── embed.go # go:embed index.html
|
||||||
|
│ └── index.html # SPA: весь CSS + JS
|
||||||
|
├── go.mod
|
||||||
|
├── Dockerfile # multi-stage: Go → alpine
|
||||||
|
└── deploy/
|
||||||
|
└── console.yaml # K8s Deployment + Service + Ingress rule
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Этап 1: Backend (main.go) — ~400-500 строк Go
|
||||||
|
|
||||||
|
### 1.1 Инициализация
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Переменные окружения:
|
||||||
|
// KUBECONFIG — путь к kubeconfig (dev) или in-cluster
|
||||||
|
// FISSION_NAMESPACE — namespace с функциями (default: "default")
|
||||||
|
// FISSION_ROUTER_URL — внутренний URL роутера (default: "http://router.fission.svc.cluster.local")
|
||||||
|
// PORT — порт (default: "8090")
|
||||||
|
```
|
||||||
|
|
||||||
|
- Создать dynamic client (как в terraform provider — client.go)
|
||||||
|
- Маршруты: `/console` (UI), `/api/*` (JSON API), `/health`
|
||||||
|
|
||||||
|
### 1.2 API endpoints
|
||||||
|
|
||||||
|
| Метод | Путь | Что делает |
|
||||||
|
|-------|------|-----------|
|
||||||
|
| GET | /api/environments | List environments.fission.io → JSON array |
|
||||||
|
| GET | /api/packages | List packages.fission.io → JSON array |
|
||||||
|
| GET | /api/functions | List functions.fission.io → JSON array |
|
||||||
|
| GET | /api/httptriggers | List httptriggers.fission.io → JSON array |
|
||||||
|
| GET | /api/timetriggers | List timetriggers.fission.io → JSON array |
|
||||||
|
| GET | /api/functions/{name} | Get function + связанный package + trigger info |
|
||||||
|
| POST | /api/functions | Create: environment → package → function → httptrigger (всё за один вызов) |
|
||||||
|
| PUT | /api/functions/{name}/code | Update package spec.deployment.literal (новый код) |
|
||||||
|
| POST | /api/functions/{name}/invoke | Proxy → fission router: POST http://router/fission-function/v2/functions/{name} |
|
||||||
|
| DELETE | /api/functions/{name} | Delete function + httptrigger + package (каскадно) |
|
||||||
|
| GET | /api/pods | List pods по label svc=... в namespace "default" (показать runtime pods) |
|
||||||
|
|
||||||
|
### 1.3 Формат ответа (JSON)
|
||||||
|
|
||||||
|
Для листинга функций — объединённая структура:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"functions": [
|
||||||
|
{
|
||||||
|
"name": "hello",
|
||||||
|
"environment": "python",
|
||||||
|
"package": "hello-pkg",
|
||||||
|
"entrypoint": "main.main",
|
||||||
|
"code": "def main():\n return hello\n",
|
||||||
|
"trigger_url": "/hello",
|
||||||
|
"trigger_methods": ["GET"],
|
||||||
|
"invoke_url": "https://fission.kube5s.ru/hello",
|
||||||
|
"created": "2026-04-14T18:30:00Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"environments": [
|
||||||
|
{"name": "python", "image": "ghcr.io/fission/python-env", "version": 3}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.4 Create function — полный flow
|
||||||
|
|
||||||
|
POST /api/functions с телом:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "my-func",
|
||||||
|
"environment": "python",
|
||||||
|
"code": "def main():\n return {hello: world}\n",
|
||||||
|
"entrypoint": "main.main",
|
||||||
|
"route": "/my-func",
|
||||||
|
"methods": ["GET", "POST"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Backend создаёт 3 CRD объекта:
|
||||||
|
1. Package (`{name}-pkg`) — spec.environment + spec.deployment.literal (base64 код)
|
||||||
|
2. Function (`{name}`) — spec.environment + spec.package + spec.invokeStrategy
|
||||||
|
3. HTTPTrigger (`{name}-route`) — spec.functionref + spec.relativeurl + spec.methods
|
||||||
|
|
||||||
|
Если environment не существует — вернуть ошибку (не создавать).
|
||||||
|
|
||||||
|
### 1.5 Update code
|
||||||
|
|
||||||
|
PUT /api/functions/{name}/code с телом: `{"code": "..."}`
|
||||||
|
|
||||||
|
1. Найти function CRD → получить package name
|
||||||
|
2. Обновить package spec.deployment.literal (base64 encode)
|
||||||
|
3. Вернуть 200
|
||||||
|
|
||||||
|
### 1.6 Invoke
|
||||||
|
|
||||||
|
POST /api/functions/{name}/invoke с телом: произвольный JSON
|
||||||
|
|
||||||
|
Proxy → `http://router.fission.svc.cluster.local/fission-function/v2/functions/{name}`
|
||||||
|
Вернуть: status code + body + latency
|
||||||
|
|
||||||
|
### 1.7 Каскадное удаление
|
||||||
|
|
||||||
|
DELETE /api/functions/{name}:
|
||||||
|
1. Получить function → имя package и trigger
|
||||||
|
2. Удалить httptrigger(s) связанные с функцией
|
||||||
|
3. Удалить function
|
||||||
|
4. Удалить package
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Этап 2: Frontend (index.html) — ~800-1000 строк
|
||||||
|
|
||||||
|
### 2.1 Дизайн — Nubes dark theme
|
||||||
|
|
||||||
|
CSS переменные (скопировать из sless):
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
--bg-page: #001120;
|
||||||
|
--bg-surface: #001929;
|
||||||
|
--bg-navbar: #001C34;
|
||||||
|
--border: #0b2d50;
|
||||||
|
--accent: #1a7fd4;
|
||||||
|
--text-primary: #e2ecf6;
|
||||||
|
--text-secondary: #6b8eaa;
|
||||||
|
--danger: #e74c3c;
|
||||||
|
--success: #27ae60;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Страницы/секции
|
||||||
|
|
||||||
|
#### Navbar
|
||||||
|
```
|
||||||
|
[Nubes logo] [/] [Fission Console] [namespace: default] [↻ Refresh] [+ Создать функцию]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Секция: Dashboard (summary)
|
||||||
|
```
|
||||||
|
Environments: 3 | Functions: 8 | Triggers: 7 | Router: fission.kube5s.ru
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Секция: Карточки функций (как в sless funcs-service)
|
||||||
|
|
||||||
|
Каждая функция — карточка:
|
||||||
|
```
|
||||||
|
┌────────────────────────────────────────────────────────────┐
|
||||||
|
│ hello-fn [python] [Ready] https://fission.kube5s.ru/hello │
|
||||||
|
│ ✎ Edit ▶ Invoke ✕ Delete │
|
||||||
|
├────────────────────────────────────────────────────────────┤
|
||||||
|
│ (expand) → показать код с подсветкой (highlight.js) │
|
||||||
|
│ (edit mode) → textarea + Save │
|
||||||
|
│ (invoke mode) → JSON input + Send + Response display │
|
||||||
|
└────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Модалка: Создать функцию
|
||||||
|
```
|
||||||
|
┌─── Создать функцию ──────────────────────────┐
|
||||||
|
│ Environment: [python ▾] [nodejs ▾] [go ▾] │
|
||||||
|
│ Имя: [my-func_________] │
|
||||||
|
│ Entrypoint: [main.main_______] │
|
||||||
|
│ Route: [/my-func________] │
|
||||||
|
│ Файл: main.py │
|
||||||
|
│ ┌──────────────────────────────────────┐ │
|
||||||
|
│ │ def main(): │ │
|
||||||
|
│ │ return {"hello": "world"} │ │
|
||||||
|
│ └──────────────────────────────────────┘ │
|
||||||
|
│ [Отмена] [Создать] │
|
||||||
|
└───────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
При смене environment → обновить шаблон кода/файла:
|
||||||
|
- python → main.py, `def main(): ...`
|
||||||
|
- nodejs → main.js, `module.exports = async function(req) { ... }`
|
||||||
|
- go → main.go, `func Handler(w http.ResponseWriter, r *http.Request) { ... }`
|
||||||
|
|
||||||
|
#### Inline: Invoke функции
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─── Invoke: hello-fn ─────────────────────────┐
|
||||||
|
│ Input JSON: │
|
||||||
|
│ ┌──────────────────────────────────┐ │
|
||||||
|
│ │ {"name": "world"} │ │
|
||||||
|
│ └──────────────────────────────────┘ │
|
||||||
|
│ [▶ Send] │
|
||||||
|
│ │
|
||||||
|
│ Response (200, 34ms): │
|
||||||
|
│ ┌──────────────────────────────────┐ │
|
||||||
|
│ │ {"hello": "world"} │ │
|
||||||
|
│ └──────────────────────────────────┘ │
|
||||||
|
└────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 JavaScript — SPA логика
|
||||||
|
|
||||||
|
Принципы (из sless referenceов):
|
||||||
|
- Весь state в объекте `S = { functions: [], environments: [], ... }`
|
||||||
|
- `render()` — главный диспетчер
|
||||||
|
- Partial DOM updates по ID (не полный re-render)
|
||||||
|
- `fetch(/api/...)` для всех операций
|
||||||
|
- `h()` — HTML escape utility
|
||||||
|
- Карточки: expand/collapse для кода, inline edit, inline invoke
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Этап 3: Сборка и деплой
|
||||||
|
|
||||||
|
### 3.1 go.mod
|
||||||
|
|
||||||
|
```
|
||||||
|
module fission-console
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
k8s.io/apimachinery v0.32.3
|
||||||
|
k8s.io/client-go v0.32.3
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Важно: использовать те же версии k8s что в terraform/provider/go.mod.
|
||||||
|
|
||||||
|
### 3.2 Dockerfile
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM golang:1.24-alpine AS builder
|
||||||
|
WORKDIR /build
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o fission-console .
|
||||||
|
|
||||||
|
FROM alpine:3.20
|
||||||
|
RUN apk add --no-cache ca-certificates
|
||||||
|
COPY --from=builder /build/fission-console /fission-console
|
||||||
|
EXPOSE 8090
|
||||||
|
ENTRYPOINT ["/fission-console"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 K8s manifest (deploy/console.yaml)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
spec:
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: fission-console
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: fission-console
|
||||||
|
spec:
|
||||||
|
serviceAccountName: fission-console
|
||||||
|
containers:
|
||||||
|
- name: console
|
||||||
|
image: naeel/fission-console:v0.1.0
|
||||||
|
ports:
|
||||||
|
- containerPort: 8090
|
||||||
|
env:
|
||||||
|
- name: FISSION_NAMESPACE
|
||||||
|
value: "default"
|
||||||
|
- name: FISSION_ROUTER_URL
|
||||||
|
value: "http://router.fission.svc.cluster.local"
|
||||||
|
- name: PORT
|
||||||
|
value: "8090"
|
||||||
|
livenessProbe:
|
||||||
|
httpGet: {path: /health, port: 8090}
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
resources:
|
||||||
|
requests: {cpu: 10m, memory: 16Mi}
|
||||||
|
limits: {cpu: 100m, memory: 64Mi}
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ServiceAccount
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
---
|
||||||
|
apiVersion: rbac.authorization.k8s.io/v1
|
||||||
|
kind: ClusterRole
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
rules:
|
||||||
|
- apiGroups: ["fission.io"]
|
||||||
|
resources: ["environments", "packages", "functions", "httptriggers", "timetriggers"]
|
||||||
|
verbs: ["get", "list", "create", "update", "patch", "delete"]
|
||||||
|
- apiGroups: [""]
|
||||||
|
resources: ["pods"]
|
||||||
|
verbs: ["get", "list"]
|
||||||
|
---
|
||||||
|
apiVersion: rbac.authorization.k8s.io/v1
|
||||||
|
kind: ClusterRoleBinding
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
subjects:
|
||||||
|
- kind: ServiceAccount
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
roleRef:
|
||||||
|
kind: ClusterRole
|
||||||
|
name: fission-console
|
||||||
|
apiGroup: rbac.authorization.k8s.io
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
app: fission-console
|
||||||
|
ports:
|
||||||
|
- port: 8090
|
||||||
|
targetPort: 8090
|
||||||
|
---
|
||||||
|
# Ingress: добавить path /console к существующему fission ingress
|
||||||
|
# ИЛИ создать отдельный Ingress для fission-console
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: Ingress
|
||||||
|
metadata:
|
||||||
|
name: fission-console
|
||||||
|
namespace: fission
|
||||||
|
annotations:
|
||||||
|
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
|
||||||
|
spec:
|
||||||
|
ingressClassName: nginx
|
||||||
|
rules:
|
||||||
|
- host: fission.kube5s.ru
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
- path: /console
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: fission-console
|
||||||
|
port:
|
||||||
|
number: 8090
|
||||||
|
tls:
|
||||||
|
- hosts: [fission.kube5s.ru]
|
||||||
|
secretName: fission-tls # проверить имя секрета
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Этап 4: Тестирование
|
||||||
|
|
||||||
|
### 4.1 Smoke test (вручную в браузере)
|
||||||
|
1. Открыть https://fission.kube5s.ru/console
|
||||||
|
2. Увидеть список существующих функций
|
||||||
|
3. Создать новую функцию (Python) → увидеть в списке
|
||||||
|
4. Отредактировать код → сохранить
|
||||||
|
5. Invoke → получить ответ
|
||||||
|
6. Удалить → исчезла из списка
|
||||||
|
|
||||||
|
### 4.2 curl smoke
|
||||||
|
```bash
|
||||||
|
# API листинг
|
||||||
|
curl -s https://fission.kube5s.ru/console/api/functions | jq .
|
||||||
|
|
||||||
|
# Создать функцию
|
||||||
|
curl -s -X POST https://fission.kube5s.ru/console/api/functions \
|
||||||
|
-H Content-Type: application/json \
|
||||||
|
-d name:test-ui
|
||||||
|
|
||||||
|
# Invoke
|
||||||
|
curl -s -X POST https://fission.kube5s.ru/console/api/functions/test-ui/invoke
|
||||||
|
|
||||||
|
# Удалить
|
||||||
|
curl -s -X DELETE https://fission.kube5s.ru/console/api/functions/test-ui
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок выполнения (для Codex)
|
||||||
|
|
||||||
|
| # | Шаг | Файл(ы) | Критерий готовности |
|
||||||
|
|---|-----|---------|-------------------|
|
||||||
|
| 1 | Создать структуру console/ + go.mod | console/ | `go mod tidy` проходит |
|
||||||
|
| 2 | Написать main.go — HTTP server + k8s client init + health endpoint | main.go | Компилируется, /health отвечает |
|
||||||
|
| 3 | Написать API handlers: list environments/functions/packages/triggers | main.go | `curl /api/functions` возвращает JSON |
|
||||||
|
| 4 | Написать API handler: create function (env→pkg→fn→trigger) | main.go | POST создаёт 3 CRD |
|
||||||
|
| 5 | Написать API handler: update code (package literal) | main.go | PUT обновляет пакет |
|
||||||
|
| 6 | Написать API handler: invoke (proxy → router) | main.go | POST вызывает функцию |
|
||||||
|
| 7 | Написать API handler: delete (каскадно) | main.go | DELETE удаляет fn+pkg+trigger |
|
||||||
|
| 8 | Создать ui/embed.go | ui/embed.go | — |
|
||||||
|
| 9 | Создать index.html — CSS (Nubes dark theme) + navbar + layout | ui/index.html | Открывается с правильным стилем |
|
||||||
|
| 10 | JS: загрузка данных + рендер карточек функций | ui/index.html | Карточки отображаются |
|
||||||
|
| 11 | JS: expand карточки → показать код с подсветкой | ui/index.html | Код виден |
|
||||||
|
| 12 | JS: модалка создания функции + шаблоны Python/JS/Go | ui/index.html | Функция создаётся через UI |
|
||||||
|
| 13 | JS: inline edit mode + save | ui/index.html | Код обновляется |
|
||||||
|
| 14 | JS: inline invoke панель | ui/index.html | Вызов и ответ показываются |
|
||||||
|
| 15 | JS: delete с подтверждением | ui/index.html | Удаление работает |
|
||||||
|
| 16 | Dockerfile + добавить в .gitignore | Dockerfile, .gitignore | `docker build` проходит |
|
||||||
|
| 17 | K8s manifest + RBAC | deploy/console.yaml | Pod запускается, /health OK |
|
||||||
|
| 18 | Ingress → smoke test в браузере | deploy/console.yaml | UI доступен по HTTPS |
|
||||||
|
| 19 | Commit + push | — | Всё в git |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## КРИТИЧЕСКИЕ ПРАВИЛА ВЫПОЛНЕНИЯ
|
||||||
|
|
||||||
|
1. **ВСЁ через SSH на VM** — `ssh naeel@5.172.178.213`. Файлы писать локально (sshfs mount), команды — по SSH.
|
||||||
|
2. **Образы на Docker Hub** (`naeel/fission-console`). НЕ использовать pearlharbor.
|
||||||
|
3. **Nubes branding** — идентичный sless. CSS variables из референса.
|
||||||
|
4. **Vanilla JS** — без React/Vue/Angular. Один HTML файл.
|
||||||
|
5. **go:embed** — index.html встраивается в бинарник.
|
||||||
|
6. **Рабочая директория:** `~/terra/fission/console/`
|
||||||
|
7. **Проверять go.mod версии** — взять k8s-* из `~/terra/fission/terraform/provider/go.mod`
|
||||||
|
8. **Не ломать существующий provider** — console/ отдельный Go module
|
||||||
|
9. **Перед docker build** — убедиться что бинарник в .gitignore
|
||||||
|
10. **Commit + push** после каждого рабочего этапа
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что НЕ делать
|
||||||
|
|
||||||
|
- Auth/login — пока не нужен (демо-режим, без токенов)
|
||||||
|
- Multi-namespace — работаем с одним namespace (default)
|
||||||
|
- Управление environments через UI — только листинг (создание через terraform)
|
||||||
|
- Логи функций (stdout/stderr) — отложить
|
||||||
|
- Version history — отложить
|
||||||
|
- TimeTriggers CRUD — только отображение (создание — terraform)
|
||||||
|
ENDOFPLAN application/json \
|
||||||
|
-d environment:python
|
||||||
|
|
||||||
|
# Invoke
|
||||||
|
curl -s -X POST https://fission.kube5s.ru/console/api/functions/test-ui/invoke
|
||||||
|
|
||||||
|
# Удалить
|
||||||
|
curl -s -X DELETE https://fission.kube5s.ru/console/api/functions/test-ui
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок выполнения (для Codex)
|
||||||
|
|
||||||
|
| # | Шаг | Файл(ы) | Критерий готовности |
|
||||||
|
|---|-----|---------|-------------------|
|
||||||
|
| 1 | Создать структуру console/ + go.mod | console/ | `go mod tidy` проходит |
|
||||||
|
| 2 | Написать main.go — HTTP server + k8s client init + health endpoint | main.go | Компилируется, /health отвечает |
|
||||||
|
| 3 | Написать API handlers: list environments/functions/packages/triggers | main.go | `curl /api/functions` возвращает JSON |
|
||||||
|
| 4 | Написать API handler: create function (env→pkg→fn→trigger) | main.go | POST создаёт 3 CRD |
|
||||||
|
| 5 | Написать API handler: update code (package literal) | main.go | PUT обновляет пакет |
|
||||||
|
| 6 | Написать API handler: invoke (proxy → router) | main.go | POST вызывает функцию |
|
||||||
|
| 7 | Написать API handler: delete (каскадно) | main.go | DELETE удаляет fn+pkg+trigger |
|
||||||
|
| 8 | Создать ui/embed.go | ui/embed.go | — |
|
||||||
|
| 9 | Создать index.html — CSS (Nubes dark theme) + navbar + layout | ui/index.html | Открывается с правильным стилем |
|
||||||
|
| 10 | JS: загрузка данных + рендер карточек функций | ui/index.html | Карточки отображаются |
|
||||||
|
| 11 | JS: expand карточки → показать код с подсветкой | ui/index.html | Код виден |
|
||||||
|
| 12 | JS: модалка создания функции + шаблоны Python/JS/Go | ui/index.html | Функция создаётся через UI |
|
||||||
|
| 13 | JS: inline edit mode + save | ui/index.html | Код обновляется |
|
||||||
|
| 14 | JS: inline invoke панель | ui/index.html | Вызов и ответ показываются |
|
||||||
|
| 15 | JS: delete с подтверждением | ui/index.html | Удаление работает |
|
||||||
|
| 16 | Dockerfile + добавить в .gitignore | Dockerfile, .gitignore | `docker build` проходит |
|
||||||
|
| 17 | K8s manifest + RBAC | deploy/console.yaml | Pod запускается, /health OK |
|
||||||
|
| 18 | Ingress → smoke test в браузере | deploy/console.yaml | UI доступен по HTTPS |
|
||||||
|
| 19 | Commit + push | — | Всё в git |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## КРИТИЧЕСКИЕ ПРАВИЛА ВЫПОЛНЕНИЯ
|
||||||
|
|
||||||
|
1. **ВСЁ через SSH на VM** — `ssh naeel@5.172.178.213`. Файлы писать локально (sshfs mount), команды — по SSH.
|
||||||
|
2. **Образы на Docker Hub** (`naeel/fission-console`). НЕ использовать pearlharbor.
|
||||||
|
3. **Nubes branding** — идентичный sless. CSS variables из референса.
|
||||||
|
4. **Vanilla JS** — без React/Vue/Angular. Один HTML файл.
|
||||||
|
5. **go:embed** — index.html встраивается в бинарник.
|
||||||
|
6. **Рабочая директория:** `~/terra/fission/console/`
|
||||||
|
7. **Проверять go.mod версии** — взять k8s-* из `~/terra/fission/terraform/provider/go.mod`
|
||||||
|
8. **Не ломать существующий provider** — console/ отдельный Go module
|
||||||
|
9. **Перед docker build** — убедиться что бинарник в .gitignore
|
||||||
|
10. **Commit + push** после каждого рабочего этапа
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что НЕ делать
|
||||||
|
|
||||||
|
- Auth/login — пока не нужен (демо-режим, без токенов)
|
||||||
|
- Multi-namespace — работаем с одним namespace (default)
|
||||||
|
- Управление environments через UI — только листинг (создание через terraform)
|
||||||
|
- Логи функций (stdout/stderr) — отложить
|
||||||
|
- Version history — отложить
|
||||||
|
- TimeTriggers CRUD — только отображение (создание — terraform)
|
||||||
|
ENDOFPLAN application/json \
|
||||||
|
-d code:def main():\n return {"ok":true}
|
||||||
|
|
||||||
|
# Invoke
|
||||||
|
curl -s -X POST https://fission.kube5s.ru/console/api/functions/test-ui/invoke
|
||||||
|
|
||||||
|
# Удалить
|
||||||
|
curl -s -X DELETE https://fission.kube5s.ru/console/api/functions/test-ui
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок выполнения (для Codex)
|
||||||
|
|
||||||
|
| # | Шаг | Файл(ы) | Критерий готовности |
|
||||||
|
|---|-----|---------|-------------------|
|
||||||
|
| 1 | Создать структуру console/ + go.mod | console/ | `go mod tidy` проходит |
|
||||||
|
| 2 | Написать main.go — HTTP server + k8s client init + health endpoint | main.go | Компилируется, /health отвечает |
|
||||||
|
| 3 | Написать API handlers: list environments/functions/packages/triggers | main.go | `curl /api/functions` возвращает JSON |
|
||||||
|
| 4 | Написать API handler: create function (env→pkg→fn→trigger) | main.go | POST создаёт 3 CRD |
|
||||||
|
| 5 | Написать API handler: update code (package literal) | main.go | PUT обновляет пакет |
|
||||||
|
| 6 | Написать API handler: invoke (proxy → router) | main.go | POST вызывает функцию |
|
||||||
|
| 7 | Написать API handler: delete (каскадно) | main.go | DELETE удаляет fn+pkg+trigger |
|
||||||
|
| 8 | Создать ui/embed.go | ui/embed.go | — |
|
||||||
|
| 9 | Создать index.html — CSS (Nubes dark theme) + navbar + layout | ui/index.html | Открывается с правильным стилем |
|
||||||
|
| 10 | JS: загрузка данных + рендер карточек функций | ui/index.html | Карточки отображаются |
|
||||||
|
| 11 | JS: expand карточки → показать код с подсветкой | ui/index.html | Код виден |
|
||||||
|
| 12 | JS: модалка создания функции + шаблоны Python/JS/Go | ui/index.html | Функция создаётся через UI |
|
||||||
|
| 13 | JS: inline edit mode + save | ui/index.html | Код обновляется |
|
||||||
|
| 14 | JS: inline invoke панель | ui/index.html | Вызов и ответ показываются |
|
||||||
|
| 15 | JS: delete с подтверждением | ui/index.html | Удаление работает |
|
||||||
|
| 16 | Dockerfile + добавить в .gitignore | Dockerfile, .gitignore | `docker build` проходит |
|
||||||
|
| 17 | K8s manifest + RBAC | deploy/console.yaml | Pod запускается, /health OK |
|
||||||
|
| 18 | Ingress → smoke test в браузере | deploy/console.yaml | UI доступен по HTTPS |
|
||||||
|
| 19 | Commit + push | — | Всё в git |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## КРИТИЧЕСКИЕ ПРАВИЛА ВЫПОЛНЕНИЯ
|
||||||
|
|
||||||
|
1. **ВСЁ через SSH на VM** — `ssh naeel@5.172.178.213`. Файлы писать локально (sshfs mount), команды — по SSH.
|
||||||
|
2. **Образы на Docker Hub** (`naeel/fission-console`). НЕ использовать pearlharbor.
|
||||||
|
3. **Nubes branding** — идентичный sless. CSS variables из референса.
|
||||||
|
4. **Vanilla JS** — без React/Vue/Angular. Один HTML файл.
|
||||||
|
5. **go:embed** — index.html встраивается в бинарник.
|
||||||
|
6. **Рабочая директория:** `~/terra/fission/console/`
|
||||||
|
7. **Проверять go.mod версии** — взять k8s-* из `~/terra/fission/terraform/provider/go.mod`
|
||||||
|
8. **Не ломать существующий provider** — console/ отдельный Go module
|
||||||
|
9. **Перед docker build** — убедиться что бинарник в .gitignore
|
||||||
|
10. **Commit + push** после каждого рабочего этапа
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что НЕ делать
|
||||||
|
|
||||||
|
- Auth/login — пока не нужен (демо-режим, без токенов)
|
||||||
|
- Multi-namespace — работаем с одним namespace (default)
|
||||||
|
- Управление environments через UI — только листинг (создание через terraform)
|
||||||
|
- Логи функций (stdout/stderr) — отложить
|
||||||
|
- Version history — отложить
|
||||||
|
- TimeTriggers CRUD — только отображение (создание — terraform)
|
||||||
|
ENDOFPLAN application/json \
|
||||||
|
-d entrypoint:main.main
|
||||||
|
|
||||||
|
# Invoke
|
||||||
|
curl -s -X POST https://fission.kube5s.ru/console/api/functions/test-ui/invoke
|
||||||
|
|
||||||
|
# Удалить
|
||||||
|
curl -s -X DELETE https://fission.kube5s.ru/console/api/functions/test-ui
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок выполнения (для Codex)
|
||||||
|
|
||||||
|
| # | Шаг | Файл(ы) | Критерий готовности |
|
||||||
|
|---|-----|---------|-------------------|
|
||||||
|
| 1 | Создать структуру console/ + go.mod | console/ | `go mod tidy` проходит |
|
||||||
|
| 2 | Написать main.go — HTTP server + k8s client init + health endpoint | main.go | Компилируется, /health отвечает |
|
||||||
|
| 3 | Написать API handlers: list environments/functions/packages/triggers | main.go | `curl /api/functions` возвращает JSON |
|
||||||
|
| 4 | Написать API handler: create function (env→pkg→fn→trigger) | main.go | POST создаёт 3 CRD |
|
||||||
|
| 5 | Написать API handler: update code (package literal) | main.go | PUT обновляет пакет |
|
||||||
|
| 6 | Написать API handler: invoke (proxy → router) | main.go | POST вызывает функцию |
|
||||||
|
| 7 | Написать API handler: delete (каскадно) | main.go | DELETE удаляет fn+pkg+trigger |
|
||||||
|
| 8 | Создать ui/embed.go | ui/embed.go | — |
|
||||||
|
| 9 | Создать index.html — CSS (Nubes dark theme) + navbar + layout | ui/index.html | Открывается с правильным стилем |
|
||||||
|
| 10 | JS: загрузка данных + рендер карточек функций | ui/index.html | Карточки отображаются |
|
||||||
|
| 11 | JS: expand карточки → показать код с подсветкой | ui/index.html | Код виден |
|
||||||
|
| 12 | JS: модалка создания функции + шаблоны Python/JS/Go | ui/index.html | Функция создаётся через UI |
|
||||||
|
| 13 | JS: inline edit mode + save | ui/index.html | Код обновляется |
|
||||||
|
| 14 | JS: inline invoke панель | ui/index.html | Вызов и ответ показываются |
|
||||||
|
| 15 | JS: delete с подтверждением | ui/index.html | Удаление работает |
|
||||||
|
| 16 | Dockerfile + добавить в .gitignore | Dockerfile, .gitignore | `docker build` проходит |
|
||||||
|
| 17 | K8s manifest + RBAC | deploy/console.yaml | Pod запускается, /health OK |
|
||||||
|
| 18 | Ingress → smoke test в браузере | deploy/console.yaml | UI доступен по HTTPS |
|
||||||
|
| 19 | Commit + push | — | Всё в git |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## КРИТИЧЕСКИЕ ПРАВИЛА ВЫПОЛНЕНИЯ
|
||||||
|
|
||||||
|
1. **ВСЁ через SSH на VM** — `ssh naeel@5.172.178.213`. Файлы писать локально (sshfs mount), команды — по SSH.
|
||||||
|
2. **Образы на Docker Hub** (`naeel/fission-console`). НЕ использовать pearlharbor.
|
||||||
|
3. **Nubes branding** — идентичный sless. CSS variables из референса.
|
||||||
|
4. **Vanilla JS** — без React/Vue/Angular. Один HTML файл.
|
||||||
|
5. **go:embed** — index.html встраивается в бинарник.
|
||||||
|
6. **Рабочая директория:** `~/terra/fission/console/`
|
||||||
|
7. **Проверять go.mod версии** — взять k8s-* из `~/terra/fission/terraform/provider/go.mod`
|
||||||
|
8. **Не ломать существующий provider** — console/ отдельный Go module
|
||||||
|
9. **Перед docker build** — убедиться что бинарник в .gitignore
|
||||||
|
10. **Commit + push** после каждого рабочего этапа
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что НЕ делать
|
||||||
|
|
||||||
|
- Auth/login — пока не нужен (демо-режим, без токенов)
|
||||||
|
- Multi-namespace — работаем с одним namespace (default)
|
||||||
|
- Управление environments через UI — только листинг (создание через terraform)
|
||||||
|
- Логи функций (stdout/stderr) — отложить
|
||||||
|
- Version history — отложить
|
||||||
|
- TimeTriggers CRUD — только отображение (создание — terraform)
|
||||||
|
ENDOFPLAN application/json \
|
||||||
|
-d route:/test-ui
|
||||||
|
|
||||||
|
# Invoke
|
||||||
|
curl -s -X POST https://fission.kube5s.ru/console/api/functions/test-ui/invoke
|
||||||
|
|
||||||
|
# Удалить
|
||||||
|
curl -s -X DELETE https://fission.kube5s.ru/console/api/functions/test-ui
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок выполнения (для Codex)
|
||||||
|
|
||||||
|
| # | Шаг | Файл(ы) | Критерий готовности |
|
||||||
|
|---|-----|---------|-------------------|
|
||||||
|
| 1 | Создать структуру console/ + go.mod | console/ | `go mod tidy` проходит |
|
||||||
|
| 2 | Написать main.go — HTTP server + k8s client init + health endpoint | main.go | Компилируется, /health отвечает |
|
||||||
|
| 3 | Написать API handlers: list environments/functions/packages/triggers | main.go | `curl /api/functions` возвращает JSON |
|
||||||
|
| 4 | Написать API handler: create function (env→pkg→fn→trigger) | main.go | POST создаёт 3 CRD |
|
||||||
|
| 5 | Написать API handler: update code (package literal) | main.go | PUT обновляет пакет |
|
||||||
|
| 6 | Написать API handler: invoke (proxy → router) | main.go | POST вызывает функцию |
|
||||||
|
| 7 | Написать API handler: delete (каскадно) | main.go | DELETE удаляет fn+pkg+trigger |
|
||||||
|
| 8 | Создать ui/embed.go | ui/embed.go | — |
|
||||||
|
| 9 | Создать index.html — CSS (Nubes dark theme) + navbar + layout | ui/index.html | Открывается с правильным стилем |
|
||||||
|
| 10 | JS: загрузка данных + рендер карточек функций | ui/index.html | Карточки отображаются |
|
||||||
|
| 11 | JS: expand карточки → показать код с подсветкой | ui/index.html | Код виден |
|
||||||
|
| 12 | JS: модалка создания функции + шаблоны Python/JS/Go | ui/index.html | Функция создаётся через UI |
|
||||||
|
| 13 | JS: inline edit mode + save | ui/index.html | Код обновляется |
|
||||||
|
| 14 | JS: inline invoke панель | ui/index.html | Вызов и ответ показываются |
|
||||||
|
| 15 | JS: delete с подтверждением | ui/index.html | Удаление работает |
|
||||||
|
| 16 | Dockerfile + добавить в .gitignore | Dockerfile, .gitignore | `docker build` проходит |
|
||||||
|
| 17 | K8s manifest + RBAC | deploy/console.yaml | Pod запускается, /health OK |
|
||||||
|
| 18 | Ingress → smoke test в браузере | deploy/console.yaml | UI доступен по HTTPS |
|
||||||
|
| 19 | Commit + push | — | Всё в git |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## КРИТИЧЕСКИЕ ПРАВИЛА ВЫПОЛНЕНИЯ
|
||||||
|
|
||||||
|
1. **ВСЁ через SSH на VM** — `ssh naeel@5.172.178.213`. Файлы писать локально (sshfs mount), команды — по SSH.
|
||||||
|
2. **Образы на Docker Hub** (`naeel/fission-console`). НЕ использовать pearlharbor.
|
||||||
|
3. **Nubes branding** — идентичный sless. CSS variables из референса.
|
||||||
|
4. **Vanilla JS** — без React/Vue/Angular. Один HTML файл.
|
||||||
|
5. **go:embed** — index.html встраивается в бинарник.
|
||||||
|
6. **Рабочая директория:** `~/terra/fission/console/`
|
||||||
|
7. **Проверять go.mod версии** — взять k8s-* из `~/terra/fission/terraform/provider/go.mod`
|
||||||
|
8. **Не ломать существующий provider** — console/ отдельный Go module
|
||||||
|
9. **Перед docker build** — убедиться что бинарник в .gitignore
|
||||||
|
10. **Commit + push** после каждого рабочего этапа
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что НЕ делать
|
||||||
|
|
||||||
|
- Auth/login — пока не нужен (демо-режим, без токенов)
|
||||||
|
- Multi-namespace — работаем с одним namespace (default)
|
||||||
|
- Управление environments через UI — только листинг (создание через terraform)
|
||||||
|
- Логи функций (stdout/stderr) — отложить
|
||||||
|
- Version history — отложить
|
||||||
|
- TimeTriggers CRUD — только отображение (создание — terraform)
|
||||||
|
ENDOFPLAN application/json \
|
||||||
|
-d methods:[GET]
|
||||||
|
|
||||||
|
# Invoke
|
||||||
|
curl -s -X POST https://fission.kube5s.ru/console/api/functions/test-ui/invoke
|
||||||
|
|
||||||
|
# Удалить
|
||||||
|
curl -s -X DELETE https://fission.kube5s.ru/console/api/functions/test-ui
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок выполнения (для Codex)
|
||||||
|
|
||||||
|
| # | Шаг | Файл(ы) | Критерий готовности |
|
||||||
|
|---|-----|---------|-------------------|
|
||||||
|
| 1 | Создать структуру console/ + go.mod | console/ | `go mod tidy` проходит |
|
||||||
|
| 2 | Написать main.go — HTTP server + k8s client init + health endpoint | main.go | Компилируется, /health отвечает |
|
||||||
|
| 3 | Написать API handlers: list environments/functions/packages/triggers | main.go | `curl /api/functions` возвращает JSON |
|
||||||
|
| 4 | Написать API handler: create function (env→pkg→fn→trigger) | main.go | POST создаёт 3 CRD |
|
||||||
|
| 5 | Написать API handler: update code (package literal) | main.go | PUT обновляет пакет |
|
||||||
|
| 6 | Написать API handler: invoke (proxy → router) | main.go | POST вызывает функцию |
|
||||||
|
| 7 | Написать API handler: delete (каскадно) | main.go | DELETE удаляет fn+pkg+trigger |
|
||||||
|
| 8 | Создать ui/embed.go | ui/embed.go | — |
|
||||||
|
| 9 | Создать index.html — CSS (Nubes dark theme) + navbar + layout | ui/index.html | Открывается с правильным стилем |
|
||||||
|
| 10 | JS: загрузка данных + рендер карточек функций | ui/index.html | Карточки отображаются |
|
||||||
|
| 11 | JS: expand карточки → показать код с подсветкой | ui/index.html | Код виден |
|
||||||
|
| 12 | JS: модалка создания функции + шаблоны Python/JS/Go | ui/index.html | Функция создаётся через UI |
|
||||||
|
| 13 | JS: inline edit mode + save | ui/index.html | Код обновляется |
|
||||||
|
| 14 | JS: inline invoke панель | ui/index.html | Вызов и ответ показываются |
|
||||||
|
| 15 | JS: delete с подтверждением | ui/index.html | Удаление работает |
|
||||||
|
| 16 | Dockerfile + добавить в .gitignore | Dockerfile, .gitignore | `docker build` проходит |
|
||||||
|
| 17 | K8s manifest + RBAC | deploy/console.yaml | Pod запускается, /health OK |
|
||||||
|
| 18 | Ingress → smoke test в браузере | deploy/console.yaml | UI доступен по HTTPS |
|
||||||
|
| 19 | Commit + push | — | Всё в git |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## КРИТИЧЕСКИЕ ПРАВИЛА ВЫПОЛНЕНИЯ
|
||||||
|
|
||||||
|
1. **ВСЁ через SSH на VM** — `ssh naeel@5.172.178.213`. Файлы писать локально (sshfs mount), команды — по SSH.
|
||||||
|
2. **Образы на Docker Hub** (`naeel/fission-console`). НЕ использовать pearlharbor.
|
||||||
|
3. **Nubes branding** — идентичный sless. CSS variables из референса.
|
||||||
|
4. **Vanilla JS** — без React/Vue/Angular. Один HTML файл.
|
||||||
|
5. **go:embed** — index.html встраивается в бинарник.
|
||||||
|
6. **Рабочая директория:** `~/terra/fission/console/`
|
||||||
|
7. **Проверять go.mod версии** — взять k8s-* из `~/terra/fission/terraform/provider/go.mod`
|
||||||
|
8. **Не ломать существующий provider** — console/ отдельный Go module
|
||||||
|
9. **Перед docker build** — убедиться что бинарник в .gitignore
|
||||||
|
10. **Commit + push** после каждого рабочего этапа
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Что НЕ делать
|
||||||
|
|
||||||
|
- Auth/login — пока не нужен (демо-режим, без токенов)
|
||||||
|
- Multi-namespace — работаем с одним namespace (default)
|
||||||
|
- Управление environments через UI — только листинг (создание через terraform)
|
||||||
|
- Логи функций (stdout/stderr) — отложить
|
||||||
|
- Version history — отложить
|
||||||
|
- TimeTriggers CRUD — только отображение (создание — terraform)
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
# План: поддержка всех языков Fission
|
||||||
|
|
||||||
|
**Дата:** 2026-04-15
|
||||||
|
**Исполнитель:** Sonnet / GPT 5.3 Codex (AI-агент)
|
||||||
|
**Цель:** Добавить рабочие функции на Go, Java, .NET, Ruby, Rust, PHP — и ПРОТЕСТИРОВАТЬ каждую
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Текущее состояние
|
||||||
|
|
||||||
|
| Язык | Статус | Проблемы |
|
||||||
|
|---|---|---|
|
||||||
|
| Python | ✅ Работает | — |
|
||||||
|
| Node.js | ✅ Работает | — |
|
||||||
|
| Go | ❌ Timeout | Runtime compilation > 20s specialization timeout |
|
||||||
|
| Java | ❌ Не развёрнуто | — |
|
||||||
|
| .NET | ❌ Не развёрнуто | — |
|
||||||
|
| Ruby | ❌ Не развёрнуто | — |
|
||||||
|
| Rust | ❌ Не развёрнуто | — |
|
||||||
|
| PHP | ❌ Не развёрнуто | — |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## КРИТИЧЕСКИЕ ПРАВИЛА (обязательно для агента)
|
||||||
|
|
||||||
|
1. **ВСЕ КОМАНДЫ — ТОЛЬКО ЧЕРЕЗ SSH:**
|
||||||
|
```bash
|
||||||
|
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 'КОМАНДА'
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Файлы редактировать можно локально** — `/home/naeel/remote_dev/fission/` = `~/terra/fission/` на VM
|
||||||
|
|
||||||
|
3. **Terraform деплой:**
|
||||||
|
```bash
|
||||||
|
ssh ... 'cd ~/terra/fission/examples/FOLDER && TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission terraform apply -auto-approve'
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Проверка функции (JWT обязателен):**
|
||||||
|
```bash
|
||||||
|
ssh ... '
|
||||||
|
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 -w "\nHTTP=%{http_code}\n" -H "Authorization: Bearer $TOKEN" https://fission.kube5s.ru/ENDPOINT
|
||||||
|
'
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **НЕ ТРОГАТЬ существующие функции** — 15 шт., список в copilot-instructions.md
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 0: Проверить доступность образов (ОБЯЗАТЕЛЬНО ПЕРВЫМ)
|
||||||
|
|
||||||
|
Перед созданием — проверить что образы exist на ghcr.io:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh ... '
|
||||||
|
for lang in go java jvm dotnet dotnet20 ruby perl php binary; do
|
||||||
|
echo "--- $lang ---"
|
||||||
|
# Попробовать pull (dry-run)
|
||||||
|
docker pull ghcr.io/fission/${lang}-env:latest 2>&1 | head -3
|
||||||
|
echo
|
||||||
|
done
|
||||||
|
'
|
||||||
|
```
|
||||||
|
|
||||||
|
Если образ не найден — попробовать варианты:
|
||||||
|
- `ghcr.io/fission/go-env`
|
||||||
|
- `ghcr.io/fission/jvm-env` (Java = JVM в Fission!)
|
||||||
|
- `ghcr.io/fission/dotnet20-env` или `ghcr.io/fission/dotnet-env`
|
||||||
|
- `ghcr.io/fission/ruby-env`
|
||||||
|
- `ghcr.io/fission/php-env`
|
||||||
|
- `ghcr.io/fission/binary-env` (для предкомпилированных)
|
||||||
|
- `ghcr.io/fission/perl-env`
|
||||||
|
|
||||||
|
Если образ не существует — НЕ создавать функцию, пропустить язык.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 1: Go (ПРОБЛЕМНЫЙ — требует особого подхода)
|
||||||
|
|
||||||
|
### Проблема
|
||||||
|
Go env компилирует код при specialization → timeout 20s → функция не работает.
|
||||||
|
|
||||||
|
### Решение: использовать `binary-env`
|
||||||
|
Go компилируется на VM → заливается как бинарник → binary-env его запускает.
|
||||||
|
|
||||||
|
**Или:** увеличить specialization timeout через InvokeStrategy:
|
||||||
|
```yaml
|
||||||
|
spec:
|
||||||
|
InvokeStrategy:
|
||||||
|
ExecutionStrategy:
|
||||||
|
ExecutorType: newdeploy # вместо poolmgr
|
||||||
|
MinScale: 1 # always running
|
||||||
|
MaxScale: 3
|
||||||
|
```
|
||||||
|
|
||||||
|
### Вариант A: pre-compiled + binary-env
|
||||||
|
```
|
||||||
|
examples/go-hello/
|
||||||
|
├── code/
|
||||||
|
│ └── main.go # исходник для справки
|
||||||
|
├── build.sh # скрипт для компиляции
|
||||||
|
└── main.tf
|
||||||
|
```
|
||||||
|
|
||||||
|
**build.sh:**
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
cd code
|
||||||
|
CGO_ENABLED=0 GOOS=linux go build -o handler main.go
|
||||||
|
```
|
||||||
|
|
||||||
|
**main.tf** — использовать `binary-env` вместо `go-env`
|
||||||
|
|
||||||
|
### Вариант B: newdeploy executor
|
||||||
|
В Terraform manifests задать `executor_type = "newdeploy"` и `min_scale = 1`.
|
||||||
|
Проверить поддерживает ли наш провайдер эти аргументы:
|
||||||
|
```bash
|
||||||
|
ssh ... 'grep -r "executor\|newdeploy\|min_scale\|invoke_strategy" ~/terra/fission/internal/'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Код функции (main.go):
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Handler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/plain")
|
||||||
|
w.Write([]byte("Hello from Go in Fission"))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Тест: HTTP 200, body содержит "Hello from Go"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 2: Java (JVM)
|
||||||
|
|
||||||
|
### Образ: `ghcr.io/fission/jvm-env`
|
||||||
|
|
||||||
|
### Структура:
|
||||||
|
```
|
||||||
|
examples/java-hello/
|
||||||
|
├── code/
|
||||||
|
│ └── io/fission/Function.java
|
||||||
|
└── main.tf
|
||||||
|
```
|
||||||
|
|
||||||
|
### Код:
|
||||||
|
```java
|
||||||
|
package io.fission;
|
||||||
|
|
||||||
|
import org.springframework.http.RequestEntity;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
|
||||||
|
public class Function implements io.fission.Function {
|
||||||
|
@Override
|
||||||
|
public ResponseEntity<?> call(RequestEntity req, io.fission.Context context) {
|
||||||
|
return ResponseEntity.ok("Hello from Java in Fission");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**ВАЖНО:** Проверить точный интерфейс JVM env. Может потребоваться другой формат:
|
||||||
|
```bash
|
||||||
|
ssh ... 'docker run --rm ghcr.io/fission/jvm-env:latest cat /app/README.md 2>/dev/null || echo "No README"'
|
||||||
|
```
|
||||||
|
|
||||||
|
### main.tf:
|
||||||
|
```hcl
|
||||||
|
resource "fission_environment" "jvm" {
|
||||||
|
name = "tf-jvm-hello-env"
|
||||||
|
image = "ghcr.io/fission/jvm-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
# ... стандартный pattern
|
||||||
|
```
|
||||||
|
|
||||||
|
### Тест: HTTP 200, body содержит "Hello from Java"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 3: PHP
|
||||||
|
|
||||||
|
### Образ: `ghcr.io/fission/php-env`
|
||||||
|
|
||||||
|
### Структура:
|
||||||
|
```
|
||||||
|
examples/php-hello/
|
||||||
|
├── code/
|
||||||
|
│ └── hello.php
|
||||||
|
└── main.tf
|
||||||
|
```
|
||||||
|
|
||||||
|
### Код:
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
return function() {
|
||||||
|
return "Hello from PHP in Fission";
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
**ВАЖНО:** entrypoint для PHP — имя файла без расширения (`hello`).
|
||||||
|
|
||||||
|
### Тест: HTTP 200, body содержит "Hello from PHP"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 4: Ruby
|
||||||
|
|
||||||
|
### Образ: `ghcr.io/fission/ruby-env`
|
||||||
|
|
||||||
|
### Структура:
|
||||||
|
```
|
||||||
|
examples/ruby-hello/
|
||||||
|
├── code/
|
||||||
|
│ └── hello.rb
|
||||||
|
└── main.tf
|
||||||
|
```
|
||||||
|
|
||||||
|
### Код:
|
||||||
|
```ruby
|
||||||
|
def main
|
||||||
|
"Hello from Ruby in Fission"
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
### Тест: HTTP 200, body содержит "Hello from Ruby"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 5: .NET (C#)
|
||||||
|
|
||||||
|
### Образ: `ghcr.io/fission/dotnet-env` или `ghcr.io/fission/dotnet20-env`
|
||||||
|
|
||||||
|
### Структура:
|
||||||
|
```
|
||||||
|
examples/dotnet-hello/
|
||||||
|
├── code/
|
||||||
|
│ └── FissionFunction.cs
|
||||||
|
└── main.tf
|
||||||
|
```
|
||||||
|
|
||||||
|
### Код:
|
||||||
|
```csharp
|
||||||
|
using System;
|
||||||
|
using Fission.DotNetCore.Api;
|
||||||
|
|
||||||
|
public class FissionFunction
|
||||||
|
{
|
||||||
|
public string Execute(FissionContext context)
|
||||||
|
{
|
||||||
|
return "Hello from .NET in Fission";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Тест: HTTP 200, body содержит "Hello from .NET"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 6: Rust
|
||||||
|
|
||||||
|
### ВЕРОЯТНО НЕ СУЩЕСТВУЕТ официально.
|
||||||
|
|
||||||
|
Проверить:
|
||||||
|
```bash
|
||||||
|
ssh ... 'docker pull ghcr.io/fission/rust-env:latest 2>&1'
|
||||||
|
```
|
||||||
|
|
||||||
|
Если нет — пропустить. Rust можно реализовать через `binary-env` (pre-compiled).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаг 7: Perl (бонус)
|
||||||
|
|
||||||
|
### Образ: `ghcr.io/fission/perl-env`
|
||||||
|
|
||||||
|
```perl
|
||||||
|
sub main {
|
||||||
|
return "Hello from Perl in Fission";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Порядок выполнения (ВАЖНО)
|
||||||
|
|
||||||
|
```
|
||||||
|
1. Проверить доступность ВСЕХ образов (docker pull) → составить список реальных
|
||||||
|
2. Для каждого доступного языка:
|
||||||
|
a. Создать examples/LANG-hello/code/... + main.tf
|
||||||
|
b. terraform apply
|
||||||
|
c. curl с JWT → проверить HTTP 200 + ожидаемый body
|
||||||
|
d. Если не работает — смотреть логи:
|
||||||
|
kubectl -n default get events --sort-by=".lastTimestamp" | tail -20
|
||||||
|
kubectl -n default get pods | grep poolmgr-LANG
|
||||||
|
kubectl -n default logs <pod> -c <container> --tail=30
|
||||||
|
e. Если timeout — попробовать newdeploy executor
|
||||||
|
f. Если всё равно не работает — удалить через terraform destroy
|
||||||
|
3. Обновить список в консоли (она автоматически видит новые функции)
|
||||||
|
4. Протестировать все через консоль (invoke)
|
||||||
|
5. Коммит + пуш + тег
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Критерий успеха
|
||||||
|
|
||||||
|
| Язык | Endpoint | Ожидаемый body | HTTP |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Go | `/go-hello` | `Hello from Go in Fission` | 200 |
|
||||||
|
| Java | `/java-hello` | `Hello from Java in Fission` | 200 |
|
||||||
|
| PHP | `/php-hello` | `Hello from PHP in Fission` | 200 |
|
||||||
|
| Ruby | `/ruby-hello` | `Hello from Ruby in Fission` | 200 |
|
||||||
|
| .NET | `/dotnet-hello` | `Hello from .NET in Fission` | 200 |
|
||||||
|
| Perl | `/perl-hello` | `Hello from Perl in Fission` | 200 |
|
||||||
|
|
||||||
|
**Минимум:** 3 новых языка работают (Go + ещё 2)
|
||||||
|
**Идеал:** все 6
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Шаблон main.tf (копировать и менять)
|
||||||
|
|
||||||
|
```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" "env" {
|
||||||
|
name = "tf-LANG-hello-env"
|
||||||
|
image = "ghcr.io/fission/LANG-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-LANG-hello-pkg"
|
||||||
|
environment = fission_environment.env.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-LANG-hello-fn"
|
||||||
|
environment = fission_environment.env.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "ENTRYPOINT"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-LANG-hello-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/LANG-hello"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Entrypoint для каждого языка
|
||||||
|
|
||||||
|
| Язык | Entrypoint | Файл |
|
||||||
|
|---|---|---|
|
||||||
|
| Python | `main.main` | `main.py` |
|
||||||
|
| Node.js | `module.exports` (пустой) | `server.js` |
|
||||||
|
| Go | `Handler` | `main.go` |
|
||||||
|
| Java | `io.fission.Function` | `Function.java` |
|
||||||
|
| PHP | `hello` | `hello.php` |
|
||||||
|
| Ruby | `hello.main` | `hello.rb` |
|
||||||
|
| .NET | `FissionFunction.Execute` | `FissionFunction.cs` |
|
||||||
|
| Perl | `hello.main` | `hello.pm` |
|
||||||
|
|
||||||
|
**⚠️ ВНИМАНИЕ:** Entrypoints могут отличаться от указанных! Проверять документацию каждого env:
|
||||||
|
```bash
|
||||||
|
ssh ... 'docker run --rm ghcr.io/fission/LANG-env:latest env 2>/dev/null | head -20'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Откат при неудаче
|
||||||
|
|
||||||
|
Если язык не работает:
|
||||||
|
```bash
|
||||||
|
ssh ... 'cd ~/terra/fission/examples/LANG-hello && TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission terraform destroy -auto-approve'
|
||||||
|
rm -rf examples/LANG-hello/
|
||||||
|
```
|
||||||
+342
@@ -164,3 +164,345 @@
|
|||||||
|
|
||||||
### Следующий шаг
|
### Следующий шаг
|
||||||
- Добавить отдельные Terraform примеры для Node.js и Go функций.
|
- Добавить отдельные Terraform примеры для Node.js и Go функций.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2026-04-15
|
||||||
|
|
||||||
|
### Fission Console — Web UI для управления функциями
|
||||||
|
|
||||||
|
**Ветка:** `feat/console`
|
||||||
|
|
||||||
|
#### Реализовано (14 апреля, вечер → 15 апреля, утро)
|
||||||
|
|
||||||
|
**Backend (console/main.go):**
|
||||||
|
- Go HTTP-сервер с embedded UI
|
||||||
|
- CRUD API для Fission CRD через dynamic k8s client:
|
||||||
|
- `POST /api/functions` — создание (Package + Function + HTTPTrigger атомарно с rollback)
|
||||||
|
- `GET /api/functions` — список всех
|
||||||
|
- `GET /api/functions/{name}` — детали (с декодированным кодом, route, methods)
|
||||||
|
- `PUT /api/functions/{name}/code` — обновление кода
|
||||||
|
- `POST /api/functions/{name}/invoke` — вызов функции через роутер
|
||||||
|
- `DELETE /api/functions/{name}` — удаление (trigger + function + package)
|
||||||
|
- Двойная маршрутизация: `/api/*` и `/console/api/*` (для работы через ingress `/console/`)
|
||||||
|
- CORS middleware, request logging
|
||||||
|
|
||||||
|
**UI (console/ui/index.html):**
|
||||||
|
- SPA-дашборд с карточками (environments, packages, functions, httptriggers, timetriggers)
|
||||||
|
- Таблица функций с кнопками Edit/Invoke/Delete
|
||||||
|
- Модал Create: выбор environment, ввод кода, route, methods
|
||||||
|
- Модал Edit Code: редактирование и сохранение
|
||||||
|
- Модал Invoke: отправка запроса, отображение статуса/latency/response
|
||||||
|
- Модал Delete: подтверждение
|
||||||
|
- Динамический `API_BASE` для работы как с `/` так и с `/console/` prefix
|
||||||
|
|
||||||
|
**Тесты (console/main_test.go):**
|
||||||
|
- 5 unit-тестов:
|
||||||
|
- `TestNormalizeMethods` — нормализация HTTP-методов
|
||||||
|
- `TestCreateFunctionValidation` — валидация обязательных полей
|
||||||
|
- `TestCreateFunctionSuccessAndGetDetails` — полный CRUD flow + Get с декодированным кодом
|
||||||
|
- `TestUpdateFunctionCode` — обновление кода в package
|
||||||
|
- `TestInvokeFunctionWithJWTAuth` — invoke с mock-роутером, проверка JWT auth flow
|
||||||
|
- Используется `dynamicfake.NewSimpleDynamicClientWithCustomListKinds`
|
||||||
|
|
||||||
|
**Docker (console/Dockerfile):**
|
||||||
|
- Multi-stage: `golang:1.26-alpine` → `alpine:3.20`
|
||||||
|
- Бинарник ~15MB
|
||||||
|
|
||||||
|
**K8s deployment (console/deploy/console.yaml):**
|
||||||
|
- ServiceAccount `fission-console`
|
||||||
|
- ClusterRole с доступом к fission.io CRD (get/list/create/update/patch/delete)
|
||||||
|
- ClusterRoleBinding
|
||||||
|
- Deployment (1 replica, port 8090, health probes, resource limits)
|
||||||
|
- Service (ClusterIP:8090)
|
||||||
|
- Ingress (fission.kube5s.ru/console, nginx, TLS)
|
||||||
|
|
||||||
|
#### Invoke auth — проблема и решение
|
||||||
|
|
||||||
|
**Проблема:** invoke через console возвращал 401 от Fission router.
|
||||||
|
|
||||||
|
**Исследование:**
|
||||||
|
1. Попробовал SA token из пода → `key is of invalid type` (K8s SA = RS256, router ожидает HS256)
|
||||||
|
2. Прочитал feature-config: `auth.enabled: true`, endpoint `/auth/login`, JWT expiry 120s
|
||||||
|
3. Нашёл credentials в секрете `router`: username=admin, password=..., jwtSigningKey=...
|
||||||
|
4. Протестировал: `POST /auth/login` → получил JWT → invoke с Bearer JWT → 200 OK
|
||||||
|
|
||||||
|
**Решение:** console при invoke делает POST `/auth/login` к роутеру, получает JWT, кеширует на 100s.
|
||||||
|
|
||||||
|
**Баги по пути:**
|
||||||
|
- Router возвращает 201 Created (не 200) на login — код проверял строго 200 → добавил `|| 201`
|
||||||
|
- Кешированный Docker-образ: пересобрал тот же тег v0.2.0, нод использовал старый → перешёл на v0.2.2
|
||||||
|
|
||||||
|
**Env переменные для auth:**
|
||||||
|
- `FISSION_AUTH_USERNAME` → secretKeyRef из `router.username`
|
||||||
|
- `FISSION_AUTH_PASSWORD` → secretKeyRef из `router.password`
|
||||||
|
|
||||||
|
#### E2E результат (все через ingress https://fission.kube5s.ru/console/)
|
||||||
|
|
||||||
|
| Операция | Результат |
|
||||||
|
|----------|-----------|
|
||||||
|
| health | 200 ok |
|
||||||
|
| create | 201 Created (function + package + httptrigger) |
|
||||||
|
| get | 200 (code, route, methods, environment) |
|
||||||
|
| update code | 200 |
|
||||||
|
| invoke | **200**, response_raw = ответ функции, latency_ms = 138 |
|
||||||
|
| delete | 200 (trigger + function + package очищены) |
|
||||||
|
|
||||||
|
#### Коммиты
|
||||||
|
|
||||||
|
- `6731e89` — feat: deliver fission console UI, k8s deploy, and tests
|
||||||
|
- `8920ba1` — fix: invoke auth via Fission router JWT login
|
||||||
|
|
||||||
|
**Docker Hub:** `naeel/fission-console:v0.2.2`
|
||||||
|
|
||||||
|
#### Правила репозитория
|
||||||
|
|
||||||
|
Создан `.github/copilot-instructions.md` с правилами:
|
||||||
|
|
||||||
|
### Обновление этапа (UI invoke stability: JS)
|
||||||
|
|
||||||
|
- Проведена диагностика JS invoke через реальный UI-путь (`/console/api/functions/{name}/invoke`) и роутер/экзекьютор логи.
|
||||||
|
- Найдена корневая причина JS-таймаутов:
|
||||||
|
- для `node-env` используется `v2/specialize`
|
||||||
|
- при `functionName=main` runtime пытался загрузить `/userfunc/deployarchive/main`
|
||||||
|
- при plain literal `deployarchive` является файлом, не директорией
|
||||||
|
- после specialize без корректного контракта запросы зависали и упирались в router roundtripper timeout.
|
||||||
|
- Для `nodejs-acc` зафиксирован runtime image: `ghcr.io/fission/node-env:1.32.5`.
|
||||||
|
- Для JS-функций выровнен контракт runtime:
|
||||||
|
- `spec.package.functionName` выставлен в пустой entrypoint (`""`) для default export
|
||||||
|
- код приведен к формату ответа Node runtime: `return { status: 200, body: "..." }`
|
||||||
|
- для основных JS-маршрутов включены методы `GET` + `POST`.
|
||||||
|
- Подтверждена работоспособность через console invoke:
|
||||||
|
- `fn-js-acc` -> `status=200`, `response_raw=hello-js-ok`
|
||||||
|
- `fn-js-direct` -> `status=200`, `response_raw=hello-js-ok`
|
||||||
|
- тестовая матрица `jsm1..jsm4` -> `status=200`.
|
||||||
|
|
||||||
|
### Статус после фикса
|
||||||
|
|
||||||
|
- Python invoke: работает.
|
||||||
|
- JS invoke: работает по UI-пути и по прямому GET роутов.
|
||||||
|
- Go invoke (`fn-go-acc`): остается отдельной runtime-проблемой (вне JS-фикса).
|
||||||
|
- Маппинг путей (локально ~/remote_dev/ = ВМ ~/terra/)
|
||||||
|
- Редактирование файлов — разрешено локально
|
||||||
|
- Команды — ИСКЛЮЧИТЕЛЬНО через SSH (VPN-конфликты)
|
||||||
|
|
||||||
|
### Следующий шаг
|
||||||
|
- UI: автоматическое обновление дашборда после create/delete
|
||||||
|
- Рассмотреть добавление логов функций (kubectl logs)
|
||||||
|
- Рассмотреть добавление time triggers в UI
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Fix по результатам баг-репорта
|
||||||
|
|
||||||
|
### Что исправлено в Terraform provider
|
||||||
|
- `fission_package`: добавлен `ModifyPlan`, который автоматически пересчитывает `code_hash` по локальному коду (`source_dir`/`code_path`).
|
||||||
|
- `fission_package`: добавлена валидация существования `environment` до создания/обновления package.
|
||||||
|
- `fission_function`: добавлена валидация существования `environment` и `package` до create/update.
|
||||||
|
- `fission_function`: добавлена pre-flight валидация `entrypoint` для Python-исходника (`main.func` должен существовать как `def func(`).
|
||||||
|
- Добавлены unit-тесты на новый функционал (`code_hash`, entrypoint validation).
|
||||||
|
|
||||||
|
### Проверка на живом кластере
|
||||||
|
- После изменения `examples/hello-python/code/main.py` `terraform plan` теперь показывает `fission_package.hello will be updated in-place` с изменением `code_hash`.
|
||||||
|
- Конфигурация с несуществующим `environment` теперь падает на этапе apply с ошибкой валидации.
|
||||||
|
- Конфигурация с неверным `entrypoint` теперь падает на этапе apply с ошибкой валидации.
|
||||||
|
|
||||||
|
### Ограничения
|
||||||
|
- Runtime-проблемы Fission (зависания на cold start/таймауты выполнения) в этом изменении не трогались: исправлен только provider-слой валидации и обнаружения изменений.
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Fix отображения кода в Console UI
|
||||||
|
|
||||||
|
### Проблема
|
||||||
|
- В модальном окне редактирования функции (`Edit Code`) для некоторых пакетов отображались байты ZIP (`PK...`) вместо исходного кода.
|
||||||
|
|
||||||
|
### Причина
|
||||||
|
- `GET /console/api/functions/{name}` декодировал `spec.deployment.literal` только из base64, но не обрабатывал архивированный payload.
|
||||||
|
|
||||||
|
### Исправление
|
||||||
|
- В `console/main.go` добавлено декодирование `literal` с поддержкой ZIP:
|
||||||
|
- если payload plain text/utf-8 -> отдаётся как есть
|
||||||
|
- если payload ZIP -> извлекается `main.py`/`main.js`/`main.go` (или первый utf-8 файл)
|
||||||
|
- Обновлён deployment image: `naeel/fission-console:v0.2.4`.
|
||||||
|
|
||||||
|
### Проверка
|
||||||
|
- `GET /console/api/functions/fn-go-acc` теперь возвращает читаемый Go-код, без `PK...` сигнатур.
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Полный пользовательский прогон UI и invoke-fix
|
||||||
|
|
||||||
|
### Что проверено как пользовательский сценарий
|
||||||
|
- Прогнан массовый invoke через UI API (`POST /console/api/functions/{name}/invoke`) для всех функций в списке.
|
||||||
|
- Итого: `31` функций, из них `25` успешно отработали, `6` вернули 502/timeout (ожидаемо проблемные/сломанные кейсы).
|
||||||
|
- Проверен полный edit flow через UI API на рабочей функции:
|
||||||
|
- `GET function` -> `PUT /code` -> `POST /invoke` -> `PUT /code` (restore) -> `POST /invoke`.
|
||||||
|
|
||||||
|
### Найденный UI-баг и исправление
|
||||||
|
- Баг: после обновления кода через UI следующий invoke мог отдавать старую специализацию/кэш.
|
||||||
|
- Причина: обновлялся только `Package`, но не обновлялся `Function.spec.package.packageref.resourceversion`.
|
||||||
|
- Фикс в `console/main.go`:
|
||||||
|
- после `package update` читается новый `package.resourceVersion`
|
||||||
|
- выполняется update `Function` с новым `packageref.resourceversion`
|
||||||
|
- invoke сразу использует новую (или восстановленную) версию кода.
|
||||||
|
|
||||||
|
### Проверка фикса
|
||||||
|
- После update через UI invoke возвращает новый ответ.
|
||||||
|
- После restore через UI invoke возвращает исходный ответ (без зависания старого кэша).
|
||||||
|
|
||||||
|
### Статус `fn-go-acc`
|
||||||
|
- `fn-go-acc` продолжает падать не из-за UI, а из-за runtime specialization на стороне Fission.
|
||||||
|
- Подтверждено логами `router/executor`: `GetServiceForFunction ... context canceled` и постоянными readiness-fail у poolmgr pod-ов `go-acc`.
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Финальный фикс `fn-go-acc`
|
||||||
|
|
||||||
|
### Симптом и root cause
|
||||||
|
- `fn-go-acc` стабильно timeout'ился на invoke.
|
||||||
|
- Изначальный пакет содержал `main.go` как `deployment.literal`, из-за чего go-runtime пытался грузить текст как plugin:
|
||||||
|
- `plugin.Open("/userfunc/deployarchive/main.go"): invalid ELF header`.
|
||||||
|
|
||||||
|
### Что сделано
|
||||||
|
- Пересобран deploy-артефакт как Go plugin (`main.so`) и упакован в `deploy.zip`.
|
||||||
|
- Важно: сборка выполнена в том же образе, что у Fission environment builder:
|
||||||
|
- `ghcr.io/fission/go-builder` (Go 1.25.6), чтобы избежать несовместимости plugin ABI.
|
||||||
|
- Функция обновлена через Fission CLI:
|
||||||
|
- `fission function update -n default --name fn-go-acc --env go-acc --entrypoint Handler --deployarchive /tmp/fn-go-acc-fix2/deploy.zip -f`.
|
||||||
|
|
||||||
|
### Результат проверки
|
||||||
|
- `/go-acc` через router с JWT: `hello-go-ok`, `HTTP 200`.
|
||||||
|
- Executor логи: specialization проходит успешно (`specialized pod`, `added function service`), без `invalid ELF`.
|
||||||
|
|
||||||
|
### Контрольный smoke после фикса
|
||||||
|
- `/auto/ok` -> `HTTP 200`
|
||||||
|
- `/js-acc` -> `HTTP 200`
|
||||||
|
- `/js-direct` -> `HTTP 200`
|
||||||
|
- `/go-acc` -> `HTTP 200`
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Edit Code для `fn-go-acc` снова показывает исходник
|
||||||
|
|
||||||
|
### Проблема
|
||||||
|
- В `Edit Code` для `fn-go-acc` поле `code` было пустым.
|
||||||
|
- Причина: после `--deployarchive` пакет `pkg-go-acc` перешел на `spec.deployment.type=url`, а в console backend чтение кода шло только из `spec.deployment.literal`.
|
||||||
|
|
||||||
|
### Исправление
|
||||||
|
- В `console/main.go` добавлен fallback-поиск исходника:
|
||||||
|
- `spec.source.literal`
|
||||||
|
- `spec.deployment.literal`
|
||||||
|
- `spec.source.url`
|
||||||
|
- `spec.deployment.url`
|
||||||
|
- Добавлена загрузка архива по URL и извлечение исходника из zip (если есть текстовые файлы).
|
||||||
|
- Добавлен unit-тест `TestGetFunctionUsesSourceLiteralWhenDeploymentLiteralMissing`.
|
||||||
|
- Собран и выкачен образ `naeel/fission-console:v0.2.6`, деплой обновлен.
|
||||||
|
|
||||||
|
### Дополнительно по данным в кластере
|
||||||
|
- Для `fn-go-acc` обновлен `sourcearchive` (`main.go`), чтобы `pkg-go-acc.spec.source.literal` содержал исходник и был доступен в Edit Code.
|
||||||
|
|
||||||
|
### Проверка
|
||||||
|
- `GET /console/api/functions/fn-go-acc` возвращает непустой `code` (Go source).
|
||||||
|
- `/go-acc` продолжает отвечать `hello-go-ok`, `HTTP 200`.
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — TLS в console, бренд NUBES, проверка `tf-neg-syntax-fn`
|
||||||
|
|
||||||
|
### TLS: фактический статус
|
||||||
|
- `http://fission.kube5s.ru/console/` -> `308 Permanent Redirect` на `https://...`
|
||||||
|
- `https://fission.kube5s.ru/console/` -> `200`
|
||||||
|
- Ingress `fission-console` настроен с:
|
||||||
|
- `nginx.ingress.kubernetes.io/force-ssl-redirect: "true"`
|
||||||
|
- `tls.secretName: fission-tls`
|
||||||
|
- `cert-manager.io/cluster-issuer: letsencrypt-prod`
|
||||||
|
|
||||||
|
### UI оформление (NUBES)
|
||||||
|
- В `console/ui/index.html` добавлены:
|
||||||
|
- favicon (inline SVG)
|
||||||
|
- брендинг в navbar: mark + wordmark `NUBES` / `FISSION CONSOLE`
|
||||||
|
- обновлен `<title>` на `NUBES Fission Console`
|
||||||
|
- Выкат: `naeel/fission-console:v0.2.9`.
|
||||||
|
|
||||||
|
### Invoke `tf-neg-syntax-fn` — проверка
|
||||||
|
- Подтверждено, что у функции синтаксически невалидный код (`def main(: ...`).
|
||||||
|
- Console invoke теперь возвращает fail-fast ошибку (не «молчание»):
|
||||||
|
- `{"error":"invoke \"tf-neg-syntax-fn\" timeout after 20s: function specialization likely failed (for example, syntax error)"}`
|
||||||
|
- Причина на кластере: specialization падает в runtime с `500`, executor делает ретраи.
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Лечение "красного" HTTPS
|
||||||
|
|
||||||
|
### Root cause
|
||||||
|
- На одном host `fission.kube5s.ru` было два ingress:
|
||||||
|
- `fission-console` с TLS
|
||||||
|
- `fission-router` без TLS
|
||||||
|
- Из-за смешанной host-конфигурации TLS мог работать нестабильно/давать красный индикатор в браузере.
|
||||||
|
|
||||||
|
### Fix
|
||||||
|
- Пропатчен `fission/fission-router`:
|
||||||
|
- добавлен `spec.tls` с `secretName: fission-tls`
|
||||||
|
- добавлена аннотация `nginx.ingress.kubernetes.io/force-ssl-redirect: "true"`
|
||||||
|
|
||||||
|
### Проверка
|
||||||
|
- `http://fission.kube5s.ru/neg/syntax` -> `308` redirect на HTTPS
|
||||||
|
- Сертификат endpoint: Let's Encrypt R13, CN/SAN `fission.kube5s.ru`, валиден
|
||||||
|
- `https://fission.kube5s.ru/console/` -> `HTTP 200`
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Строгая очистка: оставлены только рабочие и с видимым кодом
|
||||||
|
|
||||||
|
### Требование
|
||||||
|
- Убрать всё лишнее и оставить только функции, которые одновременно:
|
||||||
|
- имеют непустой `code` в `GET /console/api/functions/{name}`
|
||||||
|
- успешно проходят `POST /console/api/functions/{name}/invoke` со `status=200`
|
||||||
|
|
||||||
|
### Что сделано
|
||||||
|
- Выполнена финальная очистка функций по whitelist.
|
||||||
|
- После очистки дополнительно проверены все оставшиеся функции через Console API (code + invoke).
|
||||||
|
- Исправлена ошибка в служебном cleanup-скрипте (битый jsonpath с `{n}`), из-за которой падала пост-обработка orphan-ресурсов.
|
||||||
|
|
||||||
|
### Итоговый набор
|
||||||
|
- `auth-test2`
|
||||||
|
- `fn-js-direct`
|
||||||
|
- `fn-js-acc`
|
||||||
|
- `hello`
|
||||||
|
- `tf-auto-ok-fn`
|
||||||
|
- `tf-stress-fast-fn`
|
||||||
|
|
||||||
|
### Финальное состояние кластера
|
||||||
|
- `functions=6`
|
||||||
|
- `httptriggers=6`
|
||||||
|
- `packages=6`
|
||||||
|
|
||||||
|
### Финальная валидация
|
||||||
|
- Для каждой из 6 функций: `code=OK`, `invoke=OK`.
|
||||||
|
|
||||||
|
## 2026-04-15 (дополнение) — Наращивание до 15 функций + исправление фавикона в live UI
|
||||||
|
|
||||||
|
### Запрос
|
||||||
|
- Увеличить набор до 15 функций, включая error-кейсы.
|
||||||
|
- Прогнать тесты и чинить код/манифесты при расхождении с ожиданием.
|
||||||
|
- Исправить favicon в реальном UI (а не только в репозитории).
|
||||||
|
|
||||||
|
### Что сделано по функциям
|
||||||
|
- Подняты функции из `examples`: `hello-python`, `deep-recursion`, `destroy-test`, `frequent-update`, `orphan-test`, `multi-env-1/2/3`.
|
||||||
|
- Добавлен негативный кейс `tf-neg-syntax-fn` с route `/neg/syntax`.
|
||||||
|
- Доведено до ровно `functions=15`, `httptriggers=15`.
|
||||||
|
|
||||||
|
### Фиксы по коду/манифестам (по результатам тестов)
|
||||||
|
- `examples/multi-env-1/main.tf`
|
||||||
|
- исправлен `source_dir` с `"$\{path.module\}/code"` на `"${path.module}/code"`.
|
||||||
|
- заменен image env с `ghcr.io/fission/python-env:v1.20.0` на `ghcr.io/fission/python-env`.
|
||||||
|
- `examples/multi-env-2/main.tf`
|
||||||
|
- аналогичные исправления `source_dir` и image.
|
||||||
|
- `examples/multi-env-3/main.tf`
|
||||||
|
- аналогичные исправления `source_dir` и image.
|
||||||
|
|
||||||
|
### Тест-матрица (router + JWT)
|
||||||
|
- Итог: `PASS 15 / FAIL 0`.
|
||||||
|
- Успешные (`HTTP 200`):
|
||||||
|
- `/auth-test2`, `/js-acc`, `/js-direct`, `/hello`, `/auto/ok`, `/destroy-test`, `/freq-update`, `/tf-hello`, `/multi-env-1`, `/multi-env-2`, `/multi-env-3`, `/orphan-test`, `/stress/fast`.
|
||||||
|
- Ожидаемые error-кейсы:
|
||||||
|
- `/deep-recursion` -> timeout (`curl rc=28`, `HTTP 000`)
|
||||||
|
- `/neg/syntax` -> timeout (`curl rc=28`, `HTTP 000`)
|
||||||
|
- Доп. проверка через Console invoke:
|
||||||
|
- `tf-multi-env-1-fn` -> `status=200`
|
||||||
|
- `tf-hello-fn` -> `status=200`
|
||||||
|
- `tf-neg-syntax-fn` и `tf-deep-recursion-fn` -> ожидаемая fail-fast ошибка invoke timeout.
|
||||||
|
|
||||||
|
### Фавикон (live)
|
||||||
|
- Причина «старого фавикона»: в кластере работал старый образ `naeel/fission-console:v0.3.0`.
|
||||||
|
- Собран и выкачен новый образ: `naeel/fission-console:v0.3.1`.
|
||||||
|
- Deployment обновлен и успешно прокатан.
|
||||||
|
- Проверено в live HTML: отдается
|
||||||
|
- `<link rel="icon" type="image/png" href="https://nubes.ru/themes/custom/nubes_2025/favicon.png">`.
|
||||||
|
|||||||
@@ -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,238 @@
|
|||||||
|
# Bug Report: Fission + Terraform Integration Testing (2026-04-15)
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
- **34 functions deployed**, **17 working correctly**
|
||||||
|
- **6 CRITICAL/HIGH bugs identified**
|
||||||
|
- **3 limitations/quirks documented**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔴 CRITICAL BUGS
|
||||||
|
|
||||||
|
### BUG #1: Hanging on cold start with syntax errors
|
||||||
|
**Severity:** CRITICAL
|
||||||
|
**Scope:** Fission runtime
|
||||||
|
**Symptoms:**
|
||||||
|
- Function with syntax error in `main.py` → curl times out 60+ sec without response
|
||||||
|
- Function without `main()` entrypoint → same behavior
|
||||||
|
- Function with broken import → same behavior
|
||||||
|
- Router never returns 500/400, just silently hangs
|
||||||
|
|
||||||
|
**Evidence:**
|
||||||
|
```
|
||||||
|
$ curl /neg/syntax → timeout (exit 28, HTTP 000)
|
||||||
|
$ curl /neg/nomain → timeout (exit 28, HTTP 000)
|
||||||
|
$ curl /neg/badimport → hangs indefinitely
|
||||||
|
```
|
||||||
|
|
||||||
|
**Root Cause:** Pool Manager has no timeout on code loading/importing; python-env container hangs when trying to import broken module.
|
||||||
|
|
||||||
|
**Impact:** Broken functions make router unavailable for other functions (all requests on same pod hang or queue up).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### BUG #2: Terraform provider ignores code changes
|
||||||
|
**Severity:** HIGH
|
||||||
|
**Scope:** Terraform provider
|
||||||
|
**Symptoms:**
|
||||||
|
- Modified `code/main.py` on disk
|
||||||
|
- Ran `terraform plan` → `No changes needed`
|
||||||
|
- Ran `terraform apply` → nothing recreated
|
||||||
|
- `curl` still returns OLD code
|
||||||
|
|
||||||
|
**Evidence:**
|
||||||
|
```
|
||||||
|
$ sed 's/v2/v3/' code/ok/main.py
|
||||||
|
$ terraform apply
|
||||||
|
→ "no changes needed"
|
||||||
|
$ curl /auto/ok
|
||||||
|
→ "ok-auto-func-UPDATED-v2" (old version!)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Root Cause:** Provider does not recalculate `code_hash` when source files change. Likely uses mtime check incorrectly or doesn't hash at all.
|
||||||
|
|
||||||
|
**Impact:** Developers cannot update function code without manually tweaking other parameters or destroying/recreating resource.
|
||||||
|
|
||||||
|
**Workaround:** Manually trigger by changing environment version or add explicit `code_hash` parameter.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### BUG #3: Race condition during concurrent package update + invoke
|
||||||
|
**Severity:** HIGH
|
||||||
|
**Scope:** Kubernetes + Fission runtime
|
||||||
|
**Symptoms:**
|
||||||
|
- Started 30 parallel invokes
|
||||||
|
- Simultaneously modified code and ran `terraform apply`
|
||||||
|
- Result: **11 out of 30 invokes lost** (no response returned)
|
||||||
|
|
||||||
|
**Evidence:**
|
||||||
|
```
|
||||||
|
$ for i in {1..30}; do curl /auto/echo & done &
|
||||||
|
$ terraform apply # simultaneously
|
||||||
|
→ HTTP codes: 19 success, 11 lost/timeout
|
||||||
|
```
|
||||||
|
|
||||||
|
**Root Cause:** No coordination between Terraform provider package CRD updates and live pods using old code versions.
|
||||||
|
|
||||||
|
**Impact:** Request loss (503/timeout), potential data loss.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### BUG #4: No timeout on function execution
|
||||||
|
**Severity:** HIGH
|
||||||
|
**Scope:** Fission runtime
|
||||||
|
**Symptoms:**
|
||||||
|
- Function with very long operation (fib(100)) → curl times out after 30 sec
|
||||||
|
- No HTTP 504 or 408 sent by router
|
||||||
|
- Pod continues computation until client disconnects
|
||||||
|
|
||||||
|
**Evidence:**
|
||||||
|
```
|
||||||
|
$ curl --max-time 30 /deep-recursion
|
||||||
|
→ timeout (exit 28, HTTP 000)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Root Cause:** Fission router has no timeout on downstream pod request; Python environment has no built-in execution timeout.
|
||||||
|
|
||||||
|
**Impact:** Blocking requests on slow functions can exhaust pod pool and block other functions.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### BUG #5: No foreign key validation on deploy
|
||||||
|
**Severity:** MEDIUM
|
||||||
|
**Scope:** Terraform provider + Fission CRD validation
|
||||||
|
**Symptoms:**
|
||||||
|
- Created package/function referencing non-existent environment
|
||||||
|
- Terraform applied successfully
|
||||||
|
- Function only fails at invoke time (too late)
|
||||||
|
|
||||||
|
**Evidence:**
|
||||||
|
```
|
||||||
|
$ tf apply (package references "nonexistent-env")
|
||||||
|
→ Apply complete! Resources added successfully
|
||||||
|
$ curl /missing-ref
|
||||||
|
→ 404 or timeout (errors caught too late)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Root Cause:** Provider does not validate environment/package references before creating CRDs. K8s CRD accepts any string value.
|
||||||
|
|
||||||
|
**Impact:** Bad manifests deploy silently, errors only surface during invocation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### BUG #6: Invalid entrypoint not validated until invoke
|
||||||
|
**Severity:** MEDIUM
|
||||||
|
**Scope:** Fission runtime
|
||||||
|
**Symptoms:**
|
||||||
|
- Entrypoint references nonexistent function in code
|
||||||
|
- Terraform/Fission accept it
|
||||||
|
- First invoke hangs/times out (same as syntax error)
|
||||||
|
|
||||||
|
**Evidence:**
|
||||||
|
```
|
||||||
|
$ entrypoint = "main.nonexistent_function"
|
||||||
|
$ curl /bad-entrypoint
|
||||||
|
→ timeout (HTTP 000)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Root Cause:** No pre-flight validation of entrypoint. Only caught during cold start import.
|
||||||
|
|
||||||
|
**Impact:** Same as БАГ #1 — hangs entire pod until timeout.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Limitation #1: Upload payload size limit
|
||||||
|
**Severity:** MEDIUM
|
||||||
|
**Symptoms:** Uploading ~1MB+ payload to function endpoint hangs connection
|
||||||
|
|
||||||
|
**Evidence:**
|
||||||
|
```
|
||||||
|
$ dd if=/dev/zero bs=1M count=1 | curl --data-binary @- /auto/ok
|
||||||
|
→ timeout
|
||||||
|
```
|
||||||
|
|
||||||
|
**Root Cause:** Likely nginx ingress `client_max_body_size` limit (default ~1MB).
|
||||||
|
|
||||||
|
**Impact:** Cannot send large payloads to functions via HTTP.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Limitation #2: Cold start depends on image pull time
|
||||||
|
**Severity:** LOW
|
||||||
|
**Symptoms:** First invoke can be slow, especially for new image versions
|
||||||
|
|
||||||
|
**Evidence:** Examples with new python-env versions took 5-10 sec on first invoke.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Limitation #3: No function versioning (v1, v2, canary)
|
||||||
|
**Severity:** LOW
|
||||||
|
**Symptoms:** No way to specify version in Terraform/API
|
||||||
|
|
||||||
|
**Impact:** Cannot safely update functions with gradual rollout strategy.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ WHAT WORKS WELL
|
||||||
|
|
||||||
|
- Parallel invokes (50+) → all pass
|
||||||
|
- State consistency between Terraform and K8s
|
||||||
|
- Orphaning recovery (manual CRD delete → Terraform recreates)
|
||||||
|
- Console API (CRUD, invoke, delete)
|
||||||
|
- Auth validation (401 on missing JWT)
|
||||||
|
- HTTP method validation (405 on POST to GET-only function)
|
||||||
|
- 404 on nonexistent endpoints
|
||||||
|
- Package + trigger + function CRUD integration
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 RECOMMENDATIONS
|
||||||
|
|
||||||
|
1. **CRITICAL:** Add execution timeout in router (~60 sec default, configurable)
|
||||||
|
2. **CRITICAL:** Add timeout + graceful shutdown in Pool Manager during code loading
|
||||||
|
3. **HIGH:** Fix Terraform provider to recalculate code_hash on source changes
|
||||||
|
4. **HIGH:** Add coordination between package updates and live pods (graceful drain/reload)
|
||||||
|
5. **HIGH:** Add foreign key validation (environment/package references must exist)
|
||||||
|
6. **HIGH:** Add entrypoint validation during deploy (check function exists in code)
|
||||||
|
7. **MEDIUM:** Document payload size limits and how to adjust
|
||||||
|
8. **MEDIUM:** Add pre-flight code validation (syntax check) on deploy
|
||||||
|
9. **LOW:** Implement function versioning/canary deployment support
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 TESTING STATISTICS
|
||||||
|
|
||||||
|
- Functions deployed: **34**
|
||||||
|
- Working correctly (5 sec response): **17**
|
||||||
|
- Hanging indefinitely: **4** (syntax-error, no-main, badimport, deep-recursion)
|
||||||
|
- Timing out: **1** (deep-recursion)
|
||||||
|
- Failing correctly (500): **2** (error, runtime-error)
|
||||||
|
- Not deployed: **1** (badimport partially)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## PARALLEL STRESS RESULTS
|
||||||
|
|
||||||
|
- 50 concurrent invokes to single function → **100% success**
|
||||||
|
- 30 concurrent invokes during terraform apply → **63% success rate** (race condition)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TESTING TIMELINE
|
||||||
|
- Start: 2026-04-15 07:00 UTC
|
||||||
|
- End: 2026-04-15 09:00 UTC
|
||||||
|
- Duration: **2 hours** continuous integration testing
|
||||||
|
- Functions tested: ~30 different scenarios
|
||||||
|
- Test cases executed: ~150+
|
||||||
|
- Terraform scenarios: 15+ (create, update, delete, orphaning, race, validation, bad manifests)
|
||||||
|
- Edge cases covered: syntax errors, missing deps, race conditions, payload limits, cold start hangs, entrypoint validation
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## NOTES FOR FOLLOW-UP
|
||||||
|
|
||||||
|
- Syntax error functions should ideally reject at deploy time (validate code before accepting)
|
||||||
|
- Code changes need lifecycle management (versioning, rollback, canary deployment)
|
||||||
|
- Router needs observability: span traces, request duration metrics, timeout tracking
|
||||||
|
- Consider adding health checks per pod to detect hung function execution
|
||||||
|
- Implement stricter validation during CRD creation (foreign keys, entrypoint existence)
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
# 2026-04-15 — Thinking Log
|
||||||
|
|
||||||
|
**Агент:** GitHub Copilot (Claude Opus 4.6)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: Fixup invoke auth в fission-console
|
||||||
|
|
||||||
|
### Контекст на начало сессии
|
||||||
|
|
||||||
|
Console (fission-console) — веб-UI для управления Fission serverless functions.
|
||||||
|
Был полностью реализован: CRUD (create/get/update/delete), UI с модалами, unit-тесты,
|
||||||
|
Docker-образ, k8s deployment, ingress. Всё работало через `https://fission.kube5s.ru/console/`.
|
||||||
|
|
||||||
|
**Единственная нерешённая проблема:** invoke функции через console API возвращал
|
||||||
|
`401 unauthorized: malformed token` — роутер Fission требует авторизацию.
|
||||||
|
|
||||||
|
### Анализ проблемы
|
||||||
|
|
||||||
|
Invoke flow: console → POST к роутеру Fission → роутер вызывает функцию.
|
||||||
|
|
||||||
|
Роутер Fission (`router.fission.svc.cluster.local`) сконфигурирован с auth:
|
||||||
|
- `AUTH_USERNAME` / `AUTH_PASSWORD` — из секрета `router`
|
||||||
|
- `JWT_SIGNING_KEY` — из секрета `router`
|
||||||
|
- ConfigMap `feature-config` содержит: `auth.enabled: true`, `auth.authUriPath: "/auth/login"`, `auth.jwtExpiryTime: 120`
|
||||||
|
|
||||||
|
Значит роутер использует **собственный JWT**, а не K8s ServiceAccount tokens.
|
||||||
|
|
||||||
|
### Первая попытка: SA token (неудачная)
|
||||||
|
|
||||||
|
Изначально решил использовать ServiceAccount token из пода:
|
||||||
|
- Файл `/var/run/secrets/kubernetes.io/serviceaccount/token` автоматически монтируется в любой под
|
||||||
|
- Добавил `saTokenPath` в server struct, метод `readSAToken()`
|
||||||
|
- При invoke читал токен и ставил `Authorization: Bearer <token>`
|
||||||
|
|
||||||
|
Результат: `401 unauthorized: key is of invalid type` — роутер пытался валидировать K8s JWT
|
||||||
|
своим signing key (HS256), а K8s SA token — RS256. Не совместимы.
|
||||||
|
|
||||||
|
### Исследование auth-механизма роутера
|
||||||
|
|
||||||
|
Прочитал секрет `router`:
|
||||||
|
- username: `admin`
|
||||||
|
- password: `7XG1lSg0EFqPLE4pf3He`
|
||||||
|
- jwtSigningKey: `FWT3rdVUwfUn08tkC3lt`
|
||||||
|
|
||||||
|
Проверил endpoint `/auth/login`:
|
||||||
|
```
|
||||||
|
POST http://router.fission.svc.cluster.local/auth/login
|
||||||
|
Body: {"username":"admin","password":"..."}
|
||||||
|
Response 201: {"accesstoken":"eyJ...","tokentype":"Bearer"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверил invoke с полученным JWT:
|
||||||
|
```
|
||||||
|
GET http://router.fission.svc.cluster.local/auth-test2
|
||||||
|
Header: Authorization: Bearer eyJ...
|
||||||
|
Response 200: hello
|
||||||
|
```
|
||||||
|
|
||||||
|
**Работает!** Роутер принимает свой JWT.
|
||||||
|
|
||||||
|
### Вторая попытка: JWT login (успешная)
|
||||||
|
|
||||||
|
**Решение:** console при invoke делает POST `/auth/login` к роутеру, получает JWT, кеширует,
|
||||||
|
использует для вызова функции.
|
||||||
|
|
||||||
|
Изменения в `main.go`:
|
||||||
|
1. Добавил поля в server struct: `authUser`, `authPass`, `tokenMu sync.Mutex`, `cachedJWT`, `tokenExpAt`
|
||||||
|
2. Новый метод `getRouterToken()`:
|
||||||
|
- Если `authUser`/`authPass` заданы → делает POST `/auth/login`
|
||||||
|
- Кеширует JWT на 100 сек (JWT expiry = 120 сек, берём с запасом)
|
||||||
|
- Fallback на SA token если login не удался
|
||||||
|
3. В `handleInvokeFunction` вызывает `getRouterToken()` и ставит `Authorization: Bearer <token>`
|
||||||
|
4. Env переменные `FISSION_AUTH_USERNAME` / `FISSION_AUTH_PASSWORD` берутся из секрета `router`
|
||||||
|
|
||||||
|
Изменения в `deploy/console.yaml`:
|
||||||
|
- Добавил env `FISSION_AUTH_USERNAME` и `FISSION_AUTH_PASSWORD` с `secretKeyRef` из секрета `router`
|
||||||
|
|
||||||
|
### Баг: 201 vs 200
|
||||||
|
|
||||||
|
Первый деплой с JWT login не работал: в логах видно что login возвращает **201 Created**
|
||||||
|
(не 200 OK), а мой код проверял строго `resp.StatusCode != http.StatusOK`.
|
||||||
|
JWT получался, но отбрасывался.
|
||||||
|
|
||||||
|
Фикс: `if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {`
|
||||||
|
|
||||||
|
### Баг: кешированный Docker-образ
|
||||||
|
|
||||||
|
После первого `docker push naeel/fission-console:v0.2.0` без JWT, потом пересобрал
|
||||||
|
с JWT и запушил **тот же тег** v0.2.0. Но нод кластера использовал старый образ
|
||||||
|
(imagePullPolicy по умолчанию = IfNotPresent). SHA не совпадали.
|
||||||
|
|
||||||
|
Решение: начал использовать инкрементальные теги (v0.2.1, v0.2.2).
|
||||||
|
|
||||||
|
### Финальный результат
|
||||||
|
|
||||||
|
E2E тест через ingress:
|
||||||
|
```
|
||||||
|
=== create ===
|
||||||
|
{"httptrigger":"final-test-route","name":"final-test","package":"final-test-pkg","route":"/final-test"}
|
||||||
|
|
||||||
|
=== invoke ===
|
||||||
|
{"invoke_url":"http://router.fission.svc.cluster.local/final-test","latency_ms":138,"response_raw":"invoke works!","status":200}
|
||||||
|
|
||||||
|
=== delete ===
|
||||||
|
{"deleted":true,"name":"final-test","package":"final-test-pkg"}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Все 5 тестов пройдены.** Commit `8920ba1` → `feat/console`.
|
||||||
|
|
||||||
|
### Обновление unit-тестов
|
||||||
|
|
||||||
|
Тест `TestInvokeFunctionWithJWTAuth`:
|
||||||
|
- Поднимает mock HTTP server, который на `/auth/login` возвращает `{"accesstoken":"fake-jwt-token-xyz"}`
|
||||||
|
- На другие пути проверяет `Authorization` header
|
||||||
|
- Создаёт функцию через CRUD, вызывает invoke
|
||||||
|
- Проверяет что JWT был получен и отправлен
|
||||||
|
|
||||||
|
### Итоговая архитектура auth flow
|
||||||
|
|
||||||
|
```
|
||||||
|
User → POST /console/api/functions/NAME/invoke
|
||||||
|
↓
|
||||||
|
Console backend:
|
||||||
|
1. GET trigger для NAME → route, methods
|
||||||
|
2. getRouterToken():
|
||||||
|
- cached JWT есть и не expired? → используем
|
||||||
|
- иначе POST /auth/login → получаем JWT, кешируем на 100s
|
||||||
|
3. GET/POST router_url + route
|
||||||
|
Header: Authorization: Bearer <JWT>
|
||||||
|
↓
|
||||||
|
Fission Router (валидирует JWT)
|
||||||
|
↓
|
||||||
|
Function pod → response
|
||||||
|
↓
|
||||||
|
Console → User (JSON: status, latency_ms, invoke_url, response_raw)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: Обновление правил репозиториев
|
||||||
|
|
||||||
|
Добавлены правила работы с файловой системой и SSH:
|
||||||
|
- sless: обновлён `.github/copilot-instructions.md` — добавлена секция про маппинг путей,
|
||||||
|
разрешение редактировать локально, обязательность SSH для команд
|
||||||
|
- fission: создан `.github/copilot-instructions.md` с аналогичными правилами
|
||||||
|
|
||||||
|
Причина: VPN может быть активен локально, вызывая сбои при прямом выполнении команд.
|
||||||
|
Монтирование sshfs делает локальное редактирование файлов эквивалентным редактированию на ВМ.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: JS invoke timeouts в UI (root cause + fix)
|
||||||
|
|
||||||
|
### Симптом
|
||||||
|
|
||||||
|
- Все JS invoke через UI (`/console/api/functions/{name}/invoke`) падали по timeout.
|
||||||
|
- В router логах: `roundtripper timeout (60s)`/`error sending request to function`.
|
||||||
|
- В executor логах specialization для node окружения могла проходить, но ответ функции не возвращался.
|
||||||
|
|
||||||
|
### Ключевые находки
|
||||||
|
|
||||||
|
1. Node runtime работал через `POST /v2/specialize`.
|
||||||
|
2. При `functionName=main` runtime строил путь загрузки как:
|
||||||
|
- `/userfunc/deployarchive/main`
|
||||||
|
3. В реальном поде `/userfunc/deployarchive` был **файлом** (literal payload), а не директорией.
|
||||||
|
4. После перевода на пустой entrypoint (`functionName=""`) specialization стала успешной (`202`, `user code loaded`),
|
||||||
|
но запросы всё равно зависали.
|
||||||
|
5. Прямая проверка контейнера показала второй контрактный нюанс node runtime:
|
||||||
|
- пользовательская функция должна возвращать объект формата
|
||||||
|
`{ status, body, headers? }`
|
||||||
|
- возврат простой строки приводил к зависанию ответа (callback не отправлял HTTP response).
|
||||||
|
|
||||||
|
### Принятые изменения
|
||||||
|
|
||||||
|
- `nodejs-acc` закреплен на `ghcr.io/fission/node-env:1.32.5`.
|
||||||
|
- Для JS функций (`fn-js-acc`, `fn-js-direct`, тестовые `jsm1..jsm4`):
|
||||||
|
- выставлен пустой entrypoint (`functionName=""`)
|
||||||
|
- код приведен к контракту Node runtime:
|
||||||
|
- `module.exports = async function(context) { return { status: 200, body: "..." }; }`
|
||||||
|
- Для основных JS trigger включены методы `GET` и `POST`.
|
||||||
|
|
||||||
|
### Проверка
|
||||||
|
|
||||||
|
- UI invoke:
|
||||||
|
- `fn-js-acc` -> `status=200`, `response_raw=hello-js-ok`
|
||||||
|
- `fn-js-direct` -> `status=200`, `response_raw=hello-js-ok`
|
||||||
|
- Прямые GET через роутер:
|
||||||
|
- `/js-acc` -> 200
|
||||||
|
- `/js-direct` -> 200
|
||||||
|
- Тестовые `jsm1..jsm4` после унификации кода -> 200 через UI invoke.
|
||||||
|
|
||||||
|
### Вывод
|
||||||
|
|
||||||
|
Проблема была не в UI-рендеринге и не в одном конкретном trigger, а в несовпадении контракта Node runtime:
|
||||||
|
- entrypoint/path specialization
|
||||||
|
- shape возвращаемого значения функции.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: Финальный fix `fn-go-acc` (Go runtime specialization)
|
||||||
|
|
||||||
|
### Симптом
|
||||||
|
|
||||||
|
- `fn-go-acc` выдавал timeout на invoke через console/router.
|
||||||
|
|
||||||
|
### Диагностика
|
||||||
|
|
||||||
|
1. На исходной конфигурации в executor логах:
|
||||||
|
- `plugin.Open("/userfunc/deployarchive/main.go"): invalid ELF header`.
|
||||||
|
2. Это означало, что runtime ожидал plugin-артефакт, но в package deployment лежал исходник `main.go`.
|
||||||
|
3. После первой попытки собрать plugin локальным `go1.26.1` ошибка `invalid ELF` ушла, но появился новый фейл specialization:
|
||||||
|
- `Post "http://127.0.0.1:8888/v2/specialize": EOF`.
|
||||||
|
4. Вывод: plugin собран несовместимой версией Go относительно runtime.
|
||||||
|
|
||||||
|
### Решение
|
||||||
|
|
||||||
|
- Сборка plugin выполнена в `ghcr.io/fission/go-builder` (Go 1.25.6), то есть тем же toolchain, что у Fission environment builder:
|
||||||
|
- `GO111MODULE=off /usr/local/go/bin/go build -buildmode=plugin -o main.so ./main.go`
|
||||||
|
- упаковка `main.so` в `deploy.zip`.
|
||||||
|
- Обновление функции через CLI:
|
||||||
|
- `fission function update -n default --name fn-go-acc --env go-acc --entrypoint Handler --deployarchive /tmp/fn-go-acc-fix2/deploy.zip -f`
|
||||||
|
|
||||||
|
### Проверка
|
||||||
|
|
||||||
|
- `/go-acc` через router с JWT: `hello-go-ok`, `HTTP 200`.
|
||||||
|
- В executor логах specialization успешен:
|
||||||
|
- `specialized pod`
|
||||||
|
- `added function service`
|
||||||
|
- без `invalid ELF` и без `EOF`.
|
||||||
|
|
||||||
|
### Контрольная матрица маршрутов
|
||||||
|
|
||||||
|
- `/auto/ok` -> 200
|
||||||
|
- `/js-acc` -> 200
|
||||||
|
- `/js-direct` -> 200
|
||||||
|
- `/go-acc` -> 200
|
||||||
|
|
||||||
|
### Практический вывод
|
||||||
|
|
||||||
|
Для go-env в этом кластере критично соблюдать контракт runtime:
|
||||||
|
1. deploy-пакет должен содержать именно plugin (`.so`), а не исходник.
|
||||||
|
2. plugin должен быть собран совместимой версией Go (через `ghcr.io/fission/go-builder`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: `Edit Code` для `fn-go-acc` пустой
|
||||||
|
|
||||||
|
### Симптом
|
||||||
|
|
||||||
|
- В UI (`GET /console/api/functions/fn-go-acc`) поле `code` было пустым.
|
||||||
|
|
||||||
|
### Почему так произошло
|
||||||
|
|
||||||
|
- После фикса runtime функция была переведена на deploy-архив plugin (`main.so`).
|
||||||
|
- Package имел вид:
|
||||||
|
- `spec.deployment.type=url`
|
||||||
|
- `spec.deployment.url=...`
|
||||||
|
- без `spec.deployment.literal`
|
||||||
|
- Backend в `handleGetFunction` извлекал код только из `spec.deployment.literal`, поэтому для URL-пакета отдавал пустую строку.
|
||||||
|
|
||||||
|
### Что изменено
|
||||||
|
|
||||||
|
- В backend добавлен `extractPackageSourceCode(...)` с fallback-приоритетом:
|
||||||
|
1. `spec.source.literal`
|
||||||
|
2. `spec.deployment.literal`
|
||||||
|
3. `spec.source.url`
|
||||||
|
4. `spec.deployment.url`
|
||||||
|
- Добавлена загрузка URL-архива через `fetchPackageArchive(...)` и декодирование через `decodeArchiveBytesToSource(...)`.
|
||||||
|
- Обновлен unit-тестами сценарий, где `deployment.literal` отсутствует, но есть `source.literal`.
|
||||||
|
|
||||||
|
### Операционные шаги
|
||||||
|
|
||||||
|
- Собран и задеплоен `naeel/fission-console:v0.2.6`.
|
||||||
|
- Для текущей `fn-go-acc` дополнительно обновлен `sourcearchive` (`main.go`), чтобы исходник гарантированно отображался в Edit Code.
|
||||||
|
|
||||||
|
### Результат
|
||||||
|
|
||||||
|
- `GET /console/api/functions/fn-go-acc` теперь возвращает непустой Go source в `code`.
|
||||||
|
- Вызов `/go-acc` остается рабочим (`hello-go-ok`, HTTP 200).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: Проверка TLS + branding NUBES + верификация `tf-neg-syntax-fn`
|
||||||
|
|
||||||
|
### TLS
|
||||||
|
|
||||||
|
- Проверен доступ к console:
|
||||||
|
- `http://.../console/` -> `308` redirect на HTTPS
|
||||||
|
- `https://.../console/` -> `200`
|
||||||
|
- Ingress конфиг содержит корректный TLS блок и принудительный SSL redirect.
|
||||||
|
- Вывод: endpoint защищен TLS, «незащищенного HTTP-доступа» нет.
|
||||||
|
|
||||||
|
### Брендинг NUBES
|
||||||
|
|
||||||
|
- В `console/ui/index.html` добавлены:
|
||||||
|
- `<title>NUBES Fission Console</title>`
|
||||||
|
- favicon (inline SVG)
|
||||||
|
- navbar brand block с `NUBES` / `FISSION CONSOLE`.
|
||||||
|
- Обновлен образ до `naeel/fission-console:v0.2.9`.
|
||||||
|
|
||||||
|
### `tf-neg-syntax-fn` — почему timeout вместо прямого SyntaxError
|
||||||
|
|
||||||
|
- Функция содержит заведомо битый Python (`def main(:`), confirmed через `GET /console/api/functions/tf-neg-syntax-fn`.
|
||||||
|
- На runtime это роняет specialization (`500`), после чего executor ретраит.
|
||||||
|
- Поэтому router/console не получает «чистый traceback» сразу из runtime API и видит timeout/ошибку specialization.
|
||||||
|
- Для UX введен fail-fast и явная ошибка в console invoke:
|
||||||
|
- `timeout after 20s: function specialization likely failed (for example, syntax error)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: "Не защищено красным" — экстренное лечение
|
||||||
|
|
||||||
|
### Наблюдение
|
||||||
|
|
||||||
|
- Сертификат endpoint сам по себе валидный (Let's Encrypt, CN/SAN = `fission.kube5s.ru`).
|
||||||
|
- Но на том же host были два ingress с разной TLS-конфигурацией:
|
||||||
|
- `fission-console` с TLS
|
||||||
|
- `fission-router` без TLS
|
||||||
|
|
||||||
|
### Действие
|
||||||
|
|
||||||
|
- Патч `fission-router`:
|
||||||
|
- добавлен `spec.tls` с `secretName: fission-tls`
|
||||||
|
- добавлен `force-ssl-redirect=true`
|
||||||
|
|
||||||
|
### Результат
|
||||||
|
|
||||||
|
- HTTP на роутер-пути дает 308 -> HTTPS
|
||||||
|
- HTTPS на console стабильно 200
|
||||||
|
- Конфигурация host выровнена: теперь и console, и router на одном сертификате.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: Строгая чистка до "только точно рабочие и видимые"
|
||||||
|
|
||||||
|
### Запрос
|
||||||
|
|
||||||
|
- Оставить только функции, которые в UI/Console:
|
||||||
|
- показывают исходник (`code` не пустой)
|
||||||
|
- реально вызываются (`invoke.status == 200`)
|
||||||
|
|
||||||
|
### Что произошло
|
||||||
|
|
||||||
|
- Выполнен массовый cleanup с keep-list.
|
||||||
|
- По логу cleanup выявилась ошибка jsonpath в пост-обработке orphan-пакетов:
|
||||||
|
- использовалось `{n}` вместо `{"\\n"}`
|
||||||
|
- это ломало шаг удаления orphan-объектов после основного удаления.
|
||||||
|
- Основное удаление функций при этом сработало корректно.
|
||||||
|
|
||||||
|
### Проверка после cleanup
|
||||||
|
|
||||||
|
- Текущее состояние:
|
||||||
|
- functions: 6
|
||||||
|
- httptriggers: 6
|
||||||
|
- packages: 6
|
||||||
|
- Остались только:
|
||||||
|
- `auth-test2`
|
||||||
|
- `fn-js-direct`
|
||||||
|
- `fn-js-acc`
|
||||||
|
- `hello`
|
||||||
|
- `tf-auto-ok-fn`
|
||||||
|
- `tf-stress-fast-fn`
|
||||||
|
- Для каждой функции через Console API подтверждено:
|
||||||
|
- `code=OK`
|
||||||
|
- `invoke=OK`
|
||||||
|
|
||||||
|
### Вывод
|
||||||
|
|
||||||
|
- Финальный набор теперь соответствует строгому критерию "однозначно работает и показывается".
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Сессия: Возврат к 15 функциям + проверка ожиданий + live favicon
|
||||||
|
|
||||||
|
### Наблюдение в начале
|
||||||
|
|
||||||
|
- После строгой чистки в кластере оставалось 6 функций.
|
||||||
|
- В live UI favicon оставался старым, хотя в репозитории правка уже была.
|
||||||
|
- Проверка deployment показала: работал старый image `naeel/fission-console:v0.3.0`.
|
||||||
|
|
||||||
|
### Расширение набора до 15
|
||||||
|
|
||||||
|
- Добавлены функции из примеров:
|
||||||
|
- `tf-hello-fn`, `tf-deep-recursion-fn`, `tf-destroy-test-fn`, `tf-freq-update-fn`, `tf-orphan-fn`
|
||||||
|
- `tf-multi-env-1-fn`, `tf-multi-env-2-fn`, `tf-multi-env-3-fn`
|
||||||
|
- Добавлен негативный кейс:
|
||||||
|
- `tf-neg-syntax-fn` + route `/neg/syntax`
|
||||||
|
- Итоговый размер:
|
||||||
|
- functions = 15
|
||||||
|
- httptriggers = 15
|
||||||
|
|
||||||
|
### Что сломалось и как починено
|
||||||
|
|
||||||
|
1. `multi-env-1/2/3` не применялись:
|
||||||
|
- ошибка Terraform: `Invalid escape sequence` из-за `"$\{path.module\}/code"`.
|
||||||
|
- фикс: заменено на `"${path.module}/code"` во всех трех `main.tf`.
|
||||||
|
|
||||||
|
2. После применения `multi-env-1/2/3` маршруты таймаутили (`rc=28`):
|
||||||
|
- причина: image env `ghcr.io/fission/python-env:v1.20.0`.
|
||||||
|
- фикс: переключено на `ghcr.io/fission/python-env`, re-apply всех трех модулей.
|
||||||
|
- результат: `/multi-env-1`, `/multi-env-2`, `/multi-env-3` -> `HTTP 200`.
|
||||||
|
|
||||||
|
### Финальная тест-матрица
|
||||||
|
|
||||||
|
- Router tests с JWT: `PASS=15, FAIL=0`.
|
||||||
|
- Успешные 200: базовые + multi-env + tf-hello + stress-fast.
|
||||||
|
- Ожидаемые ошибки:
|
||||||
|
- `/deep-recursion` -> timeout (`HTTP 000`, `rc=28`)
|
||||||
|
- `/neg/syntax` -> timeout (`HTTP 000`, `rc=28`)
|
||||||
|
- Console invoke подтверждает:
|
||||||
|
- positive функции -> `status=200`
|
||||||
|
- negative функции -> fail-fast timeout error.
|
||||||
|
|
||||||
|
### Favicon в live
|
||||||
|
|
||||||
|
- Собран и выкачен `naeel/fission-console:v0.3.1`.
|
||||||
|
- `deployment/fission-console` обновлен и rollout успешен.
|
||||||
|
- Проверка `https://fission.kube5s.ru/console/` показывает нужный favicon URL:
|
||||||
|
- `https://nubes.ru/themes/custom/nubes_2025/favicon.png`.
|
||||||
@@ -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 main():
|
||||||
|
lines = []
|
||||||
|
for i in range(500):
|
||||||
|
lines.append(f"line-{i}: {'x' * 80}")
|
||||||
|
return "\n".join(lines)
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
|
||||||
|
def main():
|
||||||
|
data = {"step": 1, "value": "start"}
|
||||||
|
for i in range(2, 6):
|
||||||
|
h = hashlib.sha256(json.dumps(data).encode()).hexdigest()[:8]
|
||||||
|
data = {"step": i, "prev_hash": h, "value": f"chain-{i}"}
|
||||||
|
return json.dumps(data)
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
def main():
|
||||||
|
s = 0
|
||||||
|
for i in range(1, 100000):
|
||||||
|
s += (i * i) % 97
|
||||||
|
return f"cpu-load:{s}"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
def main():
|
||||||
|
s = 0
|
||||||
|
for i in range(1, 100000):
|
||||||
|
s += (i * i) % 97
|
||||||
|
return f"cpu-load:{s}"
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
def main():
|
||||||
|
import os
|
||||||
|
msg = os.environ.get("FISSION_INPUT", "echo-default")
|
||||||
|
return f"echo:{msg}"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
def main():
|
||||||
|
msg = os.environ.get("FISSION_INPUT", "echo-default")
|
||||||
|
return f"echo:{msg}"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
def main():
|
||||||
|
emoji = "\U0001f680\U0001f525\u2764\ufe0f"
|
||||||
|
cyrillic = "\u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440!"
|
||||||
|
chinese = "\u4f60\u597d\u4e16\u754c"
|
||||||
|
return f"emoji:{emoji} cyr:{cyrillic} zh:{chinese}"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
raise Exception("auto-error-test")
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
raise Exception("auto-error-test")
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
def main():
|
||||||
|
data = {
|
||||||
|
"status": "ok",
|
||||||
|
"items": [{"id": i, "value": i * i} for i in range(10)],
|
||||||
|
"count": 10
|
||||||
|
}
|
||||||
|
return json.dumps(data)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
def main():
|
||||||
|
results = {
|
||||||
|
"pi": round(math.pi, 10),
|
||||||
|
"e": round(math.e, 10),
|
||||||
|
"sqrt2": round(math.sqrt(2), 10),
|
||||||
|
"factorial20": math.factorial(20),
|
||||||
|
"log1000": round(math.log(1000), 10),
|
||||||
|
}
|
||||||
|
parts = [f"{k}={v}" for k, v in results.items()]
|
||||||
|
return "; ".join(parts)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import sys
|
||||||
|
|
||||||
|
def main():
|
||||||
|
big_list = list(range(500000))
|
||||||
|
size_mb = sys.getsizeof(big_list) / (1024 * 1024)
|
||||||
|
return f"memory-alloc:{size_mb:.2f}MB len={len(big_list)}"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
def main():
|
||||||
|
return """line1
|
||||||
|
line2
|
||||||
|
line3
|
||||||
|
Конец (кириллица)"""
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
def main():
|
||||||
|
try:
|
||||||
|
a = 1 / 0
|
||||||
|
except ZeroDivisionError:
|
||||||
|
try:
|
||||||
|
raise ValueError("nested after div-by-zero")
|
||||||
|
except ValueError as e:
|
||||||
|
return f"caught-nested:{e}"
|
||||||
|
return "unreachable"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "ok-auto-func"
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "ok-auto-func-UPDATED-v3-with-comment"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
def fib(n):
|
||||||
|
if n <= 1:
|
||||||
|
return n
|
||||||
|
return fib(n - 1) + fib(n - 2)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
result = fib(30)
|
||||||
|
return f"fib(30)={result}"
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import time
|
||||||
|
def main():
|
||||||
|
time.sleep(2)
|
||||||
|
return "slow-done"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import time
|
||||||
|
|
||||||
|
def main():
|
||||||
|
time.sleep(2)
|
||||||
|
return "slow-done"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import datetime
|
||||||
|
|
||||||
|
def main():
|
||||||
|
now = datetime.datetime.utcnow().isoformat()
|
||||||
|
return f"timestamp:{now}Z"
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
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-auto-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
# ok function
|
||||||
|
resource "fission_package" "ok" {
|
||||||
|
name = "tf-auto-ok-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/ok"
|
||||||
|
code_hash = "v2"
|
||||||
|
}
|
||||||
|
resource "fission_function" "ok" {
|
||||||
|
name = "tf-auto-ok-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.ok.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "ok" {
|
||||||
|
name = "tf-auto-ok-route"
|
||||||
|
function = fission_function.ok.name
|
||||||
|
url = "/auto/ok"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# echo function
|
||||||
|
resource "fission_package" "echo" {
|
||||||
|
name = "tf-auto-echo-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/echo"
|
||||||
|
}
|
||||||
|
resource "fission_function" "echo" {
|
||||||
|
name = "tf-auto-echo-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.echo.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "echo" {
|
||||||
|
name = "tf-auto-echo-route"
|
||||||
|
function = fission_function.echo.name
|
||||||
|
url = "/auto/echo"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# error function
|
||||||
|
resource "fission_package" "error" {
|
||||||
|
name = "tf-auto-error-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/error"
|
||||||
|
}
|
||||||
|
resource "fission_function" "error" {
|
||||||
|
name = "tf-auto-error-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.error.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "error" {
|
||||||
|
name = "tf-auto-error-route"
|
||||||
|
function = fission_function.error.name
|
||||||
|
url = "/auto/error"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# cpu function
|
||||||
|
resource "fission_package" "cpu" {
|
||||||
|
name = "tf-auto-cpu-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/cpu"
|
||||||
|
}
|
||||||
|
resource "fission_function" "cpu" {
|
||||||
|
name = "tf-auto-cpu-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.cpu.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "cpu" {
|
||||||
|
name = "tf-auto-cpu-route"
|
||||||
|
function = fission_function.cpu.name
|
||||||
|
url = "/auto/cpu"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# slow function
|
||||||
|
resource "fission_package" "slow" {
|
||||||
|
name = "tf-auto-slow-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/slow"
|
||||||
|
}
|
||||||
|
resource "fission_function" "slow" {
|
||||||
|
name = "tf-auto-slow-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.slow.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "slow" {
|
||||||
|
name = "tf-auto-slow-route"
|
||||||
|
function = fission_function.slow.name
|
||||||
|
url = "/auto/slow"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- BATCH 2 ---
|
||||||
|
|
||||||
|
# jsonout: возвращает сложный JSON
|
||||||
|
resource "fission_package" "jsonout" {
|
||||||
|
name = "tf-auto-jsonout-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/jsonout"
|
||||||
|
}
|
||||||
|
resource "fission_function" "jsonout" {
|
||||||
|
name = "tf-auto-jsonout-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.jsonout.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "jsonout" {
|
||||||
|
name = "tf-auto-jsonout-route"
|
||||||
|
function = fission_function.jsonout.name
|
||||||
|
url = "/auto/jsonout"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# recurse: рекурсивный Фибоначчи (нагрузка на стек)
|
||||||
|
resource "fission_package" "recurse" {
|
||||||
|
name = "tf-auto-recurse-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/recurse"
|
||||||
|
}
|
||||||
|
resource "fission_function" "recurse" {
|
||||||
|
name = "tf-auto-recurse-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.recurse.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "recurse" {
|
||||||
|
name = "tf-auto-recurse-route"
|
||||||
|
function = fission_function.recurse.name
|
||||||
|
url = "/auto/recurse"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# bigdata: большой ответ (~45KB текста)
|
||||||
|
resource "fission_package" "bigdata" {
|
||||||
|
name = "tf-auto-bigdata-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/bigdata"
|
||||||
|
}
|
||||||
|
resource "fission_function" "bigdata" {
|
||||||
|
name = "tf-auto-bigdata-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.bigdata.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "bigdata" {
|
||||||
|
name = "tf-auto-bigdata-route"
|
||||||
|
function = fission_function.bigdata.name
|
||||||
|
url = "/auto/bigdata"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# math: математические вычисления
|
||||||
|
resource "fission_package" "math" {
|
||||||
|
name = "tf-auto-math-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/math"
|
||||||
|
}
|
||||||
|
resource "fission_function" "math" {
|
||||||
|
name = "tf-auto-math-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.math.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "math" {
|
||||||
|
name = "tf-auto-math-route"
|
||||||
|
function = fission_function.math.name
|
||||||
|
url = "/auto/math"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# timestamp: текущее время UTC
|
||||||
|
resource "fission_package" "timestamp" {
|
||||||
|
name = "tf-auto-timestamp-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/timestamp"
|
||||||
|
}
|
||||||
|
resource "fission_function" "timestamp" {
|
||||||
|
name = "tf-auto-timestamp-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.timestamp.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "timestamp" {
|
||||||
|
name = "tf-auto-timestamp-route"
|
||||||
|
function = fission_function.timestamp.name
|
||||||
|
url = "/auto/timestamp"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- BATCH 3 ---
|
||||||
|
|
||||||
|
# multiline: многострочный вывод с кириллицей
|
||||||
|
resource "fission_package" "multiline" {
|
||||||
|
name = "tf-auto-multiline-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/multiline"
|
||||||
|
}
|
||||||
|
resource "fission_function" "multiline" {
|
||||||
|
name = "tf-auto-multiline-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.multiline.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "multiline" {
|
||||||
|
name = "tf-auto-multiline-route"
|
||||||
|
function = fission_function.multiline.name
|
||||||
|
url = "/auto/multiline"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# encoding: unicode/emoji/кириллица/китайский
|
||||||
|
resource "fission_package" "encoding" {
|
||||||
|
name = "tf-auto-encoding-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/encoding"
|
||||||
|
}
|
||||||
|
resource "fission_function" "encoding" {
|
||||||
|
name = "tf-auto-encoding-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.encoding.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "encoding" {
|
||||||
|
name = "tf-auto-encoding-route"
|
||||||
|
function = fission_function.encoding.name
|
||||||
|
url = "/auto/encoding"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# nested: вложенные try/except
|
||||||
|
resource "fission_package" "nested" {
|
||||||
|
name = "tf-auto-nested-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/nested"
|
||||||
|
}
|
||||||
|
resource "fission_function" "nested" {
|
||||||
|
name = "tf-auto-nested-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.nested.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "nested" {
|
||||||
|
name = "tf-auto-nested-route"
|
||||||
|
function = fission_function.nested.name
|
||||||
|
url = "/auto/nested"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# memory: аллокация памяти (500k элементов)
|
||||||
|
resource "fission_package" "memory" {
|
||||||
|
name = "tf-auto-memory-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/memory"
|
||||||
|
}
|
||||||
|
resource "fission_function" "memory" {
|
||||||
|
name = "tf-auto-memory-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.memory.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "memory" {
|
||||||
|
name = "tf-auto-memory-route"
|
||||||
|
function = fission_function.memory.name
|
||||||
|
url = "/auto/memory"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
|
|
||||||
|
# chain: хеш-цепочка (имитация блокчейна)
|
||||||
|
resource "fission_package" "chain" {
|
||||||
|
name = "tf-auto-chain-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code/chain"
|
||||||
|
}
|
||||||
|
resource "fission_function" "chain" {
|
||||||
|
name = "tf-auto-chain-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.chain.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
resource "fission_http_trigger" "chain" {
|
||||||
|
name = "tf-auto-chain-route"
|
||||||
|
function = fission_function.chain.name
|
||||||
|
url = "/auto/chain"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -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,2 @@
|
|||||||
|
def main():
|
||||||
|
return "destroy-test-alive"
|
||||||
@@ -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-destroy-test-env"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-destroy-test-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-destroy-test-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-destroy-test-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/destroy-test"
|
||||||
|
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)")
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Настоящий Go через builder pipeline:
|
||||||
|
# go-builder компилирует handler.go → .so плагин
|
||||||
|
# go-env загружает .so через plugin.Open()
|
||||||
|
resource "fission_environment" "go" {
|
||||||
|
name = "tf-go-hello-env"
|
||||||
|
image = "ghcr.io/fission/go-env"
|
||||||
|
builder_image = "ghcr.io/fission/go-builder"
|
||||||
|
builder_command = "build"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-go-hello-pkg"
|
||||||
|
environment = fission_environment.go.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
deploy_type = "source"
|
||||||
|
build_command = "build"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-go-hello-fn"
|
||||||
|
environment = fission_environment.go.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "Handler"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-go-hello-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/go-hello"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -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,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-multi-env-1"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-multi-env-1-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-multi-env-1-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-multi-env-1-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/multi-env-1"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "env-2"
|
||||||
@@ -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-multi-env-2"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-multi-env-2-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-multi-env-2-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-multi-env-2-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/multi-env-2"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main():
|
||||||
|
return "env-3"
|
||||||
@@ -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-multi-env-3"
|
||||||
|
image = "ghcr.io/fission/python-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-multi-env-3-pkg"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-multi-env-3-fn"
|
||||||
|
environment = fission_environment.python.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.main"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-multi-env-3-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/multi-env-3"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -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,3 @@
|
|||||||
|
sub {
|
||||||
|
return "Hello from Perl in Fission";
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
terraform {
|
||||||
|
required_providers {
|
||||||
|
fission = {
|
||||||
|
source = "nail/fission"
|
||||||
|
version = "~> 0.1.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
provider "fission" {
|
||||||
|
kubeconfig_path = "/home/naeel/.kube/config"
|
||||||
|
namespace = "default"
|
||||||
|
}
|
||||||
|
|
||||||
|
# version = 1: Perl env uses v1 specialization (/specialize endpoint)
|
||||||
|
resource "fission_environment" "perl" {
|
||||||
|
name = "tf-perl-hello-env"
|
||||||
|
image = "ghcr.io/fission/perl-env"
|
||||||
|
version = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-perl-hello-pkg"
|
||||||
|
environment = fission_environment.perl.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-perl-hello-fn"
|
||||||
|
environment = fission_environment.perl.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "handler"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-perl-hello-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/perl-hello"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?php
|
||||||
|
function handler($context)
|
||||||
|
{
|
||||||
|
/** @var \Psr\Http\Message\ResponseInterface $response */
|
||||||
|
$response = $context["response"];
|
||||||
|
$response->getBody()->write("Hello from PHP in Fission");
|
||||||
|
}
|
||||||
@@ -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" "php" {
|
||||||
|
name = "tf-php-hello-env"
|
||||||
|
image = "ghcr.io/fission/php-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-php-hello-pkg"
|
||||||
|
environment = fission_environment.php.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-php-hello-fn"
|
||||||
|
environment = fission_environment.php.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "main.php::handler"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-php-hello-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/php-hello"
|
||||||
|
methods = ["GET"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# frozen_string_literal: true
|
||||||
|
|
||||||
|
def handler
|
||||||
|
"Hello from Ruby in Fission"
|
||||||
|
end
|
||||||
@@ -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" "ruby" {
|
||||||
|
name = "tf-ruby-hello-env"
|
||||||
|
image = "ghcr.io/fission/ruby-env"
|
||||||
|
version = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_package" "pkg" {
|
||||||
|
name = "tf-ruby-hello-pkg"
|
||||||
|
environment = fission_environment.ruby.name
|
||||||
|
source_dir = "${path.module}/code"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_function" "fn" {
|
||||||
|
name = "tf-ruby-hello-fn"
|
||||||
|
environment = fission_environment.ruby.name
|
||||||
|
package_name = fission_package.pkg.name
|
||||||
|
entrypoint = "handler"
|
||||||
|
}
|
||||||
|
|
||||||
|
resource "fission_http_trigger" "route" {
|
||||||
|
name = "tf-ruby-hello-route"
|
||||||
|
function = fission_function.fn.name
|
||||||
|
url = "/ruby-hello"
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,11 +2,14 @@ package resources
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"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"
|
||||||
|
|
||||||
@@ -24,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 создает инстанс ресурса функции.
|
||||||
@@ -67,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,
|
||||||
@@ -107,6 +137,22 @@ func (r *FunctionResource) Create(ctx context.Context, req resource.CreateReques
|
|||||||
}
|
}
|
||||||
|
|
||||||
namespace := resolveNamespace(plan.Namespace, r.client.Namespace)
|
namespace := resolveNamespace(plan.Namespace, r.client.Namespace)
|
||||||
|
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации Environment для Function", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pkg, err := ensurePackageExists(ctx, r.client, namespace, plan.PackageName.ValueString())
|
||||||
|
if err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации Package для Function", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := validateEntrypointAgainstPackageSource(plan.Entrypoint.ValueString(), pkg); err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации entrypoint", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
functionObject := functionToUnstructured(plan, namespace)
|
functionObject := functionToUnstructured(plan, namespace)
|
||||||
|
|
||||||
createdFunction, err := r.client.CreateFunction(ctx, functionObject)
|
createdFunction, err := r.client.CreateFunction(ctx, functionObject)
|
||||||
@@ -152,6 +198,22 @@ func (r *FunctionResource) Update(ctx context.Context, req resource.UpdateReques
|
|||||||
}
|
}
|
||||||
|
|
||||||
namespace := resolveNamespace(plan.Namespace, r.client.Namespace)
|
namespace := resolveNamespace(plan.Namespace, r.client.Namespace)
|
||||||
|
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации Environment для Function", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
pkg, err := ensurePackageExists(ctx, r.client, namespace, plan.PackageName.ValueString())
|
||||||
|
if err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации Package для Function", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := validateEntrypointAgainstPackageSource(plan.Entrypoint.ValueString(), pkg); err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации entrypoint", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
existingFunction, err := r.client.GetFunction(ctx, namespace, plan.Name.ValueString())
|
existingFunction, err := r.client.GetFunction(ctx, namespace, plan.Name.ValueString())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
resp.Diagnostics.AddError("Ошибка получения Function перед обновлением", err.Error())
|
resp.Diagnostics.AddError("Ошибка получения Function перед обновлением", err.Error())
|
||||||
@@ -201,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",
|
||||||
@@ -208,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(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,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())
|
||||||
@@ -251,6 +340,72 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func validateEntrypointAgainstPackageSource(entrypoint string, pkg *unstructured.Unstructured) error {
|
||||||
|
if entrypoint == "" {
|
||||||
|
return fmt.Errorf("entrypoint не может быть пустым")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Для Python/Go/JS: валидируем формат module.function и наличие функции в исходнике.
|
||||||
|
// Для PHP (module::function), Ruby (function), Perl (function) — допускаем любой непустой формат.
|
||||||
|
parts := strings.Split(entrypoint, ".")
|
||||||
|
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||||
|
// Не стандартный module.function — допускаем (PHP, Ruby, Perl и др.)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if parts[0] != "main" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
literalSource, found, err := unstructured.NestedString(pkg.Object, "spec", "deployment", "literal")
|
||||||
|
if err != nil || !found || literalSource == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
literalBytes, err := base64.StdEncoding.DecodeString(literalSource)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
source := string(literalBytes)
|
||||||
|
if looksLikePythonSource(source) {
|
||||||
|
signature := fmt.Sprintf("def %s(", parts[1])
|
||||||
|
if !strings.Contains(source, signature) {
|
||||||
|
return fmt.Errorf("entrypoint %q не найден в Python исходнике пакета (ожидался %q)", entrypoint, signature)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func looksLikePythonSource(source string) bool {
|
||||||
|
trimmed := strings.TrimSpace(source)
|
||||||
|
if strings.HasPrefix(trimmed, "def ") || strings.Contains(source, "\ndef ") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(source, "import ") && !strings.Contains(source, "func ") && !strings.Contains(source, "module.exports") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package resources
|
package resources
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/hashicorp/terraform-plugin-framework/types"
|
"github.com/hashicorp/terraform-plugin-framework/types"
|
||||||
@@ -30,9 +31,93 @@ 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 {
|
||||||
t.Fatalf("InvokeStrategy not set correctly")
|
t.Fatalf("InvokeStrategy not set correctly")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
source := "def main():\n return 'ok'\n"
|
||||||
|
pkg := &unstructured.Unstructured{Object: map[string]interface{}{
|
||||||
|
"spec": map[string]interface{}{
|
||||||
|
"deployment": map[string]interface{}{
|
||||||
|
"literal": base64.StdEncoding.EncodeToString([]byte(source)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
|
||||||
|
if err := validateEntrypointAgainstPackageSource("main.main", pkg); err != nil {
|
||||||
|
t.Fatalf("expected valid entrypoint, got error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateEntrypointAgainstPackageSourcePythonMissing(t *testing.T) {
|
||||||
|
source := "def another():\n return 'ok'\n"
|
||||||
|
pkg := &unstructured.Unstructured{Object: map[string]interface{}{
|
||||||
|
"spec": map[string]interface{}{
|
||||||
|
"deployment": map[string]interface{}{
|
||||||
|
"literal": base64.StdEncoding.EncodeToString([]byte(source)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
|
||||||
|
if err := validateEntrypointAgainstPackageSource("main.main", pkg); err == nil {
|
||||||
|
t.Fatalf("expected validation error for missing python function")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateEntrypointAgainstPackageSourceBadFormat(t *testing.T) {
|
||||||
|
pkg := &unstructured.Unstructured{}
|
||||||
|
// Пустой entrypoint должен быть ошибкой
|
||||||
|
if err := validateEntrypointAgainstPackageSource("", pkg); err == nil {
|
||||||
|
t.Fatalf("expected validation error for empty entrypoint")
|
||||||
|
}
|
||||||
|
// Одиночное слово допустимо (Ruby, Perl)
|
||||||
|
if err := validateEntrypointAgainstPackageSource("handler", pkg); err != nil {
|
||||||
|
t.Fatalf("unexpected error for single-word entrypoint: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
package resources
|
package resources
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
@@ -11,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"
|
||||||
|
|
||||||
@@ -19,6 +24,7 @@ import (
|
|||||||
|
|
||||||
var _ resource.Resource = &PackageResource{}
|
var _ resource.Resource = &PackageResource{}
|
||||||
var _ resource.ResourceWithImportState = &PackageResource{}
|
var _ resource.ResourceWithImportState = &PackageResource{}
|
||||||
|
var _ resource.ResourceWithModifyPlan = &PackageResource{}
|
||||||
|
|
||||||
// Изменено: 2026-04-14 19:45 UTC.
|
// Изменено: 2026-04-14 19:45 UTC.
|
||||||
// Resource для управления Fission Package через Kubernetes CRD API.
|
// Resource для управления Fission Package через Kubernetes CRD API.
|
||||||
@@ -35,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"`
|
||||||
@@ -69,7 +76,7 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
|
|||||||
},
|
},
|
||||||
"source_dir": schema.StringAttribute{
|
"source_dir": schema.StringAttribute{
|
||||||
Optional: true,
|
Optional: true,
|
||||||
Description: "Путь к директории с кодом (поддерживаются main.py, main.js, main.go).",
|
Description: "Путь к директории с кодом (поддерживаются main.py, main.js, main.go, main.php, main.rb, main.pl).",
|
||||||
},
|
},
|
||||||
"code_path": schema.StringAttribute{
|
"code_path": schema.StringAttribute{
|
||||||
Optional: true,
|
Optional: true,
|
||||||
@@ -77,12 +84,19 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
|
|||||||
},
|
},
|
||||||
"code_hash": schema.StringAttribute{
|
"code_hash": schema.StringAttribute{
|
||||||
Optional: true,
|
Optional: true,
|
||||||
|
Computed: true,
|
||||||
Description: "Произвольный хеш кода для контроля изменений.",
|
Description: "Произвольный хеш кода для контроля изменений.",
|
||||||
},
|
},
|
||||||
"build_command": schema.StringAttribute{
|
"build_command": schema.StringAttribute{
|
||||||
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,
|
||||||
@@ -104,6 +118,46 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ModifyPlan пересчитывает code_hash по локальному коду, чтобы terraform видел изменения source_dir/code_path.
|
||||||
|
func (r *PackageResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
|
||||||
|
if req.Plan.Raw.IsNull() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var plan packageResourceModel
|
||||||
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
||||||
|
if resp.Diagnostics.HasError() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var config packageResourceModel
|
||||||
|
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
|
||||||
|
if resp.Diagnostics.HasError() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasManualCodeHash(config.CodeHash) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if plan.SourceDir.IsUnknown() || plan.CodePath.IsUnknown() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !validatePackageSource(plan.SourceDir, plan.CodePath, &resp.Diagnostics) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
|
||||||
|
if err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
|
||||||
|
resp.Diagnostics.Append(resp.Plan.Set(ctx, &plan)...)
|
||||||
|
}
|
||||||
|
|
||||||
// Configure получает клиент из provider.Configure().
|
// Configure получает клиент из provider.Configure().
|
||||||
func (r *PackageResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
func (r *PackageResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
||||||
if req.ProviderData == nil {
|
if req.ProviderData == nil {
|
||||||
@@ -135,12 +189,21 @@ func (r *PackageResource) Create(ctx context.Context, req resource.CreateRequest
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
|
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации Environment для Package", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !hasManualCodeHash(plan.CodeHash) {
|
||||||
|
plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
|
||||||
|
}
|
||||||
|
|
||||||
packageObject := packageToUnstructured(plan, namespace, literalBytes)
|
packageObject := packageToUnstructured(plan, namespace, literalBytes)
|
||||||
createdPackage, err := r.client.CreatePackage(ctx, packageObject)
|
createdPackage, err := r.client.CreatePackage(ctx, packageObject)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -189,12 +252,21 @@ func (r *PackageResource) Update(ctx context.Context, req resource.UpdateRequest
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
|
if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil {
|
||||||
|
resp.Diagnostics.AddError("Ошибка валидации Environment для Package", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !hasManualCodeHash(plan.CodeHash) {
|
||||||
|
plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
|
||||||
|
}
|
||||||
|
|
||||||
existingPackage, err := r.client.GetPackage(ctx, namespace, plan.Name.ValueString())
|
existingPackage, err := r.client.GetPackage(ctx, namespace, plan.Name.ValueString())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
resp.Diagnostics.AddError("Ошибка получения Package перед обновлением", err.Error())
|
resp.Diagnostics.AddError("Ошибка получения Package перед обновлением", err.Error())
|
||||||
@@ -268,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)
|
||||||
@@ -292,9 +364,60 @@ 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"}
|
candidates := []string{"main.py", "main.js", "main.go", "main.php", "main.rb", "main.pl"}
|
||||||
for _, candidate := range candidates {
|
for _, candidate := range candidates {
|
||||||
candidatePath := filepath.Join(sourceDir, candidate)
|
candidatePath := filepath.Join(sourceDir, candidate)
|
||||||
fileInfo, err := os.Stat(candidatePath)
|
fileInfo, err := os.Stat(candidatePath)
|
||||||
@@ -303,13 +426,43 @@ func resolveMainSourceFile(sourceDir string) (string, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", fmt.Errorf("source_dir %q must contain one of: main.py, main.js, main.go", sourceDir)
|
return "", fmt.Errorf("source_dir %q must contain one of: main.py, main.js, main.go, main.php, main.rb, main.pl", sourceDir)
|
||||||
}
|
}
|
||||||
|
|
||||||
// packageToUnstructured преобразует Terraform model в Kubernetes CRD payload.
|
// packageToUnstructured преобразует Terraform model в Kubernetes CRD payload.
|
||||||
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",
|
||||||
@@ -317,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}
|
||||||
@@ -343,6 +482,8 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
|
|||||||
buildCommand, _, _ := unstructured.NestedString(packageObject.Object, "spec", "buildcmd")
|
buildCommand, _, _ := unstructured.NestedString(packageObject.Object, "spec", "buildcmd")
|
||||||
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")
|
||||||
|
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())),
|
||||||
@@ -352,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(),
|
||||||
@@ -371,5 +513,25 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
|
|||||||
state.BuildLog = types.StringValue(buildLog)
|
state.BuildLog = types.StringValue(buildLog)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Определить hash из содержимого (deployment или source)
|
||||||
|
literalForHash := deploymentLiteral
|
||||||
|
if literalForHash == "" {
|
||||||
|
literalForHash = sourceLiteral
|
||||||
|
}
|
||||||
|
if literalForHash != "" {
|
||||||
|
if literalBytes, err := base64.StdEncoding.DecodeString(literalForHash); err == nil {
|
||||||
|
state.CodeHash = types.StringValue(calculateCodeHash(literalBytes))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return state
|
return state
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func hasManualCodeHash(codeHash types.String) bool {
|
||||||
|
return !codeHash.IsNull() && !codeHash.IsUnknown() && codeHash.ValueString() != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func calculateCodeHash(literalBytes []byte) string {
|
||||||
|
sum := sha256.Sum256(literalBytes)
|
||||||
|
return fmt.Sprintf("%x", sum)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
package resources
|
package resources
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -102,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) {
|
||||||
@@ -113,6 +158,16 @@ func TestResolveNamespace(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCalculateCodeHash(t *testing.T) {
|
||||||
|
input := []byte("def main():\n return 'ok'\n")
|
||||||
|
got := calculateCodeHash(input)
|
||||||
|
|
||||||
|
expected := fmt.Sprintf("%x", sha256.Sum256(input))
|
||||||
|
if got != expected {
|
||||||
|
t.Fatalf("unexpected code hash: got %q want %q", got, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestUnstructuredToPackageModelSetsNullComputed(t *testing.T) {
|
func TestUnstructuredToPackageModelSetsNullComputed(t *testing.T) {
|
||||||
obj := &unstructured.Unstructured{Object: map[string]interface{}{
|
obj := &unstructured.Unstructured{Object: map[string]interface{}{
|
||||||
"apiVersion": "fission.io/v1",
|
"apiVersion": "fission.io/v1",
|
||||||
@@ -167,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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package resources
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||||
|
|
||||||
|
"terraform-provider-fission/internal/client"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ensureEnvironmentExists(ctx context.Context, fissionClient *client.Client, namespace, name string) error {
|
||||||
|
_, err := fissionClient.GetEnvironment(ctx, namespace, name)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("environment %q не найден в namespace %q: %w", name, namespace, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensurePackageExists(ctx context.Context, fissionClient *client.Client, namespace, name string) (*unstructured.Unstructured, error) {
|
||||||
|
pkg, err := fissionClient.GetPackage(ctx, namespace, name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("package %q не найден в namespace %q: %w", name, namespace, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return pkg, nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user