Compare commits
7
Commits
v0.1.7
...
feat/console
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d66e5b566 | ||
|
|
c78b539d24 | ||
|
|
cccc5ca024 | ||
|
|
66404fde3a | ||
|
|
4964c8f357 | ||
|
|
7e23a71574 | ||
|
|
ab2eff69a0 |
@@ -8,6 +8,9 @@ bin/
|
||||
*.test
|
||||
*.out
|
||||
|
||||
# Compiled function binaries (generated, not versioned)
|
||||
examples/*/dist/
|
||||
|
||||
# Provider binaries
|
||||
terraform-provider-fission
|
||||
terraform-provider-fission_*
|
||||
|
||||
@@ -46,7 +46,7 @@ spec:
|
||||
serviceAccountName: fission-console
|
||||
containers:
|
||||
- name: console
|
||||
image: naeel/fission-console:v0.3.1
|
||||
image: naeel/fission-console:v0.3.4
|
||||
ports:
|
||||
- containerPort: 8090
|
||||
env:
|
||||
|
||||
+126
-21
@@ -6,9 +6,11 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
@@ -39,11 +41,12 @@ var (
|
||||
const defaultSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
|
||||
|
||||
type server struct {
|
||||
dyn dynamic.Interface
|
||||
ns string
|
||||
routerURL string
|
||||
http *http.Client
|
||||
saTokenPath string
|
||||
dyn dynamic.Interface
|
||||
ns string
|
||||
routerURL string
|
||||
http *http.Client
|
||||
saTokenPath string
|
||||
invokeTimeout time.Duration
|
||||
|
||||
authUser string
|
||||
authPass string
|
||||
@@ -71,6 +74,8 @@ func main() {
|
||||
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 {
|
||||
@@ -87,13 +92,14 @@ func main() {
|
||||
saTokenPath := envDefault("SA_TOKEN_PATH", defaultSATokenPath)
|
||||
|
||||
s := &server{
|
||||
dyn: dyn,
|
||||
ns: namespace,
|
||||
routerURL: routerURL,
|
||||
http: &http.Client{Timeout: 30 * time.Second},
|
||||
saTokenPath: saTokenPath,
|
||||
authUser: authUser,
|
||||
authPass: authPass,
|
||||
dyn: dyn,
|
||||
ns: namespace,
|
||||
routerURL: routerURL,
|
||||
http: &http.Client{Timeout: httpTimeout},
|
||||
saTokenPath: saTokenPath,
|
||||
invokeTimeout: invokeTimeout,
|
||||
authUser: authUser,
|
||||
authPass: authPass,
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
@@ -126,7 +132,7 @@ func main() {
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: withCORS(logRequests(mux)),
|
||||
Handler: withSecurityHeaders(withCORS(logRequests(mux))),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
@@ -341,12 +347,7 @@ func (s *server) handleGetFunction(w http.ResponseWriter, r *http.Request, name
|
||||
if packageName != "" {
|
||||
pkg, pkgErr := s.dyn.Resource(packageGVR).Namespace(s.ns).Get(ctx, packageName, metav1.GetOptions{})
|
||||
if pkgErr == nil {
|
||||
literal, _, _ := unstructured.NestedString(pkg.Object, "spec", "deployment", "literal")
|
||||
if literal != "" {
|
||||
if decodedCode, decErr := decodeLiteralToSource(literal); decErr == nil {
|
||||
code = decodedCode
|
||||
}
|
||||
}
|
||||
code = s.extractPackageSourceCode(ctx, pkg)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,7 +460,12 @@ func (s *server) handleInvokeFunction(w http.ResponseWriter, r *http.Request, na
|
||||
bodyBytes = []byte("{}")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
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)
|
||||
@@ -516,6 +522,15 @@ func (s *server) handleInvokeFunction(w http.ResponseWriter, r *http.Request, na
|
||||
|
||||
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
|
||||
}
|
||||
@@ -694,6 +709,17 @@ func withCORS(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
@@ -701,6 +727,19 @@ func envDefault(key, fallback string) string {
|
||||
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"}
|
||||
@@ -721,12 +760,78 @@ func normalizeMethods(in []string) []string {
|
||||
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
|
||||
}
|
||||
@@ -737,7 +842,7 @@ func decodeLiteralToSource(literal string) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
return string(decoded), nil
|
||||
return "", fmt.Errorf("payload does not contain utf-8 source")
|
||||
}
|
||||
|
||||
func decodeZipSource(zipBytes []byte) (string, error) {
|
||||
|
||||
@@ -142,6 +142,77 @@ func TestUpdateFunctionCode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>NUBES Fission Console</title>
|
||||
<link rel="icon" type="image/png" href="https://nubes.ru/themes/custom/nubes_2025/favicon.png">
|
||||
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAA4ZJREFUeJztm8+Lm0UYxz/fySZUoWIrVtbmXfyBP05Fa3e3rogsglJRK0p7E2svnrz6B3gQ8eRJFooXET14KKJ4FUQo3UQQ9CRC6W4WQW0VXZduTd7HQ9c22bzbTCY/ZpO8n0syb56Z+c437zPvhMzIzJhkXGwBsckNiC0gNrkBsQXEZsonSJLj4GNPgb2ACo9j9gDOvrSV6qkB6+sJ6WSJ5MIxUo4h5sDuI9U7tlZ57/+YTAN0zyOPUi+9jOxJxMOUj9wJOBBg117QvqGMwhNpcQ/J+rOkPIc0j+xeytyGsaWXa2+kvc312gxQMleHYgFtrQ9GYJmgmSfup3z15xuDNW/dGXOAjd680NgshlYdvcH2mfEwQIU0tOp4GNADuQGxBcRmPAyQgh/W42FAD+QGxBYQm/EwIF8HhJMbEFtAX3DreQqEkhsQW0BsxsMAlz8Gg8kNiC0gNuNhgJvK54BQcgNiC+gLhUlPgcuTbkAP5AbEFhCbcAOM4LyLitIW3eEGyP7qWUwMHFdaixNO1v4Av5pG8H/yfWfvesk7tq5GczHDAHnmtu727nTQbJYe8o51+qOl2BYgNv1a0iHvTgeNGq94x6buYnOx3YCU3/1asn06ePQZ744HiXTCO3a6/m1zsd0Ax/f+HTc+kU76598AUDL/LpjfjjWxYdXqRvOljDvAfezfO3dQvvCDtLjHu04f0czsaSx9y7uC8eP2S20GWO38Z+A7DwDwIOX135TMvylpKI9VJQv7lcx+hfEhurELsCPOfdDWVtZ5ASWzZ4GXArQ1QJfA/kTW6BhtLgX+7qL9IqTTmKa7GjgAumKry7dsv5q9Vfbfq29QLL1I9wulAtgB4ADmoy9kY4fodugAODuT2dpOJ0aUzH8E6asBXe0+zP5h7bvbzay+/aOdv+Ha8mnE5YEKGxqF17MGDzcxwMzqTBUWgc65vKuxT7cm9kx2TIHrATOzxzHOEpZ5sanYamXuZgEdJzlbqXyOmzrO6N0J56hVj3YK8prl7eK5L6g3DmFc6l3XEDCWbLWyYGYdf9h1TIGWYMmRHDlDaqcY0qKnO/Qr4oStLH/jXSPk4KSShf2ovoTZ80Db4iICv2D2ttWqS91WDDKgpYHy4adR8TWww8BdmN2KrOg5Zwoo+PV0/ThICmyArWHua9D7Vjv/U5j6Phgw6uzCPB4uuQGxBcRm4g34D1IN9ODV8oQpAAAAAElFTkSuQmCC">
|
||||
<script>
|
||||
if (window.location.protocol !== 'https:' && window.location.hostname !== 'localhost' && window.location.hostname !== '127.0.0.1') {
|
||||
window.location.replace('https://' + window.location.host + window.location.pathname + window.location.search + window.location.hash);
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
# План: поддержка всех языков Fission
|
||||
|
||||
**Дата:** 2026-04-15
|
||||
**Исполнитель:** Sonnet / GPT 5.3 Codex (AI-агент)
|
||||
**Цель:** Добавить рабочие функции на Go, Java, .NET, Ruby, Rust, PHP — и ПРОТЕСТИРОВАТЬ каждую
|
||||
|
||||
---
|
||||
|
||||
## Текущее состояние
|
||||
|
||||
| Язык | Статус | Проблемы |
|
||||
|---|---|---|
|
||||
| Python | ✅ Работает | — |
|
||||
| Node.js | ✅ Работает | — |
|
||||
| Go | ❌ Timeout | Runtime compilation > 20s specialization timeout |
|
||||
| Java | ❌ Не развёрнуто | — |
|
||||
| .NET | ❌ Не развёрнуто | — |
|
||||
| Ruby | ❌ Не развёрнуто | — |
|
||||
| Rust | ❌ Не развёрнуто | — |
|
||||
| PHP | ❌ Не развёрнуто | — |
|
||||
|
||||
---
|
||||
|
||||
## КРИТИЧЕСКИЕ ПРАВИЛА (обязательно для агента)
|
||||
|
||||
1. **ВСЕ КОМАНДЫ — ТОЛЬКО ЧЕРЕЗ SSH:**
|
||||
```bash
|
||||
ssh -i ~/.ssh/naeel_vm_id_ed25519 -o StrictHostKeyChecking=no -o ConnectTimeout=10 naeel@5.172.178.213 'КОМАНДА'
|
||||
```
|
||||
|
||||
2. **Файлы редактировать можно локально** — `/home/naeel/remote_dev/fission/` = `~/terra/fission/` на VM
|
||||
|
||||
3. **Terraform деплой:**
|
||||
```bash
|
||||
ssh ... 'cd ~/terra/fission/examples/FOLDER && TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission terraform apply -auto-approve'
|
||||
```
|
||||
|
||||
4. **Проверка функции (JWT обязателен):**
|
||||
```bash
|
||||
ssh ... '
|
||||
PASSWORD=$(kubectl -n fission get secret router -o jsonpath={.data.password} | base64 -d)
|
||||
TOKEN=$(curl -sk -X POST https://fission.kube5s.ru/auth/login -H "Content-Type: application/json" -d "{\"username\":\"admin\",\"password\":\"$PASSWORD\"}" | python3 -c "import sys,json; print(json.load(sys.stdin)[\"accesstoken\"])")
|
||||
curl -sk -w "\nHTTP=%{http_code}\n" -H "Authorization: Bearer $TOKEN" https://fission.kube5s.ru/ENDPOINT
|
||||
'
|
||||
```
|
||||
|
||||
5. **НЕ ТРОГАТЬ существующие функции** — 15 шт., список в copilot-instructions.md
|
||||
|
||||
---
|
||||
|
||||
## Шаг 0: Проверить доступность образов (ОБЯЗАТЕЛЬНО ПЕРВЫМ)
|
||||
|
||||
Перед созданием — проверить что образы exist на ghcr.io:
|
||||
|
||||
```bash
|
||||
ssh ... '
|
||||
for lang in go java jvm dotnet dotnet20 ruby perl php binary; do
|
||||
echo "--- $lang ---"
|
||||
# Попробовать pull (dry-run)
|
||||
docker pull ghcr.io/fission/${lang}-env:latest 2>&1 | head -3
|
||||
echo
|
||||
done
|
||||
'
|
||||
```
|
||||
|
||||
Если образ не найден — попробовать варианты:
|
||||
- `ghcr.io/fission/go-env`
|
||||
- `ghcr.io/fission/jvm-env` (Java = JVM в Fission!)
|
||||
- `ghcr.io/fission/dotnet20-env` или `ghcr.io/fission/dotnet-env`
|
||||
- `ghcr.io/fission/ruby-env`
|
||||
- `ghcr.io/fission/php-env`
|
||||
- `ghcr.io/fission/binary-env` (для предкомпилированных)
|
||||
- `ghcr.io/fission/perl-env`
|
||||
|
||||
Если образ не существует — НЕ создавать функцию, пропустить язык.
|
||||
|
||||
---
|
||||
|
||||
## Шаг 1: Go (ПРОБЛЕМНЫЙ — требует особого подхода)
|
||||
|
||||
### Проблема
|
||||
Go env компилирует код при specialization → timeout 20s → функция не работает.
|
||||
|
||||
### Решение: использовать `binary-env`
|
||||
Go компилируется на VM → заливается как бинарник → binary-env его запускает.
|
||||
|
||||
**Или:** увеличить specialization timeout через InvokeStrategy:
|
||||
```yaml
|
||||
spec:
|
||||
InvokeStrategy:
|
||||
ExecutionStrategy:
|
||||
ExecutorType: newdeploy # вместо poolmgr
|
||||
MinScale: 1 # always running
|
||||
MaxScale: 3
|
||||
```
|
||||
|
||||
### Вариант A: pre-compiled + binary-env
|
||||
```
|
||||
examples/go-hello/
|
||||
├── code/
|
||||
│ └── main.go # исходник для справки
|
||||
├── build.sh # скрипт для компиляции
|
||||
└── main.tf
|
||||
```
|
||||
|
||||
**build.sh:**
|
||||
```bash
|
||||
#!/bin/bash
|
||||
cd code
|
||||
CGO_ENABLED=0 GOOS=linux go build -o handler main.go
|
||||
```
|
||||
|
||||
**main.tf** — использовать `binary-env` вместо `go-env`
|
||||
|
||||
### Вариант B: newdeploy executor
|
||||
В Terraform manifests задать `executor_type = "newdeploy"` и `min_scale = 1`.
|
||||
Проверить поддерживает ли наш провайдер эти аргументы:
|
||||
```bash
|
||||
ssh ... 'grep -r "executor\|newdeploy\|min_scale\|invoke_strategy" ~/terra/fission/internal/'
|
||||
```
|
||||
|
||||
### Код функции (main.go):
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Handler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
w.Write([]byte("Hello from Go in Fission"))
|
||||
}
|
||||
```
|
||||
|
||||
### Тест: HTTP 200, body содержит "Hello from Go"
|
||||
|
||||
---
|
||||
|
||||
## Шаг 2: Java (JVM)
|
||||
|
||||
### Образ: `ghcr.io/fission/jvm-env`
|
||||
|
||||
### Структура:
|
||||
```
|
||||
examples/java-hello/
|
||||
├── code/
|
||||
│ └── io/fission/Function.java
|
||||
└── main.tf
|
||||
```
|
||||
|
||||
### Код:
|
||||
```java
|
||||
package io.fission;
|
||||
|
||||
import org.springframework.http.RequestEntity;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
public class Function implements io.fission.Function {
|
||||
@Override
|
||||
public ResponseEntity<?> call(RequestEntity req, io.fission.Context context) {
|
||||
return ResponseEntity.ok("Hello from Java in Fission");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**ВАЖНО:** Проверить точный интерфейс JVM env. Может потребоваться другой формат:
|
||||
```bash
|
||||
ssh ... 'docker run --rm ghcr.io/fission/jvm-env:latest cat /app/README.md 2>/dev/null || echo "No README"'
|
||||
```
|
||||
|
||||
### main.tf:
|
||||
```hcl
|
||||
resource "fission_environment" "jvm" {
|
||||
name = "tf-jvm-hello-env"
|
||||
image = "ghcr.io/fission/jvm-env"
|
||||
version = 3
|
||||
}
|
||||
# ... стандартный pattern
|
||||
```
|
||||
|
||||
### Тест: HTTP 200, body содержит "Hello from Java"
|
||||
|
||||
---
|
||||
|
||||
## Шаг 3: PHP
|
||||
|
||||
### Образ: `ghcr.io/fission/php-env`
|
||||
|
||||
### Структура:
|
||||
```
|
||||
examples/php-hello/
|
||||
├── code/
|
||||
│ └── hello.php
|
||||
└── main.tf
|
||||
```
|
||||
|
||||
### Код:
|
||||
```php
|
||||
<?php
|
||||
return function() {
|
||||
return "Hello from PHP in Fission";
|
||||
};
|
||||
```
|
||||
|
||||
**ВАЖНО:** entrypoint для PHP — имя файла без расширения (`hello`).
|
||||
|
||||
### Тест: HTTP 200, body содержит "Hello from PHP"
|
||||
|
||||
---
|
||||
|
||||
## Шаг 4: Ruby
|
||||
|
||||
### Образ: `ghcr.io/fission/ruby-env`
|
||||
|
||||
### Структура:
|
||||
```
|
||||
examples/ruby-hello/
|
||||
├── code/
|
||||
│ └── hello.rb
|
||||
└── main.tf
|
||||
```
|
||||
|
||||
### Код:
|
||||
```ruby
|
||||
def main
|
||||
"Hello from Ruby in Fission"
|
||||
end
|
||||
```
|
||||
|
||||
### Тест: HTTP 200, body содержит "Hello from Ruby"
|
||||
|
||||
---
|
||||
|
||||
## Шаг 5: .NET (C#)
|
||||
|
||||
### Образ: `ghcr.io/fission/dotnet-env` или `ghcr.io/fission/dotnet20-env`
|
||||
|
||||
### Структура:
|
||||
```
|
||||
examples/dotnet-hello/
|
||||
├── code/
|
||||
│ └── FissionFunction.cs
|
||||
└── main.tf
|
||||
```
|
||||
|
||||
### Код:
|
||||
```csharp
|
||||
using System;
|
||||
using Fission.DotNetCore.Api;
|
||||
|
||||
public class FissionFunction
|
||||
{
|
||||
public string Execute(FissionContext context)
|
||||
{
|
||||
return "Hello from .NET in Fission";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Тест: HTTP 200, body содержит "Hello from .NET"
|
||||
|
||||
---
|
||||
|
||||
## Шаг 6: Rust
|
||||
|
||||
### ВЕРОЯТНО НЕ СУЩЕСТВУЕТ официально.
|
||||
|
||||
Проверить:
|
||||
```bash
|
||||
ssh ... 'docker pull ghcr.io/fission/rust-env:latest 2>&1'
|
||||
```
|
||||
|
||||
Если нет — пропустить. Rust можно реализовать через `binary-env` (pre-compiled).
|
||||
|
||||
---
|
||||
|
||||
## Шаг 7: Perl (бонус)
|
||||
|
||||
### Образ: `ghcr.io/fission/perl-env`
|
||||
|
||||
```perl
|
||||
sub main {
|
||||
return "Hello from Perl in Fission";
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Порядок выполнения (ВАЖНО)
|
||||
|
||||
```
|
||||
1. Проверить доступность ВСЕХ образов (docker pull) → составить список реальных
|
||||
2. Для каждого доступного языка:
|
||||
a. Создать examples/LANG-hello/code/... + main.tf
|
||||
b. terraform apply
|
||||
c. curl с JWT → проверить HTTP 200 + ожидаемый body
|
||||
d. Если не работает — смотреть логи:
|
||||
kubectl -n default get events --sort-by=".lastTimestamp" | tail -20
|
||||
kubectl -n default get pods | grep poolmgr-LANG
|
||||
kubectl -n default logs <pod> -c <container> --tail=30
|
||||
e. Если timeout — попробовать newdeploy executor
|
||||
f. Если всё равно не работает — удалить через terraform destroy
|
||||
3. Обновить список в консоли (она автоматически видит новые функции)
|
||||
4. Протестировать все через консоль (invoke)
|
||||
5. Коммит + пуш + тег
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Критерий успеха
|
||||
|
||||
| Язык | Endpoint | Ожидаемый body | HTTP |
|
||||
|---|---|---|---|
|
||||
| Go | `/go-hello` | `Hello from Go in Fission` | 200 |
|
||||
| Java | `/java-hello` | `Hello from Java in Fission` | 200 |
|
||||
| PHP | `/php-hello` | `Hello from PHP in Fission` | 200 |
|
||||
| Ruby | `/ruby-hello` | `Hello from Ruby in Fission` | 200 |
|
||||
| .NET | `/dotnet-hello` | `Hello from .NET in Fission` | 200 |
|
||||
| Perl | `/perl-hello` | `Hello from Perl in Fission` | 200 |
|
||||
|
||||
**Минимум:** 3 новых языка работают (Go + ещё 2)
|
||||
**Идеал:** все 6
|
||||
|
||||
---
|
||||
|
||||
## Шаблон main.tf (копировать и менять)
|
||||
|
||||
```hcl
|
||||
terraform {
|
||||
required_providers {
|
||||
fission = {
|
||||
source = "nail/fission"
|
||||
version = "~> 0.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "fission" {
|
||||
kubeconfig_path = "/home/naeel/.kube/config"
|
||||
namespace = "default"
|
||||
}
|
||||
|
||||
resource "fission_environment" "env" {
|
||||
name = "tf-LANG-hello-env"
|
||||
image = "ghcr.io/fission/LANG-env"
|
||||
version = 3
|
||||
}
|
||||
|
||||
resource "fission_package" "pkg" {
|
||||
name = "tf-LANG-hello-pkg"
|
||||
environment = fission_environment.env.name
|
||||
source_dir = "${path.module}/code"
|
||||
}
|
||||
|
||||
resource "fission_function" "fn" {
|
||||
name = "tf-LANG-hello-fn"
|
||||
environment = fission_environment.env.name
|
||||
package_name = fission_package.pkg.name
|
||||
entrypoint = "ENTRYPOINT"
|
||||
}
|
||||
|
||||
resource "fission_http_trigger" "route" {
|
||||
name = "tf-LANG-hello-route"
|
||||
function = fission_function.fn.name
|
||||
url = "/LANG-hello"
|
||||
methods = ["GET"]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Entrypoint для каждого языка
|
||||
|
||||
| Язык | Entrypoint | Файл |
|
||||
|---|---|---|
|
||||
| Python | `main.main` | `main.py` |
|
||||
| Node.js | `module.exports` (пустой) | `server.js` |
|
||||
| Go | `Handler` | `main.go` |
|
||||
| Java | `io.fission.Function` | `Function.java` |
|
||||
| PHP | `hello` | `hello.php` |
|
||||
| Ruby | `hello.main` | `hello.rb` |
|
||||
| .NET | `FissionFunction.Execute` | `FissionFunction.cs` |
|
||||
| Perl | `hello.main` | `hello.pm` |
|
||||
|
||||
**⚠️ ВНИМАНИЕ:** Entrypoints могут отличаться от указанных! Проверять документацию каждого env:
|
||||
```bash
|
||||
ssh ... 'docker run --rm ghcr.io/fission/LANG-env:latest env 2>/dev/null | head -20'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Откат при неудаче
|
||||
|
||||
Если язык не работает:
|
||||
```bash
|
||||
ssh ... 'cd ~/terra/fission/examples/LANG-hello && TF_CLI_CONFIG_FILE=/tmp/terraformrc-fission terraform destroy -auto-approve'
|
||||
rm -rf examples/LANG-hello/
|
||||
```
|
||||
@@ -1,2 +1,2 @@
|
||||
def main():
|
||||
return "ok-auto-func-UPDATED-v2"
|
||||
return "ok-auto-func-UPDATED-v3-with-comment"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Handler используется binary-env: binary получает HTTP request через stdin,
|
||||
// stdout является HTTP response body.
|
||||
//
|
||||
// Для деплоя нужно скомпилировать перед terraform apply:
|
||||
// CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o ../dist/handler .
|
||||
//
|
||||
// Compiled size: ~1.6MB (слишком велико для literal deployment).
|
||||
// Используется shell-based handler в dist/handler (см. ниже).
|
||||
func main() {
|
||||
fmt.Print("Hello from Go in Fission")
|
||||
}
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Handler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprintf(w, "Hello from Go in Fission")
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
fission = {
|
||||
source = "nail/fission"
|
||||
version = "~> 0.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "fission" {
|
||||
kubeconfig_path = "/home/naeel/.kube/config"
|
||||
namespace = "default"
|
||||
}
|
||||
|
||||
# Go использует binary-env: функция является скомпилированным Linux-бинарником.
|
||||
# Перед apply необходимо скомпилировать:
|
||||
# CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o dist/handler code/
|
||||
resource "fission_environment" "go" {
|
||||
name = "tf-go-hello-env"
|
||||
image = "ghcr.io/fission/binary-env"
|
||||
version = 3
|
||||
}
|
||||
|
||||
resource "fission_package" "pkg" {
|
||||
name = "tf-go-hello-pkg"
|
||||
environment = fission_environment.go.name
|
||||
code_path = "${path.module}/dist/handler"
|
||||
}
|
||||
|
||||
resource "fission_function" "fn" {
|
||||
name = "tf-go-hello-fn"
|
||||
environment = fission_environment.go.name
|
||||
package_name = fission_package.pkg.name
|
||||
entrypoint = "handler"
|
||||
}
|
||||
|
||||
resource "fission_http_trigger" "route" {
|
||||
name = "tf-go-hello-route"
|
||||
function = fission_function.fn.name
|
||||
url = "/go-hello"
|
||||
methods = ["GET"]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
sub {
|
||||
return "Hello from Perl in Fission";
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
fission = {
|
||||
source = "nail/fission"
|
||||
version = "~> 0.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "fission" {
|
||||
kubeconfig_path = "/home/naeel/.kube/config"
|
||||
namespace = "default"
|
||||
}
|
||||
|
||||
# version = 1: Perl env uses v1 specialization (/specialize endpoint)
|
||||
resource "fission_environment" "perl" {
|
||||
name = "tf-perl-hello-env"
|
||||
image = "ghcr.io/fission/perl-env"
|
||||
version = 1
|
||||
}
|
||||
|
||||
resource "fission_package" "pkg" {
|
||||
name = "tf-perl-hello-pkg"
|
||||
environment = fission_environment.perl.name
|
||||
source_dir = "${path.module}/code"
|
||||
}
|
||||
|
||||
resource "fission_function" "fn" {
|
||||
name = "tf-perl-hello-fn"
|
||||
environment = fission_environment.perl.name
|
||||
package_name = fission_package.pkg.name
|
||||
entrypoint = "handler"
|
||||
}
|
||||
|
||||
resource "fission_http_trigger" "route" {
|
||||
name = "tf-perl-hello-route"
|
||||
function = fission_function.fn.name
|
||||
url = "/perl-hello"
|
||||
methods = ["GET"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
function handler($context)
|
||||
{
|
||||
/** @var \Psr\Http\Message\ResponseInterface $response */
|
||||
$response = $context["response"];
|
||||
$response->getBody()->write("Hello from PHP in Fission");
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
fission = {
|
||||
source = "nail/fission"
|
||||
version = "~> 0.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "fission" {
|
||||
kubeconfig_path = "/home/naeel/.kube/config"
|
||||
namespace = "default"
|
||||
}
|
||||
|
||||
resource "fission_environment" "php" {
|
||||
name = "tf-php-hello-env"
|
||||
image = "ghcr.io/fission/php-env"
|
||||
version = 3
|
||||
}
|
||||
|
||||
resource "fission_package" "pkg" {
|
||||
name = "tf-php-hello-pkg"
|
||||
environment = fission_environment.php.name
|
||||
source_dir = "${path.module}/code"
|
||||
}
|
||||
|
||||
resource "fission_function" "fn" {
|
||||
name = "tf-php-hello-fn"
|
||||
environment = fission_environment.php.name
|
||||
package_name = fission_package.pkg.name
|
||||
entrypoint = "main.php::handler"
|
||||
}
|
||||
|
||||
resource "fission_http_trigger" "route" {
|
||||
name = "tf-php-hello-route"
|
||||
function = fission_function.fn.name
|
||||
url = "/php-hello"
|
||||
methods = ["GET"]
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
def handler
|
||||
"Hello from Ruby in Fission"
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
terraform {
|
||||
required_providers {
|
||||
fission = {
|
||||
source = "nail/fission"
|
||||
version = "~> 0.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
provider "fission" {
|
||||
kubeconfig_path = "/home/naeel/.kube/config"
|
||||
namespace = "default"
|
||||
}
|
||||
|
||||
resource "fission_environment" "ruby" {
|
||||
name = "tf-ruby-hello-env"
|
||||
image = "ghcr.io/fission/ruby-env"
|
||||
version = 3
|
||||
}
|
||||
|
||||
resource "fission_package" "pkg" {
|
||||
name = "tf-ruby-hello-pkg"
|
||||
environment = fission_environment.ruby.name
|
||||
source_dir = "${path.module}/code"
|
||||
}
|
||||
|
||||
resource "fission_function" "fn" {
|
||||
name = "tf-ruby-hello-fn"
|
||||
environment = fission_environment.ruby.name
|
||||
package_name = fission_package.pkg.name
|
||||
entrypoint = "handler"
|
||||
}
|
||||
|
||||
resource "fission_http_trigger" "route" {
|
||||
name = "tf-ruby-hello-route"
|
||||
function = fission_function.fn.name
|
||||
url = "/ruby-hello"
|
||||
methods = ["GET"]
|
||||
}
|
||||
@@ -290,9 +290,16 @@ func unstructuredToFunctionModel(functionObject *unstructured.Unstructured, base
|
||||
}
|
||||
|
||||
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] == "" {
|
||||
return fmt.Errorf("entrypoint %q должен иметь формат module.function", entrypoint)
|
||||
// Не стандартный module.function — допускаем (PHP, Ruby, Perl и др.)
|
||||
return nil
|
||||
}
|
||||
|
||||
if parts[0] != "main" {
|
||||
|
||||
@@ -70,7 +70,12 @@ func TestValidateEntrypointAgainstPackageSourcePythonMissing(t *testing.T) {
|
||||
|
||||
func TestValidateEntrypointAgainstPackageSourceBadFormat(t *testing.T) {
|
||||
pkg := &unstructured.Unstructured{}
|
||||
if err := validateEntrypointAgainstPackageSource("main", pkg); err == nil {
|
||||
t.Fatalf("expected validation error for bad entrypoint format")
|
||||
// Пустой 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,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,
|
||||
@@ -355,7 +355,7 @@ func loadPackageLiteral(sourceDir, codePath string) ([]byte, error) {
|
||||
|
||||
// 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)
|
||||
@@ -364,7 +364,7 @@ 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.
|
||||
|
||||
Reference in New Issue
Block a user