diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..5dfb05a --- /dev/null +++ b/.github/copilot-instructions.md @@ -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 'КОМАНДА' + ``` diff --git a/.github/pravila.md b/.github/pravila.md new file mode 100644 index 0000000..be15fff --- /dev/null +++ b/.github/pravila.md @@ -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` и др.) — только после явного подтверждения с указанием конкретных объектов +- Отвечать кратко, без вступлений, извинений, благодарностей и прочей воды diff --git a/.gitignore b/.gitignore index f0ed2c9..7fc6f93 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,10 @@ bin/ *.test *.out +# Compiled function binaries (generated, not versioned) +examples/*/dist/ + # Provider binaries terraform-provider-fission terraform-provider-fission_* +console/fission-console diff --git a/console/Dockerfile b/console/Dockerfile new file mode 100644 index 0000000..a8491c9 --- /dev/null +++ b/console/Dockerfile @@ -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"] diff --git a/console/deploy/console.yaml b/console/deploy/console.yaml new file mode 100644 index 0000000..4c60eac --- /dev/null +++ b/console/deploy/console.yaml @@ -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 diff --git a/console/go.mod b/console/go.mod new file mode 100644 index 0000000..e531983 --- /dev/null +++ b/console/go.mod @@ -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 +) diff --git a/console/go.sum b/console/go.sum new file mode 100644 index 0000000..778ac55 --- /dev/null +++ b/console/go.sum @@ -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= diff --git a/console/main.go b/console/main.go new file mode 100644 index 0000000..d60fd97 --- /dev/null +++ b/console/main.go @@ -0,0 +1,1102 @@ +package main + +import ( + "archive/zip" + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "os" + "sort" + "strings" + "sync" + "time" + "unicode/utf8" + + "fission-console/ui" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" +) + +var ( + environmentGVR = schema.GroupVersionResource{Group: "fission.io", Version: "v1", Resource: "environments"} + packageGVR = schema.GroupVersionResource{Group: "fission.io", Version: "v1", Resource: "packages"} + functionGVR = schema.GroupVersionResource{Group: "fission.io", Version: "v1", Resource: "functions"} + httpTrigGVR = schema.GroupVersionResource{Group: "fission.io", Version: "v1", Resource: "httptriggers"} + timeTrigGVR = schema.GroupVersionResource{Group: "fission.io", Version: "v1", Resource: "timetriggers"} +) + +const defaultSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token" + +var deckAPIs = map[string]string{ + "prod": "https://deck-api.ngcloud.ru/api/v1", + "dev": "https://deck-api-dev.ngcloud.ru/api/v1", + "test": "https://deck-api-test.ngcloud.ru/api/v1", +} + +type server struct { + dyn dynamic.Interface + ns string + routerURL string + http *http.Client + saTokenPath string + invokeTimeout time.Duration + + authUser string + authPass string + + tokenMu sync.Mutex + cachedJWT string + tokenExpAt time.Time + tokenCache sync.Map +} + +type createFunctionRequest struct { + Name string `json:"name"` + Language string `json:"language"` + Environment string `json:"environment"` + Code string `json:"code"` + Entrypoint string `json:"entrypoint"` + Route string `json:"route"` + Methods []string `json:"methods"` +} + +type langEnvDef struct { + Image string + BuilderImage string +} + +var langEnvMap = map[string]langEnvDef{ + "python": {Image: "ghcr.io/fission/python-env"}, + "nodejs": {Image: "ghcr.io/fission/node-env"}, + "go": {Image: "ghcr.io/fission/go-env", BuilderImage: "ghcr.io/fission/go-builder"}, + "php": {Image: "ghcr.io/fission/php-env"}, + "ruby": {Image: "ghcr.io/fission/ruby-env"}, + "perl": {Image: "ghcr.io/fission/perl-env"}, +} + +type updateCodeRequest struct { + Code string `json:"code"` +} + +func main() { + kubeconfig := strings.TrimSpace(os.Getenv("KUBECONFIG")) + namespace := envDefault("FISSION_NAMESPACE", "default") + routerURL := strings.TrimRight(envDefault("FISSION_ROUTER_URL", "http://router.fission.svc.cluster.local"), "/") + port := envDefault("PORT", "8090") + httpTimeout := envDurationDefault("FISSION_HTTP_TIMEOUT", 30*time.Second) + invokeTimeout := envDurationDefault("FISSION_INVOKE_TIMEOUT", 20*time.Second) + + cfg, err := buildConfig(kubeconfig) + if err != nil { + log.Fatalf("build kube config: %v", err) + } + + dyn, err := dynamic.NewForConfig(cfg) + if err != nil { + log.Fatalf("create dynamic client: %v", err) + } + + authUser := envDefault("FISSION_AUTH_USERNAME", "") + authPass := envDefault("FISSION_AUTH_PASSWORD", "") + saTokenPath := envDefault("SA_TOKEN_PATH", defaultSATokenPath) + + s := &server{ + dyn: dyn, + ns: namespace, + routerURL: routerURL, + http: &http.Client{Timeout: httpTimeout}, + saTokenPath: saTokenPath, + invokeTimeout: invokeTimeout, + authUser: authUser, + authPass: authPass, + } + + mux := http.NewServeMux() + mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = w.Write([]byte("ok\n")) + }) + mux.HandleFunc("/console/health", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + _, _ = w.Write([]byte("ok\n")) + }) + + uiHandler := http.StripPrefix("/console", ui.Handler()) + mux.Handle("/console", uiHandler) + mux.Handle("/console/", uiHandler) + + mux.HandleFunc("/api/environments", s.handleList(environmentGVR)) + mux.HandleFunc("/api/packages", s.handleList(packageGVR)) + mux.HandleFunc("/api/functions", s.handleFunctionsRoot) + mux.HandleFunc("/api/functions/", s.handleFunctionsAction) + mux.HandleFunc("/api/httptriggers", s.handleList(httpTrigGVR)) + mux.HandleFunc("/api/timetriggers", s.handleList(timeTrigGVR)) + + auth := func(h http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + token := strings.TrimSpace(r.Header.Get("X-Auth-Token")) + env := strings.TrimSpace(strings.ToLower(r.Header.Get("X-Auth-Env"))) + if _, ok := deckAPIs[env]; !ok { + env = "test" + } + if token == "" { + writeJSONError(w, http.StatusUnauthorized, "unauthorized") + return + } + if err := s.validateDeckToken(token, env); err != nil { + writeJSONError(w, http.StatusUnauthorized, "unauthorized") + return + } + h(w, r) + } + } + + mux.HandleFunc("/console/api/auth", s.handleAuth) + mux.HandleFunc("/console/api/environments", auth(s.handleList(environmentGVR))) + mux.HandleFunc("/console/api/packages", auth(s.handleList(packageGVR))) + mux.HandleFunc("/console/api/functions", auth(s.handleFunctionsRoot)) + mux.HandleFunc("/console/api/functions/", auth(s.handleFunctionsAction)) + mux.HandleFunc("/console/api/httptriggers", auth(s.handleList(httpTrigGVR))) + mux.HandleFunc("/console/api/timetriggers", auth(s.handleList(timeTrigGVR))) + + httpServer := &http.Server{ + Addr: ":" + port, + Handler: withSecurityHeaders(withCORS(logRequests(mux))), + ReadHeaderTimeout: 10 * time.Second, + } + + log.Printf("fission-console listening on :%s (namespace=%s)", port, namespace) + log.Fatal(httpServer.ListenAndServe()) +} + +func (s *server) handleFunctionsRoot(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + s.handleList(functionGVR)(w, r) + case http.MethodPost: + s.handleCreateFunction(w, r) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func (s *server) handleFunctionsAction(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.URL.Path, "/api/functions/") + if path == r.URL.Path { + path = strings.TrimPrefix(r.URL.Path, "/console/api/functions/") + } + path = strings.Trim(path, "/") + if path == "" { + http.NotFound(w, r) + return + } + + parts := strings.Split(path, "/") + name := strings.TrimSpace(parts[0]) + if name == "" { + writeJSONError(w, http.StatusBadRequest, "function name is required") + return + } + + if len(parts) == 1 { + switch r.Method { + case http.MethodGet: + s.handleGetFunction(w, r, name) + case http.MethodDelete: + s.handleDeleteFunction(w, r, name) + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } + return + } + + if len(parts) == 2 && parts[1] == "code" && r.Method == http.MethodPut { + s.handleUpdateFunctionCode(w, r, name) + return + } + + if len(parts) == 2 && parts[1] == "invoke" && r.Method == http.MethodPost { + s.handleInvokeFunction(w, r, name) + return + } + + http.NotFound(w, r) +} + +func (s *server) handleCreateFunction(w http.ResponseWriter, r *http.Request) { + var req createFunctionRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("decode request: %v", err)) + return + } + + req.Name = strings.TrimSpace(req.Name) + req.Language = strings.TrimSpace(req.Language) + req.Environment = strings.TrimSpace(req.Environment) + req.Code = strings.TrimSpace(req.Code) + req.Entrypoint = strings.TrimSpace(req.Entrypoint) + req.Route = strings.TrimSpace(req.Route) + + // Resolve language → environment (auto-create if needed) + if req.Language != "" { + langDef, ok := langEnvMap[req.Language] + if !ok { + writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("unsupported language: %q", req.Language)) + return + } + envName := "console-" + req.Language + "-env" + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + _, err := s.dyn.Resource(environmentGVR).Namespace(s.ns).Get(ctx, envName, metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + env := s.buildLangEnvironment(envName, langDef) + if _, err := s.dyn.Resource(environmentGVR).Namespace(s.ns).Create(ctx, env, metav1.CreateOptions{}); err != nil { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("create environment %q: %v", envName, err)) + return + } + } else if err != nil { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("check environment: %v", err)) + return + } + req.Environment = envName + } + + if req.Name == "" || req.Environment == "" || req.Code == "" { + writeJSONError(w, http.StatusBadRequest, "name, environment/language and code are required") + return + } + if req.Entrypoint == "" { + req.Entrypoint = "main.main" + } + if req.Route == "" { + req.Route = "/" + req.Name + } + if !strings.HasPrefix(req.Route, "/") { + req.Route = "/" + req.Route + } + req.Methods = normalizeMethods(req.Methods) + + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + + if _, err := s.dyn.Resource(environmentGVR).Namespace(s.ns).Get(ctx, req.Environment, metav1.GetOptions{}); err != nil { + writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("environment %q not found: %v", req.Environment, err)) + return + } + + pkgName := req.Name + "-pkg" + triggerName := req.Name + "-route" + methodValues := make([]any, 0, len(req.Methods)) + for _, method := range req.Methods { + methodValues = append(methodValues, method) + } + + // Build the package spec: Go uses source archive (builder), others use literal deployment + var pkgSpec map[string]any + if req.Language == "go" { + srcZip, err := s.buildGoSourceZip(req.Code) + if err != nil { + writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("build go source archive: %v", err)) + return + } + literal := base64.StdEncoding.EncodeToString(srcZip) + pkgSpec = map[string]any{ + "source": map[string]any{ + "type": "literal", + "literal": literal, + }, + "deployment": map[string]any{}, + "environment": map[string]any{ + "name": req.Environment, + "namespace": s.ns, + }, + "buildcommand": "build", + } + } else { + literal := base64.StdEncoding.EncodeToString([]byte(req.Code)) + pkgSpec = map[string]any{ + "deployment": map[string]any{ + "type": "literal", + "literal": literal, + }, + "environment": map[string]any{ + "name": req.Environment, + "namespace": s.ns, + }, + "source": map[string]any{}, + } + } + + pkg := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "fission.io/v1", + "kind": "Package", + "metadata": map[string]any{ + "name": pkgName, + "namespace": s.ns, + }, + "spec": pkgSpec, + }} + + if _, err := s.dyn.Resource(packageGVR).Namespace(s.ns).Create(ctx, pkg, metav1.CreateOptions{}); err != nil { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("create package: %v", err)) + return + } + + fn := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "fission.io/v1", + "kind": "Function", + "metadata": map[string]any{ + "name": req.Name, + "namespace": s.ns, + }, + "spec": map[string]any{ + "environment": map[string]any{ + "name": req.Environment, + "namespace": s.ns, + }, + "InvokeStrategy": map[string]any{ + "ExecutionStrategy": map[string]any{"ExecutorType": "poolmgr"}, + "StrategyType": "execution", + }, + "package": map[string]any{ + "packageref": map[string]any{"name": pkgName, "namespace": s.ns}, + "functionName": req.Entrypoint, + }, + }, + }} + + if _, err := s.dyn.Resource(functionGVR).Namespace(s.ns).Create(ctx, fn, metav1.CreateOptions{}); err != nil { + _ = s.dyn.Resource(packageGVR).Namespace(s.ns).Delete(ctx, pkgName, metav1.DeleteOptions{}) + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("create function: %v", err)) + return + } + + httpTrigger := &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "fission.io/v1", + "kind": "HTTPTrigger", + "metadata": map[string]any{ + "name": triggerName, + "namespace": s.ns, + }, + "spec": map[string]any{ + "relativeurl": req.Route, + "methods": methodValues, + "createingress": true, + "functionref": map[string]any{ + "type": "name", + "name": req.Name, + }, + }, + }} + + if _, err := s.dyn.Resource(httpTrigGVR).Namespace(s.ns).Create(ctx, httpTrigger, metav1.CreateOptions{}); err != nil { + _ = s.dyn.Resource(functionGVR).Namespace(s.ns).Delete(ctx, req.Name, metav1.DeleteOptions{}) + _ = s.dyn.Resource(packageGVR).Namespace(s.ns).Delete(ctx, pkgName, metav1.DeleteOptions{}) + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("create httptrigger: %v", err)) + return + } + + writeAnyJSON(w, http.StatusCreated, map[string]any{ + "name": req.Name, + "package": pkgName, + "httptrigger": triggerName, + "route": req.Route, + }) +} + +func (s *server) buildLangEnvironment(name string, def langEnvDef) *unstructured.Unstructured { + spec := map[string]any{ + "version": int64(3), + "runtime": map[string]any{ + "image": def.Image, + }, + "poolsize": int64(1), + } + if def.BuilderImage != "" { + spec["builder"] = map[string]any{ + "image": def.BuilderImage, + "command": "build", + } + } + return &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "fission.io/v1", + "kind": "Environment", + "metadata": map[string]any{ + "name": name, + "namespace": s.ns, + }, + "spec": spec, + }} +} + +func (s *server) buildGoSourceZip(code string) ([]byte, error) { + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + + fw, err := zw.Create("handler.go") + if err != nil { + return nil, err + } + if _, err := fw.Write([]byte(code)); err != nil { + return nil, err + } + + goMod := "module github.com/user/fn\n\ngo 1.23\n" + fw2, err := zw.Create("go.mod") + if err != nil { + return nil, err + } + if _, err := fw2.Write([]byte(goMod)); err != nil { + return nil, err + } + + if err := zw.Close(); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func (s *server) handleGetFunction(w http.ResponseWriter, r *http.Request, name string) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + + fn, err := s.dyn.Resource(functionGVR).Namespace(s.ns).Get(ctx, name, metav1.GetOptions{}) + if err != nil { + status := http.StatusBadGateway + if apierrors.IsNotFound(err) { + status = http.StatusNotFound + } + writeJSONError(w, status, fmt.Sprintf("get function %q: %v", name, err)) + return + } + + packageName, _, _ := unstructured.NestedString(fn.Object, "spec", "package", "packageref", "name") + environment, _, _ := unstructured.NestedString(fn.Object, "spec", "environment", "name") + entrypoint, _, _ := unstructured.NestedString(fn.Object, "spec", "package", "functionName") + + code := "" + if packageName != "" { + pkg, pkgErr := s.dyn.Resource(packageGVR).Namespace(s.ns).Get(ctx, packageName, metav1.GetOptions{}) + if pkgErr == nil { + code = s.extractPackageSourceCode(ctx, pkg) + } + } + + route := "" + methods := []string{} + triggers, trigErr := s.dyn.Resource(httpTrigGVR).Namespace(s.ns).List(ctx, metav1.ListOptions{}) + if trigErr == nil { + for _, trig := range triggers.Items { + refName, _, _ := unstructured.NestedString(trig.Object, "spec", "functionref", "name") + if refName != name { + continue + } + route, _, _ = unstructured.NestedString(trig.Object, "spec", "relativeurl") + methods, _, _ = unstructured.NestedStringSlice(trig.Object, "spec", "methods") + break + } + } + + writeAnyJSON(w, http.StatusOK, map[string]any{ + "name": name, + "namespace": s.ns, + "environment": environment, + "package": packageName, + "entrypoint": entrypoint, + "code": code, + "route": route, + "methods": methods, + "raw": fn.Object, + }) +} + +func (s *server) handleUpdateFunctionCode(w http.ResponseWriter, r *http.Request, name string) { + var req updateCodeRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("decode request: %v", err)) + return + } + req.Code = strings.TrimSpace(req.Code) + if req.Code == "" { + writeJSONError(w, http.StatusBadRequest, "code is required") + return + } + + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + + fn, err := s.dyn.Resource(functionGVR).Namespace(s.ns).Get(ctx, name, metav1.GetOptions{}) + if err != nil { + status := http.StatusBadGateway + if apierrors.IsNotFound(err) { + status = http.StatusNotFound + } + writeJSONError(w, status, fmt.Sprintf("get function %q: %v", name, err)) + return + } + + pkgName, _, _ := unstructured.NestedString(fn.Object, "spec", "package", "packageref", "name") + if pkgName == "" { + writeJSONError(w, http.StatusBadGateway, "function has no package reference") + return + } + + pkg, err := s.dyn.Resource(packageGVR).Namespace(s.ns).Get(ctx, pkgName, metav1.GetOptions{}) + if err != nil { + status := http.StatusBadGateway + if apierrors.IsNotFound(err) { + status = http.StatusNotFound + } + writeJSONError(w, status, fmt.Sprintf("get package %q: %v", pkgName, err)) + return + } + + literal := base64.StdEncoding.EncodeToString([]byte(req.Code)) + if err := unstructured.SetNestedField(pkg.Object, literal, "spec", "deployment", "literal"); err != nil { + writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("set package literal: %v", err)) + return + } + + if _, err := s.dyn.Resource(packageGVR).Namespace(s.ns).Update(ctx, pkg, metav1.UpdateOptions{}); err != nil { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("update package %q: %v", pkgName, err)) + return + } + + updatedPkg, err := s.dyn.Resource(packageGVR).Namespace(s.ns).Get(ctx, pkgName, metav1.GetOptions{}) + if err != nil { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("get updated package %q: %v", pkgName, err)) + return + } + + if err := unstructured.SetNestedField(fn.Object, updatedPkg.GetResourceVersion(), "spec", "package", "packageref", "resourceversion"); err != nil { + writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("set function package resourceversion: %v", err)) + return + } + + if _, err := s.dyn.Resource(functionGVR).Namespace(s.ns).Update(ctx, fn, metav1.UpdateOptions{}); err != nil { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("update function %q package ref: %v", name, err)) + return + } + + writeAnyJSON(w, http.StatusOK, map[string]any{"updated": true, "package": pkgName, "package_resourceversion": updatedPkg.GetResourceVersion()}) +} + +func (s *server) handleInvokeFunction(w http.ResponseWriter, r *http.Request, name string) { + bodyBytes, err := io.ReadAll(r.Body) + if err != nil { + writeJSONError(w, http.StatusBadRequest, fmt.Sprintf("read request body: %v", err)) + return + } + if len(bytes.TrimSpace(bodyBytes)) == 0 { + bodyBytes = []byte("{}") + } + + invokeTimeout := s.invokeTimeout + if invokeTimeout <= 0 { + invokeTimeout = 20 * time.Second + } + + ctx, cancel := context.WithTimeout(r.Context(), invokeTimeout) + defer cancel() + + invokeURL := fmt.Sprintf("%s/fission-function/v2/functions/%s", s.routerURL, name) + invokeMethod := http.MethodPost + triggers, err := s.dyn.Resource(httpTrigGVR).Namespace(s.ns).List(ctx, metav1.ListOptions{}) + if err == nil { + for _, trig := range triggers.Items { + refName, _, _ := unstructured.NestedString(trig.Object, "spec", "functionref", "name") + if refName != name { + continue + } + route, _, _ := unstructured.NestedString(trig.Object, "spec", "relativeurl") + methods, _, _ := unstructured.NestedStringSlice(trig.Object, "spec", "methods") + hasPost := false + hasGet := false + for _, method := range methods { + m := strings.ToUpper(strings.TrimSpace(method)) + if m == http.MethodPost { + hasPost = true + } + if m == http.MethodGet { + hasGet = true + } + } + if route != "" { + if !strings.HasPrefix(route, "/") { + route = "/" + route + } + invokeURL = s.routerURL + route + if !hasPost && hasGet { + invokeMethod = http.MethodGet + } + break + } + } + } + + start := time.Now() + var invokeBody io.Reader + if invokeMethod == http.MethodPost { + invokeBody = bytes.NewReader(bodyBytes) + } + req, err := http.NewRequestWithContext(ctx, invokeMethod, invokeURL, invokeBody) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build invoke request: %v", err)) + return + } + if invokeMethod == http.MethodPost { + req.Header.Set("Content-Type", "application/json") + } + if token := s.getRouterToken(); token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + + resp, err := s.http.Do(req) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("invoke %q timeout after %s: function specialization likely failed (for example, syntax error)", name, invokeTimeout)) + return + } + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("invoke %q timeout after %s: function specialization likely failed (for example, syntax error)", name, invokeTimeout)) + return + } + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("invoke %q: %v", name, err)) + return + } + defer resp.Body.Close() + + respBody, _ := io.ReadAll(resp.Body) + writeAnyJSON(w, http.StatusOK, map[string]any{ + "status": resp.StatusCode, + "latency_ms": time.Since(start).Milliseconds(), + "invoke_url": invokeURL, + "response_raw": string(respBody), + }) +} + +func (s *server) readSAToken() string { + if s.saTokenPath == "" { + return "" + } + data, err := os.ReadFile(s.saTokenPath) + if err != nil { + return "" + } + return strings.TrimSpace(string(data)) +} + +func (s *server) getRouterToken() string { + if s.authUser == "" || s.authPass == "" { + return s.readSAToken() + } + + s.tokenMu.Lock() + defer s.tokenMu.Unlock() + + if s.cachedJWT != "" && time.Now().Before(s.tokenExpAt) { + return s.cachedJWT + } + + loginURL := s.routerURL + "/auth/login" + body, _ := json.Marshal(map[string]string{"username": s.authUser, "password": s.authPass}) + resp, err := s.http.Post(loginURL, "application/json", bytes.NewReader(body)) + if err != nil { + log.Printf("router login failed: %v", err) + return s.readSAToken() + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { + respBody, _ := io.ReadAll(resp.Body) + log.Printf("router login %d: %s", resp.StatusCode, string(respBody)) + return s.readSAToken() + } + + var result struct { + AccessToken string `json:"accesstoken"` + } + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil || result.AccessToken == "" { + log.Printf("router login decode error: %v", err) + return s.readSAToken() + } + + s.cachedJWT = result.AccessToken + s.tokenExpAt = time.Now().Add(100 * time.Second) + log.Printf("router JWT obtained, expires in 100s") + return s.cachedJWT +} + +func (s *server) validateDeckToken(token, env string) error { + cacheKey := env + ":" + token + if v, ok := s.tokenCache.Load(cacheKey); ok { + if time.Now().Before(v.(time.Time)) { + return nil + } + s.tokenCache.Delete(cacheKey) + } + apiBase, ok := deckAPIs[env] + if !ok { + return fmt.Errorf("unknown env: %s", env) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/index.cfm/instances", nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+token) + resp, err := s.http.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + _, _ = io.ReadAll(resp.Body) + if resp.StatusCode == http.StatusUnauthorized { + return fmt.Errorf("invalid token") + } + s.tokenCache.Store(cacheKey, time.Now().Add(5*time.Minute)) + return nil +} + +func (s *server) handleAuth(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed") + return + } + var body struct { + Token string `json:"token"` + Env string `json:"env"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil || strings.TrimSpace(body.Token) == "" { + writeJSONError(w, http.StatusBadRequest, "token required") + return + } + env := strings.TrimSpace(strings.ToLower(body.Env)) + if _, ok := deckAPIs[env]; !ok { + env = "test" + } + if err := s.validateDeckToken(body.Token, env); err != nil { + writeJSONError(w, http.StatusUnauthorized, "invalid token") + return + } + w.Header().Set("Content-Type", "application/json; charset=utf-8") + _ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "env": env}) +} + +func (s *server) handleDeleteFunction(w http.ResponseWriter, r *http.Request, name string) { + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + + var pkgName string + fn, err := s.dyn.Resource(functionGVR).Namespace(s.ns).Get(ctx, name, metav1.GetOptions{}) + if err == nil { + pkgName, _, _ = unstructured.NestedString(fn.Object, "spec", "package", "packageref", "name") + } + + triggers, err := s.dyn.Resource(httpTrigGVR).Namespace(s.ns).List(ctx, metav1.ListOptions{}) + if err == nil { + for _, trig := range triggers.Items { + refName, _, _ := unstructured.NestedString(trig.Object, "spec", "functionref", "name") + if refName == name { + _ = s.dyn.Resource(httpTrigGVR).Namespace(s.ns).Delete(ctx, trig.GetName(), metav1.DeleteOptions{}) + } + } + } + + if err := s.dyn.Resource(functionGVR).Namespace(s.ns).Delete(ctx, name, metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("delete function %q: %v", name, err)) + return + } + + if pkgName != "" { + if err := s.dyn.Resource(packageGVR).Namespace(s.ns).Delete(ctx, pkgName, metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("delete package %q: %v", pkgName, err)) + return + } + } + + writeAnyJSON(w, http.StatusOK, map[string]any{"deleted": true, "name": name, "package": pkgName}) +} + +func buildConfig(kubeconfig string) (*rest.Config, error) { + if kubeconfig != "" { + cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err == nil { + return cfg, nil + } + return nil, fmt.Errorf("kubeconfig %s: %w", kubeconfig, err) + } + + cfg, err := rest.InClusterConfig() + if err == nil { + return cfg, nil + } + + loadingRules := &clientcmd.ClientConfigLoadingRules{} + clientCfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{}) + return clientCfg.ClientConfig() +} + +func (s *server) handleList(gvr schema.GroupVersionResource) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + + list, err := s.dyn.Resource(gvr).Namespace(s.ns).List(ctx, metav1.ListOptions{}) + if err != nil { + writeJSONError(w, http.StatusBadGateway, fmt.Sprintf("list %s: %v", gvr.Resource, err)) + return + } + + writeJSON(w, http.StatusOK, list.Items) + } +} + +func writeJSON(w http.ResponseWriter, status int, data []unstructured.Unstructured) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(data) +} + +func writeAnyJSON(w http.ResponseWriter, status int, data any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(data) +} + +func writeJSONError(w http.ResponseWriter, status int, msg string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{"error": msg}) +} + +func logRequests(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + log.Printf("%s %s", r.Method, r.URL.Path) + next.ServeHTTP(w, r) + }) +} + +func withCORS(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Auth-Token, X-Auth-Env") + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + next.ServeHTTP(w, r) + }) +} + +func withSecurityHeaders(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") + w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") + w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self' data:; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests; block-all-mixed-content") + next.ServeHTTP(w, r) + }) +} + +func envDefault(key, fallback string) string { + if v := strings.TrimSpace(os.Getenv(key)); v != "" { + return v + } + return fallback +} + +func envDurationDefault(key string, fallback time.Duration) time.Duration { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return fallback + } + d, err := time.ParseDuration(raw) + if err != nil || d <= 0 { + log.Printf("invalid duration for %s=%q, using default %s", key, raw, fallback) + return fallback + } + return d +} + +func normalizeMethods(in []string) []string { + if len(in) == 0 { + return []string{"GET"} + } + out := make([]string, 0, len(in)) + seen := map[string]bool{} + for _, method := range in { + m := strings.ToUpper(strings.TrimSpace(method)) + if m == "" || seen[m] { + continue + } + seen[m] = true + out = append(out, m) + } + if len(out) == 0 { + return []string{"GET"} + } + return out +} + +func (s *server) extractPackageSourceCode(ctx context.Context, pkg *unstructured.Unstructured) string { + literalPaths := [][]string{ + {"spec", "source", "literal"}, + {"spec", "deployment", "literal"}, + } + for _, p := range literalPaths { + literal, found, _ := unstructured.NestedString(pkg.Object, p...) + if !found || strings.TrimSpace(literal) == "" { + continue + } + if decodedCode, decErr := decodeLiteralToSource(literal); decErr == nil && strings.TrimSpace(decodedCode) != "" { + return decodedCode + } + } + + urlPaths := [][]string{ + {"spec", "source", "url"}, + {"spec", "deployment", "url"}, + } + for _, p := range urlPaths { + urlValue, found, _ := unstructured.NestedString(pkg.Object, p...) + if !found || strings.TrimSpace(urlValue) == "" { + continue + } + + archiveBytes, fetchErr := s.fetchPackageArchive(ctx, urlValue) + if fetchErr != nil { + continue + } + + decodedCode, decErr := decodeArchiveBytesToSource(archiveBytes) + if decErr == nil && strings.TrimSpace(decodedCode) != "" { + return decodedCode + } + } + + return "" +} + +func (s *server) fetchPackageArchive(ctx context.Context, archiveURL string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, archiveURL, nil) + if err != nil { + return nil, err + } + + resp, err := s.http.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("archive request failed: %s", resp.Status) + } + + return io.ReadAll(resp.Body) +} + +func decodeLiteralToSource(literal string) (string, error) { + decoded, err := base64.StdEncoding.DecodeString(literal) + if err != nil { + return "", err + } + + return decodeArchiveBytesToSource(decoded) +} + +func decodeArchiveBytesToSource(decoded []byte) (string, error) { + if len(decoded) == 0 { + return "", fmt.Errorf("empty payload") + } + + if utf8.Valid(decoded) { + return string(decoded), nil + } + + if len(decoded) >= 4 && bytes.Equal(decoded[:4], []byte{'P', 'K', 3, 4}) { + if src, zipErr := decodeZipSource(decoded); zipErr == nil { + return src, nil + } + } + + return "", fmt.Errorf("payload does not contain utf-8 source") +} + +func decodeZipSource(zipBytes []byte) (string, error) { + reader, err := zip.NewReader(bytes.NewReader(zipBytes), int64(len(zipBytes))) + if err != nil { + return "", err + } + + preferred := []string{"main.py", "main.js", "main.go", "handler.go", "handler.js", "handler.py"} + for _, name := range preferred { + for _, file := range reader.File { + if strings.EqualFold(file.Name, name) { + content, readErr := readZipFile(file) + if readErr != nil { + return "", readErr + } + if utf8.Valid(content) { + return string(content), nil + } + } + } + } + + files := make([]*zip.File, 0, len(reader.File)) + for _, file := range reader.File { + if file.FileInfo().IsDir() { + continue + } + files = append(files, file) + } + sort.Slice(files, func(i, j int) bool { + return files[i].Name < files[j].Name + }) + + for _, file := range files { + content, readErr := readZipFile(file) + if readErr != nil { + continue + } + if utf8.Valid(content) { + return string(content), nil + } + } + + return "", fmt.Errorf("zip archive does not contain utf-8 source files") +} + +func readZipFile(file *zip.File) ([]byte, error) { + rc, err := file.Open() + if err != nil { + return nil, err + } + defer rc.Close() + + return io.ReadAll(rc) +} diff --git a/console/main_test.go b/console/main_test.go new file mode 100644 index 0000000..b8c0766 --- /dev/null +++ b/console/main_test.go @@ -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"]) + } +} diff --git a/console/ui/embed.go b/console/ui/embed.go new file mode 100644 index 0000000..20ef7f6 --- /dev/null +++ b/console/ui/embed.go @@ -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)) +} diff --git a/console/ui/index.html b/console/ui/index.html new file mode 100644 index 0000000..d97a62a --- /dev/null +++ b/console/ui/index.html @@ -0,0 +1,807 @@ + + + + + + NUBES Fission Console + + + + + + + + +
+
+
Окружения
-
+
Пакеты
-
+
Функции
-
+
HTTP-триггеры
-
+
Тайм-триггеры
-
+
+ +
+
+
Функции
+
Actions: view, edit code, invoke, delete
+
+ + + + + +
ИмяОкружениеПакетМаршрутМетодыДействия
+
+
Namespace: default. CRUD происходит напрямую через CRD Fission.
+
+
+ + + + + + + + + + diff --git a/doc/AUDIT_PROVIDER_VS_FISSION_2026-06-03.md b/doc/AUDIT_PROVIDER_VS_FISSION_2026-06-03.md new file mode 100644 index 0000000..51d95ab --- /dev/null +++ b/doc/AUDIT_PROVIDER_VS_FISSION_2026-06-03.md @@ -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. diff --git a/doc/CODEX_UI_PLAN.md b/doc/CODEX_UI_PLAN.md new file mode 100644 index 0000000..2b14dc9 --- /dev/null +++ b/doc/CODEX_UI_PLAN.md @@ -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) diff --git a/doc/PLAN_MULTI_LANGUAGE.md b/doc/PLAN_MULTI_LANGUAGE.md new file mode 100644 index 0000000..1c0a352 --- /dev/null +++ b/doc/PLAN_MULTI_LANGUAGE.md @@ -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 +&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 -c --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/ +``` diff --git a/doc/progress.md b/doc/progress.md index c889487..785ecb4 100644 --- a/doc/progress.md +++ b/doc/progress.md @@ -164,3 +164,345 @@ ### Следующий шаг - Добавить отдельные 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` + - обновлен `` на `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">`. diff --git a/doc/test-auth-v0.5.0-2026-04-19.md b/doc/test-auth-v0.5.0-2026-04-19.md new file mode 100644 index 0000000..a105414 --- /dev/null +++ b/doc/test-auth-v0.5.0-2026-04-19.md @@ -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 токена. diff --git a/doc/thinking/2026-04-15-bug-report.md b/doc/thinking/2026-04-15-bug-report.md new file mode 100644 index 0000000..ce61566 --- /dev/null +++ b/doc/thinking/2026-04-15-bug-report.md @@ -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) diff --git a/doc/thinking/2026-04-15.md b/doc/thinking/2026-04-15.md new file mode 100644 index 0000000..9c6f250 --- /dev/null +++ b/doc/thinking/2026-04-15.md @@ -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` + - 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`. diff --git a/doc/thinking/2026-06-03-audit.md b/doc/thinking/2026-06-03-audit.md new file mode 100644 index 0000000..d43e407 --- /dev/null +++ b/doc/thinking/2026-06-03-audit.md @@ -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` diff --git a/examples/auto-funcs/code/bigdata/main.py b/examples/auto-funcs/code/bigdata/main.py new file mode 100644 index 0000000..1adb79f --- /dev/null +++ b/examples/auto-funcs/code/bigdata/main.py @@ -0,0 +1,5 @@ +def main(): + lines = [] + for i in range(500): + lines.append(f"line-{i}: {'x' * 80}") + return "\n".join(lines) diff --git a/examples/auto-funcs/code/chain/main.py b/examples/auto-funcs/code/chain/main.py new file mode 100644 index 0000000..f82e396 --- /dev/null +++ b/examples/auto-funcs/code/chain/main.py @@ -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) diff --git a/examples/auto-funcs/code/cpu.py b/examples/auto-funcs/code/cpu.py new file mode 100644 index 0000000..7ebb2a8 --- /dev/null +++ b/examples/auto-funcs/code/cpu.py @@ -0,0 +1,5 @@ +def main(): + s = 0 + for i in range(1, 100000): + s += (i * i) % 97 + return f"cpu-load:{s}" \ No newline at end of file diff --git a/examples/auto-funcs/code/cpu/main.py b/examples/auto-funcs/code/cpu/main.py new file mode 100644 index 0000000..a28b8cf --- /dev/null +++ b/examples/auto-funcs/code/cpu/main.py @@ -0,0 +1,5 @@ +def main(): + s = 0 + for i in range(1, 100000): + s += (i * i) % 97 + return f"cpu-load:{s}" diff --git a/examples/auto-funcs/code/echo.py b/examples/auto-funcs/code/echo.py new file mode 100644 index 0000000..94a2514 --- /dev/null +++ b/examples/auto-funcs/code/echo.py @@ -0,0 +1,4 @@ +def main(): + import os + msg = os.environ.get("FISSION_INPUT", "echo-default") + return f"echo:{msg}" \ No newline at end of file diff --git a/examples/auto-funcs/code/echo/main.py b/examples/auto-funcs/code/echo/main.py new file mode 100644 index 0000000..7148fce --- /dev/null +++ b/examples/auto-funcs/code/echo/main.py @@ -0,0 +1,5 @@ +import os + +def main(): + msg = os.environ.get("FISSION_INPUT", "echo-default") + return f"echo:{msg}" diff --git a/examples/auto-funcs/code/encoding/main.py b/examples/auto-funcs/code/encoding/main.py new file mode 100644 index 0000000..cac9723 --- /dev/null +++ b/examples/auto-funcs/code/encoding/main.py @@ -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}" diff --git a/examples/auto-funcs/code/error.py b/examples/auto-funcs/code/error.py new file mode 100644 index 0000000..b27585c --- /dev/null +++ b/examples/auto-funcs/code/error.py @@ -0,0 +1,2 @@ +def main(): + raise Exception("auto-error-test") \ No newline at end of file diff --git a/examples/auto-funcs/code/error/main.py b/examples/auto-funcs/code/error/main.py new file mode 100644 index 0000000..65f4f65 --- /dev/null +++ b/examples/auto-funcs/code/error/main.py @@ -0,0 +1,2 @@ +def main(): + raise Exception("auto-error-test") diff --git a/examples/auto-funcs/code/jsonout/main.py b/examples/auto-funcs/code/jsonout/main.py new file mode 100644 index 0000000..0b4260c --- /dev/null +++ b/examples/auto-funcs/code/jsonout/main.py @@ -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) diff --git a/examples/auto-funcs/code/math/main.py b/examples/auto-funcs/code/math/main.py new file mode 100644 index 0000000..a3d909e --- /dev/null +++ b/examples/auto-funcs/code/math/main.py @@ -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) diff --git a/examples/auto-funcs/code/memory/main.py b/examples/auto-funcs/code/memory/main.py new file mode 100644 index 0000000..c5332a6 --- /dev/null +++ b/examples/auto-funcs/code/memory/main.py @@ -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)}" diff --git a/examples/auto-funcs/code/multiline/main.py b/examples/auto-funcs/code/multiline/main.py new file mode 100644 index 0000000..df7554e --- /dev/null +++ b/examples/auto-funcs/code/multiline/main.py @@ -0,0 +1,5 @@ +def main(): + return """line1 +line2 +line3 +Конец (кириллица)""" diff --git a/examples/auto-funcs/code/nested/main.py b/examples/auto-funcs/code/nested/main.py new file mode 100644 index 0000000..404d41b --- /dev/null +++ b/examples/auto-funcs/code/nested/main.py @@ -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" diff --git a/examples/auto-funcs/code/ok.py b/examples/auto-funcs/code/ok.py new file mode 100644 index 0000000..0066b01 --- /dev/null +++ b/examples/auto-funcs/code/ok.py @@ -0,0 +1,2 @@ +def main(): + return "ok-auto-func" \ No newline at end of file diff --git a/examples/auto-funcs/code/ok/main.py b/examples/auto-funcs/code/ok/main.py new file mode 100644 index 0000000..1662884 --- /dev/null +++ b/examples/auto-funcs/code/ok/main.py @@ -0,0 +1,2 @@ +def main(): + return "ok-auto-func-UPDATED-v3-with-comment" diff --git a/examples/auto-funcs/code/recurse/main.py b/examples/auto-funcs/code/recurse/main.py new file mode 100644 index 0000000..ae3afcd --- /dev/null +++ b/examples/auto-funcs/code/recurse/main.py @@ -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}" diff --git a/examples/auto-funcs/code/slow.py b/examples/auto-funcs/code/slow.py new file mode 100644 index 0000000..46e3947 --- /dev/null +++ b/examples/auto-funcs/code/slow.py @@ -0,0 +1,4 @@ +import time +def main(): + time.sleep(2) + return "slow-done" \ No newline at end of file diff --git a/examples/auto-funcs/code/slow/main.py b/examples/auto-funcs/code/slow/main.py new file mode 100644 index 0000000..da21a0c --- /dev/null +++ b/examples/auto-funcs/code/slow/main.py @@ -0,0 +1,5 @@ +import time + +def main(): + time.sleep(2) + return "slow-done" diff --git a/examples/auto-funcs/code/timestamp/main.py b/examples/auto-funcs/code/timestamp/main.py new file mode 100644 index 0000000..379fca2 --- /dev/null +++ b/examples/auto-funcs/code/timestamp/main.py @@ -0,0 +1,5 @@ +import datetime + +def main(): + now = datetime.datetime.utcnow().isoformat() + return f"timestamp:{now}Z" diff --git a/examples/auto-funcs/main.tf b/examples/auto-funcs/main.tf new file mode 100644 index 0000000..61047d3 --- /dev/null +++ b/examples/auto-funcs/main.tf @@ -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"] +} diff --git a/examples/bad-entrypoint/code/main.py b/examples/bad-entrypoint/code/main.py new file mode 100644 index 0000000..0d97d74 --- /dev/null +++ b/examples/bad-entrypoint/code/main.py @@ -0,0 +1,5 @@ +def good_function(): + return "correct" + +def main(): + return "this is main" diff --git a/examples/bad-entrypoint/main.tf b/examples/bad-entrypoint/main.tf new file mode 100644 index 0000000..22fcd72 --- /dev/null +++ b/examples/bad-entrypoint/main.tf @@ -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 +} diff --git a/examples/deep-recursion/code/main.py b/examples/deep-recursion/code/main.py new file mode 100644 index 0000000..6cf6d29 --- /dev/null +++ b/examples/deep-recursion/code/main.py @@ -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)}" diff --git a/examples/deep-recursion/main.tf b/examples/deep-recursion/main.tf new file mode 100644 index 0000000..b8fc547 --- /dev/null +++ b/examples/deep-recursion/main.tf @@ -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"] +} diff --git a/examples/destroy-test/code/main.py b/examples/destroy-test/code/main.py new file mode 100644 index 0000000..282c218 --- /dev/null +++ b/examples/destroy-test/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "destroy-test-alive" diff --git a/examples/destroy-test/main.tf b/examples/destroy-test/main.tf new file mode 100644 index 0000000..b035ecd --- /dev/null +++ b/examples/destroy-test/main.tf @@ -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"] +} diff --git a/examples/env-stress-1/code/main.py b/examples/env-stress-1/code/main.py new file mode 100644 index 0000000..f0c9e06 --- /dev/null +++ b/examples/env-stress-1/code/main.py @@ -0,0 +1 @@ +def main(): return "env-1" diff --git a/examples/env-stress-2/code/main.py b/examples/env-stress-2/code/main.py new file mode 100644 index 0000000..b293647 --- /dev/null +++ b/examples/env-stress-2/code/main.py @@ -0,0 +1 @@ +def main(): return "env-2" diff --git a/examples/env-stress-3/code/main.py b/examples/env-stress-3/code/main.py new file mode 100644 index 0000000..3578e5e --- /dev/null +++ b/examples/env-stress-3/code/main.py @@ -0,0 +1 @@ +def main(): return "env-3" diff --git a/examples/env-stress-4/code/main.py b/examples/env-stress-4/code/main.py new file mode 100644 index 0000000..8ba370f --- /dev/null +++ b/examples/env-stress-4/code/main.py @@ -0,0 +1 @@ +def main(): return "env-4" diff --git a/examples/env-stress-5/code/main.py b/examples/env-stress-5/code/main.py new file mode 100644 index 0000000..f1c5f9c --- /dev/null +++ b/examples/env-stress-5/code/main.py @@ -0,0 +1 @@ +def main(): return "env-5" diff --git a/examples/frequent-update/code/main.py b/examples/frequent-update/code/main.py new file mode 100644 index 0000000..f30a426 --- /dev/null +++ b/examples/frequent-update/code/main.py @@ -0,0 +1 @@ +def main(): return "v10" diff --git a/examples/frequent-update/main.tf b/examples/frequent-update/main.tf new file mode 100644 index 0000000..562dbc1 --- /dev/null +++ b/examples/frequent-update/main.tf @@ -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"] +} diff --git a/examples/go-hello/code/go.mod b/examples/go-hello/code/go.mod new file mode 100644 index 0000000..cea403b --- /dev/null +++ b/examples/go-hello/code/go.mod @@ -0,0 +1,3 @@ +module github.com/user/fn + +go 1.23 diff --git a/examples/go-hello/code/handler.go b/examples/go-hello/code/handler.go new file mode 100644 index 0000000..659e6d5 --- /dev/null +++ b/examples/go-hello/code/handler.go @@ -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)") +} diff --git a/examples/go-hello/main.tf b/examples/go-hello/main.tf new file mode 100644 index 0000000..0d1fd89 --- /dev/null +++ b/examples/go-hello/main.tf @@ -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"] +} diff --git a/examples/invalid-manifest/code/main.py b/examples/invalid-manifest/code/main.py new file mode 100644 index 0000000..64d722b --- /dev/null +++ b/examples/invalid-manifest/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "test" diff --git a/examples/invalid-manifest/main.tf b/examples/invalid-manifest/main.tf new file mode 100644 index 0000000..e2de694 --- /dev/null +++ b/examples/invalid-manifest/main.tf @@ -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" +} diff --git a/examples/missing-ref/code/main.py b/examples/missing-ref/code/main.py new file mode 100644 index 0000000..64d722b --- /dev/null +++ b/examples/missing-ref/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "test" diff --git a/examples/missing-ref/main.tf b/examples/missing-ref/main.tf new file mode 100644 index 0000000..119bbfe --- /dev/null +++ b/examples/missing-ref/main.tf @@ -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" +} diff --git a/examples/multi-env-1/code/main.py b/examples/multi-env-1/code/main.py new file mode 100644 index 0000000..c0af74c --- /dev/null +++ b/examples/multi-env-1/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "env-1" diff --git a/examples/multi-env-1/main.tf b/examples/multi-env-1/main.tf new file mode 100644 index 0000000..5d8884e --- /dev/null +++ b/examples/multi-env-1/main.tf @@ -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"] +} diff --git a/examples/multi-env-2/code/main.py b/examples/multi-env-2/code/main.py new file mode 100644 index 0000000..28241dd --- /dev/null +++ b/examples/multi-env-2/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "env-2" diff --git a/examples/multi-env-2/main.tf b/examples/multi-env-2/main.tf new file mode 100644 index 0000000..70a5fb0 --- /dev/null +++ b/examples/multi-env-2/main.tf @@ -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"] +} diff --git a/examples/multi-env-3/code/main.py b/examples/multi-env-3/code/main.py new file mode 100644 index 0000000..4d8bd64 --- /dev/null +++ b/examples/multi-env-3/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "env-3" diff --git a/examples/multi-env-3/main.tf b/examples/multi-env-3/main.tf new file mode 100644 index 0000000..fe42331 --- /dev/null +++ b/examples/multi-env-3/main.tf @@ -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"] +} diff --git a/examples/neg-tests/bad-import/code/main.py b/examples/neg-tests/bad-import/code/main.py new file mode 100644 index 0000000..b5b5ff0 --- /dev/null +++ b/examples/neg-tests/bad-import/code/main.py @@ -0,0 +1,4 @@ +import nonexistent_module_xyz_12345 + +def main(): + return nonexistent_module_xyz_12345.do_something() diff --git a/examples/neg-tests/bad-import/main.tf b/examples/neg-tests/bad-import/main.tf new file mode 100644 index 0000000..1c2e4d2 --- /dev/null +++ b/examples/neg-tests/bad-import/main.tf @@ -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"] +} diff --git a/examples/neg-tests/name-conflict/main.tf b/examples/neg-tests/name-conflict/main.tf new file mode 100644 index 0000000..7b83e62 --- /dev/null +++ b/examples/neg-tests/name-conflict/main.tf @@ -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 +} diff --git a/examples/neg-tests/no-main/code/main.py b/examples/neg-tests/no-main/code/main.py new file mode 100644 index 0000000..59edbae --- /dev/null +++ b/examples/neg-tests/no-main/code/main.py @@ -0,0 +1,2 @@ +def not_main(): + return "there is no main() here, Fission will fail to invoke" diff --git a/examples/neg-tests/no-main/main.tf b/examples/neg-tests/no-main/main.tf new file mode 100644 index 0000000..19cf176 --- /dev/null +++ b/examples/neg-tests/no-main/main.tf @@ -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"] +} diff --git a/examples/neg-tests/runtime-error/code/main.py b/examples/neg-tests/runtime-error/code/main.py new file mode 100644 index 0000000..17b16d2 --- /dev/null +++ b/examples/neg-tests/runtime-error/code/main.py @@ -0,0 +1,3 @@ +def main(): + x = 1 / 0 + return f"result: {x}" diff --git a/examples/neg-tests/runtime-error/main.tf b/examples/neg-tests/runtime-error/main.tf new file mode 100644 index 0000000..6f6805a --- /dev/null +++ b/examples/neg-tests/runtime-error/main.tf @@ -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"] +} diff --git a/examples/neg-tests/syntax-error/code/main.py b/examples/neg-tests/syntax-error/code/main.py new file mode 100644 index 0000000..13c982a --- /dev/null +++ b/examples/neg-tests/syntax-error/code/main.py @@ -0,0 +1,2 @@ +def main(: + return "this should never work" diff --git a/examples/neg-tests/syntax-error/main.tf b/examples/neg-tests/syntax-error/main.tf new file mode 100644 index 0000000..6c6874a --- /dev/null +++ b/examples/neg-tests/syntax-error/main.tf @@ -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"] +} diff --git a/examples/orphan-test/code/main.py b/examples/orphan-test/code/main.py new file mode 100644 index 0000000..e8407a3 --- /dev/null +++ b/examples/orphan-test/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "orphan-test" diff --git a/examples/orphan-test/main.tf b/examples/orphan-test/main.tf new file mode 100644 index 0000000..1a620a7 --- /dev/null +++ b/examples/orphan-test/main.tf @@ -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"] +} diff --git a/examples/perl-hello/code/main.pl b/examples/perl-hello/code/main.pl new file mode 100644 index 0000000..e5e75e0 --- /dev/null +++ b/examples/perl-hello/code/main.pl @@ -0,0 +1,3 @@ +sub { + return "Hello from Perl in Fission"; +} diff --git a/examples/perl-hello/main.tf b/examples/perl-hello/main.tf new file mode 100644 index 0000000..4377028 --- /dev/null +++ b/examples/perl-hello/main.tf @@ -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"] +} diff --git a/examples/php-hello/code/main.php b/examples/php-hello/code/main.php new file mode 100644 index 0000000..e908e39 --- /dev/null +++ b/examples/php-hello/code/main.php @@ -0,0 +1,7 @@ +getBody()->write("Hello from PHP in Fission"); +} diff --git a/examples/php-hello/main.tf b/examples/php-hello/main.tf new file mode 100644 index 0000000..8cd779b --- /dev/null +++ b/examples/php-hello/main.tf @@ -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"] +} diff --git a/examples/ruby-hello/code/main.rb b/examples/ruby-hello/code/main.rb new file mode 100644 index 0000000..5d9be58 --- /dev/null +++ b/examples/ruby-hello/code/main.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +def handler + "Hello from Ruby in Fission" +end diff --git a/examples/ruby-hello/main.tf b/examples/ruby-hello/main.tf new file mode 100644 index 0000000..0e9859f --- /dev/null +++ b/examples/ruby-hello/main.tf @@ -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"] +} diff --git a/examples/validate-bad-entrypoint/code/main.py b/examples/validate-bad-entrypoint/code/main.py new file mode 100644 index 0000000..41f6d95 --- /dev/null +++ b/examples/validate-bad-entrypoint/code/main.py @@ -0,0 +1,2 @@ +def exists(): + return "x" diff --git a/examples/validate-bad-entrypoint/main.tf b/examples/validate-bad-entrypoint/main.tf new file mode 100644 index 0000000..8779a8e --- /dev/null +++ b/examples/validate-bad-entrypoint/main.tf @@ -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" +} diff --git a/examples/validate-missing-env/code/main.py b/examples/validate-missing-env/code/main.py new file mode 100644 index 0000000..8689aea --- /dev/null +++ b/examples/validate-missing-env/code/main.py @@ -0,0 +1,2 @@ +def main(): + return "x" diff --git a/examples/validate-missing-env/main.tf b/examples/validate-missing-env/main.tf new file mode 100644 index 0000000..16e50e3 --- /dev/null +++ b/examples/validate-missing-env/main.tf @@ -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" +} diff --git a/terraform/provider/internal/resources/environment_resource.go b/terraform/provider/internal/resources/environment_resource.go index 875329c..899e998 100644 --- a/terraform/provider/internal/resources/environment_resource.go +++ b/terraform/provider/internal/resources/environment_resource.go @@ -24,13 +24,15 @@ type EnvironmentResource struct { } type environmentResourceModel struct { - ID types.String `tfsdk:"id"` - Name types.String `tfsdk:"name"` - Image types.String `tfsdk:"image"` - Version types.Int64 `tfsdk:"version"` - PoolSize types.Int64 `tfsdk:"poolsize"` - Namespace types.String `tfsdk:"namespace"` - UID types.String `tfsdk:"uid"` + ID types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + Image types.String `tfsdk:"image"` + Version types.Int64 `tfsdk:"version"` + PoolSize types.Int64 `tfsdk:"poolsize"` + BuilderImage types.String `tfsdk:"builder_image"` + BuilderCommand types.String `tfsdk:"builder_command"` + Namespace types.String `tfsdk:"namespace"` + UID types.String `tfsdk:"uid"` } func NewEnvironmentResource() resource.Resource { @@ -68,6 +70,14 @@ func (r *EnvironmentResource) Schema(_ context.Context, _ resource.SchemaRequest Default: int64default.StaticInt64(3), 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{ Optional: true, Computed: true, @@ -216,6 +226,26 @@ func (r *EnvironmentResource) ImportState(ctx context.Context, req resource.Impo // environmentToUnstructured преобразует Terraform model в Kubernetes CRD payload. 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{}{ "apiVersion": "fission.io/v1", "kind": "Environment", @@ -223,13 +253,7 @@ func environmentToUnstructured(model environmentResourceModel, namespace string) "name": model.Name.ValueString(), "namespace": namespace, }, - "spec": map[string]interface{}{ - "version": model.Version.ValueInt64(), - "runtime": map[string]interface{}{ - "image": model.Image.ValueString(), - }, - "poolsize": model.PoolSize.ValueInt64(), - }, + "spec": spec, }} } @@ -238,6 +262,8 @@ func unstructuredToEnvironmentModel(environmentObject *unstructured.Unstructured imageValue, _, _ := unstructured.NestedString(environmentObject.Object, "spec", "runtime", "image") versionValue, _, _ := unstructured.NestedInt64(environmentObject.Object, "spec", "version") 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.Name = types.StringValue(environmentObject.GetName()) @@ -254,6 +280,12 @@ func unstructuredToEnvironmentModel(environmentObject *unstructured.Unstructured if poolsizeValue != 0 { state.PoolSize = types.Int64Value(poolsizeValue) } + if builderImage != "" { + state.BuilderImage = types.StringValue(builderImage) + } + if builderCommand != "" { + state.BuilderCommand = types.StringValue(builderCommand) + } return state } diff --git a/terraform/provider/internal/resources/environment_resource_test.go b/terraform/provider/internal/resources/environment_resource_test.go index 33ebb44..ab7f6c2 100644 --- a/terraform/provider/internal/resources/environment_resource_test.go +++ b/terraform/provider/internal/resources/environment_resource_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/hashicorp/terraform-plugin-framework/types" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) func TestEnvironmentToUnstructuredAndBack(t *testing.T) { @@ -33,3 +34,51 @@ func TestEnvironmentToUnstructuredAndBack(t *testing.T) { 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") + } +} diff --git a/terraform/provider/internal/resources/function_resource.go b/terraform/provider/internal/resources/function_resource.go index 952067b..a2abdd7 100644 --- a/terraform/provider/internal/resources/function_resource.go +++ b/terraform/provider/internal/resources/function_resource.go @@ -2,11 +2,14 @@ package resources import ( "context" + "encoding/base64" "fmt" + "strings" "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" "github.com/hashicorp/terraform-plugin-framework/types" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -24,13 +27,18 @@ type FunctionResource struct { // functionResourceModel описывает состояние terraform ресурса fission_function. type functionResourceModel struct { - ID types.String `tfsdk:"id"` - Name types.String `tfsdk:"name"` - Environment types.String `tfsdk:"environment"` - PackageName types.String `tfsdk:"package_name"` - Entrypoint types.String `tfsdk:"entrypoint"` - Namespace types.String `tfsdk:"namespace"` - UID types.String `tfsdk:"uid"` + ID types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + Environment types.String `tfsdk:"environment"` + PackageName types.String `tfsdk:"package_name"` + Entrypoint types.String `tfsdk:"entrypoint"` + ExecutorType types.String `tfsdk:"executor_type"` + 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 создает инстанс ресурса функции. @@ -67,6 +75,28 @@ func (r *FunctionResource) Schema(_ context.Context, _ resource.SchemaRequest, r Required: true, 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{ Optional: true, Computed: true, @@ -107,6 +137,22 @@ func (r *FunctionResource) Create(ctx context.Context, req resource.CreateReques } namespace := resolveNamespace(plan.Namespace, r.client.Namespace) + if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil { + resp.Diagnostics.AddError("Ошибка валидации Environment для Function", err.Error()) + return + } + + pkg, err := ensurePackageExists(ctx, r.client, namespace, plan.PackageName.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка валидации Package для Function", err.Error()) + return + } + + if err := validateEntrypointAgainstPackageSource(plan.Entrypoint.ValueString(), pkg); err != nil { + resp.Diagnostics.AddError("Ошибка валидации entrypoint", err.Error()) + return + } + functionObject := functionToUnstructured(plan, namespace) createdFunction, err := r.client.CreateFunction(ctx, functionObject) @@ -152,6 +198,22 @@ func (r *FunctionResource) Update(ctx context.Context, req resource.UpdateReques } namespace := resolveNamespace(plan.Namespace, r.client.Namespace) + if err := ensureEnvironmentExists(ctx, r.client, namespace, plan.Environment.ValueString()); err != nil { + resp.Diagnostics.AddError("Ошибка валидации Environment для Function", err.Error()) + return + } + + pkg, err := ensurePackageExists(ctx, r.client, namespace, plan.PackageName.ValueString()) + if err != nil { + resp.Diagnostics.AddError("Ошибка валидации Package для Function", err.Error()) + return + } + + if err := validateEntrypointAgainstPackageSource(plan.Entrypoint.ValueString(), pkg); err != nil { + resp.Diagnostics.AddError("Ошибка валидации entrypoint", err.Error()) + return + } + existingFunction, err := r.client.GetFunction(ctx, namespace, plan.Name.ValueString()) if err != nil { resp.Diagnostics.AddError("Ошибка получения Function перед обновлением", err.Error()) @@ -201,6 +263,46 @@ func (r *FunctionResource) ImportState(ctx context.Context, req resource.ImportS // functionToUnstructured преобразует Terraform model в Kubernetes CRD payload. 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{}{ "apiVersion": "fission.io/v1", "kind": "Function", @@ -208,25 +310,7 @@ func functionToUnstructured(model functionResourceModel, namespace string) *unst "name": model.Name.ValueString(), "namespace": namespace, }, - "spec": map[string]interface{}{ - "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(), - }, - }, + "spec": spec, }} } @@ -235,6 +319,11 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base environmentName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "environment", "name") packageName, _, _ := unstructured.NestedString(functionObject.Object, "spec", "package", "packageref", "name") 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.Name = types.StringValue(functionObject.GetName()) @@ -251,6 +340,72 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base if 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 } + +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 +} diff --git a/terraform/provider/internal/resources/function_resource_test.go b/terraform/provider/internal/resources/function_resource_test.go index 9256cfd..ac7b55f 100644 --- a/terraform/provider/internal/resources/function_resource_test.go +++ b/terraform/provider/internal/resources/function_resource_test.go @@ -1,6 +1,7 @@ package resources import ( + "encoding/base64" "testing" "github.com/hashicorp/terraform-plugin-framework/types" @@ -30,9 +31,93 @@ func TestFunctionToUnstructuredAndBack(t *testing.T) { if state.Entrypoint.ValueString() != "main.main" { 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") if err != nil || !found || len(invoke) == 0 { 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) + } +} diff --git a/terraform/provider/internal/resources/package_resource.go b/terraform/provider/internal/resources/package_resource.go index 5744a85..0fea3cc 100644 --- a/terraform/provider/internal/resources/package_resource.go +++ b/terraform/provider/internal/resources/package_resource.go @@ -1,9 +1,13 @@ package resources import ( + "archive/zip" + "bytes" "context" + "crypto/sha256" "encoding/base64" "fmt" + "io" "os" "path/filepath" @@ -11,6 +15,7 @@ import ( "github.com/hashicorp/terraform-plugin-framework/path" "github.com/hashicorp/terraform-plugin-framework/resource" "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault" "github.com/hashicorp/terraform-plugin-framework/types" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -19,6 +24,7 @@ import ( var _ resource.Resource = &PackageResource{} var _ resource.ResourceWithImportState = &PackageResource{} +var _ resource.ResourceWithModifyPlan = &PackageResource{} // Изменено: 2026-04-14 19:45 UTC. // Resource для управления Fission Package через Kubernetes CRD API. @@ -35,6 +41,7 @@ type packageResourceModel struct { CodePath types.String `tfsdk:"code_path"` CodeHash types.String `tfsdk:"code_hash"` BuildCmd types.String `tfsdk:"build_command"` + DeployType types.String `tfsdk:"deploy_type"` Namespace types.String `tfsdk:"namespace"` UID types.String `tfsdk:"uid"` BuildStatus types.String `tfsdk:"build_status"` @@ -69,7 +76,7 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re }, "source_dir": schema.StringAttribute{ 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{ Optional: true, @@ -77,12 +84,19 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re }, "code_hash": schema.StringAttribute{ Optional: true, + Computed: true, Description: "Произвольный хеш кода для контроля изменений.", }, "build_command": schema.StringAttribute{ Optional: true, 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{ Optional: 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(). func (r *PackageResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { if req.ProviderData == nil { @@ -135,12 +189,21 @@ func (r *PackageResource) Create(ctx context.Context, req resource.CreateRequest 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 { resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error()) return } + if !hasManualCodeHash(plan.CodeHash) { + plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes)) + } + packageObject := packageToUnstructured(plan, namespace, literalBytes) createdPackage, err := r.client.CreatePackage(ctx, packageObject) if err != nil { @@ -189,12 +252,21 @@ func (r *PackageResource) Update(ctx context.Context, req resource.UpdateRequest 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 { resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error()) return } + if !hasManualCodeHash(plan.CodeHash) { + plan.CodeHash = types.StringValue(calculateCodeHash(literalBytes)) + } + existingPackage, err := r.client.GetPackage(ctx, namespace, plan.Name.ValueString()) if err != nil { resp.Diagnostics.AddError("Ошибка получения Package перед обновлением", err.Error()) @@ -268,7 +340,7 @@ func resolveNamespace(resourceNamespace types.String, providerNamespace string) return namespace } -// loadPackageLiteral читает bytes для spec.deployment.literal. +// loadPackageLiteral читает bytes для literal deployment (один файл). func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) { if sourceDir != "" { mainFilePath, err := resolveMainSourceFile(sourceDir) @@ -292,9 +364,60 @@ func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) { 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. 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 { candidatePath := filepath.Join(sourceDir, candidate) 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. func packageToUnstructured(model packageResourceModel, namespace string, literalBytes []byte) *unstructured.Unstructured { 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{}{ "apiVersion": "fission.io/v1", "kind": "Package", @@ -317,21 +470,7 @@ func packageToUnstructured(model packageResourceModel, namespace string, literal "name": model.Name.ValueString(), "namespace": namespace, }, - "spec": map[string]interface{}{ - "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") + "spec": spec, } return &unstructured.Unstructured{Object: object} @@ -343,6 +482,8 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p buildCommand, _, _ := unstructured.NestedString(packageObject.Object, "spec", "buildcmd") buildStatus, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildstatus") buildLog, _, _ := unstructured.NestedString(packageObject.Object, "status", "buildlog") + deploymentLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "deployment", "literal") + sourceLiteral, _, _ := unstructured.NestedString(packageObject.Object, "spec", "source", "literal") state := packageResourceModel{ 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, CodeHash: base.CodeHash, BuildCmd: base.BuildCmd, + DeployType: base.DeployType, Namespace: types.StringValue(packageObject.GetNamespace()), UID: types.StringValue(string(packageObject.GetUID())), BuildStatus: types.StringNull(), @@ -371,5 +513,25 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p 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 } + +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) +} diff --git a/terraform/provider/internal/resources/package_resource_test.go b/terraform/provider/internal/resources/package_resource_test.go index 33d8d5d..906d19f 100644 --- a/terraform/provider/internal/resources/package_resource_test.go +++ b/terraform/provider/internal/resources/package_resource_test.go @@ -1,8 +1,12 @@ package resources import ( + "archive/zip" + "bytes" "context" + "crypto/sha256" "encoding/base64" + "fmt" "os" "path/filepath" "testing" @@ -102,6 +106,47 @@ func TestPackageToUnstructured(t *testing.T) { if string(decoded) != "print('hi')" { 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) { @@ -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) { obj := &unstructured.Unstructured{Object: map[string]interface{}{ "apiVersion": "fission.io/v1", @@ -167,3 +222,39 @@ func TestHTTPTriggerRoundTrip(t *testing.T) { 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") + } +} diff --git a/terraform/provider/internal/resources/validation_helpers.go b/terraform/provider/internal/resources/validation_helpers.go new file mode 100644 index 0000000..da0d1d3 --- /dev/null +++ b/terraform/provider/internal/resources/validation_helpers.go @@ -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 +}