snapshot before legacy cleanup

This commit is contained in:
Naeel
2026-04-27 07:36:06 +03:00
parent 9461026546
commit 7cfe20bf76
25 changed files with 1430 additions and 261 deletions
+1 -2
View File
@@ -22,7 +22,7 @@ import (
//
// Почему реальные линтеры, а не LLM:
// LLM часто "исправляет" валидный код и врёт о наличии ошибок.
// node --check / python3 -m py_compile / ruby -c / php -l / perl -c — детерминированы и надёжны.
// node --check / python3 -m py_compile / ruby -c / php -l — детерминированы и надёжны.
// Go использует go/parser прямо в процессе — без внешних команд, быстро.
func (s *Server) handleAICheck(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -54,7 +54,6 @@ func (s *Server) handleAICheck(w http.ResponseWriter, r *http.Request) {
"python": {ext: ".py", cmd: []string{"python3", "-m", "py_compile"}},
"ruby": {ext: ".rb", cmd: []string{"ruby", "-c"}},
"php": {ext: ".php", cmd: []string{"php", "-l"}},
"perl": {ext: ".pl", cmd: []string{"perl", "-c"}},
"go": {ext: ".go", cmd: nil}, // go проверяется через go/parser в процессе
}
+21 -21
View File
@@ -35,6 +35,19 @@ var validFuncName = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`)
// Выше — не имеет смысла для inline функции; лучше использовать Package с URL.
const maxCodeSize = 1 << 20
func buildDeployArchive(lang, code string) ([]byte, error) {
switch lang {
case "nodejs":
return runtime.BuildJSDeployZip(code)
case "php":
return runtime.BuildScriptZip(code, "main.php")
case "ruby":
return runtime.BuildScriptZip(code, "handler.rb")
default:
return []byte(code), nil
}
}
// handleFunctionsRoot обрабатывает запросы к /console/api/functions без имени функции.
// GET → список всех функций, POST → создать новую.
func (s *Server) handleFunctionsRoot(w http.ResponseWriter, r *http.Request) {
@@ -212,17 +225,10 @@ func (s *Server) handleCreateFunction(w http.ResponseWriter, r *http.Request) {
"buildcommand": "build",
}
} else {
var deployBytes []byte
if req.Language == "nodejs" {
zipBytes, zipErr := runtime.BuildJSDeployZip(req.Code)
if zipErr != nil {
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build nodejs archive: %v", zipErr))
return
}
deployBytes = zipBytes
} else {
// Python, PHP, Ruby, Perl — код передаётся как есть в deployment.literal
deployBytes = []byte(req.Code)
deployBytes, archiveErr := buildDeployArchive(req.Language, req.Code)
if archiveErr != nil {
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build %s archive: %v", req.Language, archiveErr))
return
}
pkgSpec = map[string]any{
"deployment": map[string]any{"type": "literal", "literal": base64.StdEncoding.EncodeToString(deployBytes)},
@@ -429,16 +435,10 @@ func (s *Server) handleUpdateFunctionCode(w http.ResponseWriter, r *http.Request
// Определяем язык из аннотации — нужен для правильной упаковки
lang, _, _ := unstructured.NestedString(fn.Object, "metadata", "annotations", "fission-console/language")
var deployBytes []byte
if lang == "nodejs" {
zipBytes, zipErr := runtime.BuildJSDeployZip(req.Code)
if zipErr != nil {
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build nodejs archive: %v", zipErr))
return
}
deployBytes = zipBytes
} else {
deployBytes = []byte(req.Code)
deployBytes, archiveErr := buildDeployArchive(lang, req.Code)
if archiveErr != nil {
writeJSONError(w, http.StatusInternalServerError, fmt.Sprintf("build %s archive: %v", lang, archiveErr))
return
}
literal := base64.StdEncoding.EncodeToString(deployBytes)
+168 -62
View File
@@ -4,7 +4,6 @@ import (
"context"
"net/http"
"os"
"strings"
"time"
"fission-console/internal/fission"
@@ -14,72 +13,95 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
)
var requiredBootstrapServiceAccounts = []string{"fission-fetcher", "fission-builder"}
var requiredBootstrapRoleBindings = []string{
"fission-executor-user-ns",
"fission-router-user-ns",
"fission-buildermgr-user-ns",
"fission-kubewatcher-user-ns",
"fission-timer-user-ns",
"fission-fetcher-system-user-ns",
"fission-builder-system-user-ns",
"fission-fetcher-local-user-ns",
"fission-builder-local-user-ns",
}
type namespacePreparationStatus struct {
ManagedByConsole bool `json:"managedByConsole"`
WatcherLabel bool `json:"watcherLabel"`
ServiceAccounts map[string]bool `json:"serviceAccounts"`
RoleBindings map[string]bool `json:"roleBindings"`
}
func (s namespacePreparationStatus) Ready() bool {
if !s.ManagedByConsole || !s.WatcherLabel {
return false
}
for _, ok := range s.ServiceAccounts {
if !ok {
return false
}
}
for _, ok := range s.RoleBindings {
if !ok {
return false
}
}
return true
}
type controlPlaneServiceStatus struct {
Ready bool `json:"ready"`
PodCount int `json:"podCount"`
ReadyPods []string `json:"readyPods"`
}
type controlPlaneStatus struct {
Namespace string `json:"namespace"`
Ready bool `json:"ready"`
Executor controlPlaneServiceStatus `json:"executor"`
Router controlPlaneServiceStatus `json:"router"`
}
// handleNSStatus возвращает статус инициализации пользовательского namespace.
// Используется UI для отображения прогресса при первом входе нового пользователя.
//
// Три стадии:
// 1. Namespace существует и Active
// 2. Namespace добавлен в FISSION_RESOURCE_NAMESPACES executor deployment
// 3. Executor pod Running + Ready (готов принимать функции)
// 2. Namespace подготовлен для Layer 1 NSWatcher: label + bootstrap RBAC/SA
// 3. Fission control-plane готов: executor и router Running + Ready
func (s *Server) handleNSStatus(w http.ResponseWriter, r *http.Request) {
ns := s.userNS(r)
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
fissionNS := os.Getenv("FISSION_SYSTEM_NAMESPACE")
if fissionNS == "" {
fissionNS = "fission"
}
type stageInfo struct {
Name string `json:"name"`
Done bool `json:"done"`
}
stages := []stageInfo{
{Name: "Создание пространства имён"},
{Name: "Регистрация в Fission"},
{Name: "Прогрев окружений"},
{Name: "Подготовка namespace для Fission"},
{Name: "Готовность control-plane"},
}
// Stage 1: namespace существует и Active
nsObj, err := s.dyn.Resource(fission.NamespaceGVR).Get(ctx, ns, metav1.GetOptions{})
var preparation namespacePreparationStatus
control := controlPlaneStatus{Namespace: fissionSystemNamespace()}
if err == nil {
phase, _, _ := unstructured.NestedString(nsObj.Object, "status", "phase")
stages[0].Done = phase == "Active"
}
// Stage 2: namespace в FISSION_RESOURCE_NAMESPACES executor deployment
if stages[0].Done {
execDep, err2 := s.dyn.Resource(fission.DeploymentGVR).Namespace(fissionNS).Get(ctx, "executor", metav1.GetOptions{})
if err2 == nil {
stages[1].Done = nsInFissionEnv(execDep, ns)
}
preparation = s.namespacePreparationStatus(ctx, ns, nsObj)
stages[1].Done = preparation.Ready()
}
// Stage 3: executor pod Running + Ready
if stages[1].Done {
podGVR := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
podList, err3 := s.dyn.Resource(podGVR).Namespace(fissionNS).List(ctx, metav1.ListOptions{
LabelSelector: "svc=executor",
})
if err3 == nil {
for _, pod := range podList.Items {
phase, _, _ := unstructured.NestedString(pod.Object, "status", "phase")
if phase != "Running" {
continue
}
conditions, _, _ := unstructured.NestedSlice(pod.Object, "status", "conditions")
for _, c := range conditions {
cond, ok := c.(map[string]any)
if !ok {
continue
}
if cond["type"] == "Ready" && cond["status"] == "True" {
stages[2].Done = true
}
}
}
}
control = s.controlPlaneStatus(ctx)
stages[2].Done = control.Ready
}
ready := stages[0].Done && stages[1].Done && stages[2].Done
@@ -89,32 +111,116 @@ func (s *Server) handleNSStatus(w http.ResponseWriter, r *http.Request) {
})
}
// nsInFissionEnv проверяет что namespace ns содержится в FISSION_RESOURCE_NAMESPACES
// первого контейнера данного deployment.
func nsInFissionEnv(dep *unstructured.Unstructured, ns string) bool {
containers, _, _ := unstructured.NestedSlice(dep.Object, "spec", "template", "spec", "containers")
for _, c := range containers {
cont, ok := c.(map[string]any)
func (s *Server) handleNSDebug(w http.ResponseWriter, r *http.Request) {
ns := s.userNS(r)
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
nsObj, err := s.dyn.Resource(fission.NamespaceGVR).Get(ctx, ns, metav1.GetOptions{})
labels := map[string]string{}
phase := ""
exists := err == nil
active := false
preparation := namespacePreparationStatus{}
if exists {
labels, _, _ = unstructured.NestedStringMap(nsObj.Object, "metadata", "labels")
phase, _, _ = unstructured.NestedString(nsObj.Object, "status", "phase")
active = phase == "Active"
preparation = s.namespacePreparationStatus(ctx, ns, nsObj)
}
control := s.controlPlaneStatus(ctx)
writeAnyJSON(w, http.StatusOK, map[string]any{
"namespace": ns,
"exists": exists,
"active": active,
"phase": phase,
"labels": labels,
"prepared": preparation.Ready(),
"preparation": preparation,
"controlPlane": control,
"namespaceReady": active && preparation.Ready() && control.Ready,
})
}
func (s *Server) namespacePreparationStatus(ctx context.Context, ns string, nsObj *unstructured.Unstructured) namespacePreparationStatus {
status := namespacePreparationStatus{
ServiceAccounts: make(map[string]bool, len(requiredBootstrapServiceAccounts)),
RoleBindings: make(map[string]bool, len(requiredBootstrapRoleBindings)),
}
if nsObj != nil {
labels, _, _ := unstructured.NestedStringMap(nsObj.Object, "metadata", "labels")
status.ManagedByConsole = labels["managed-by"] == "fission-console"
status.WatcherLabel = labels["fission.io/managed"] == "true"
}
saGVR := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "serviceaccounts"}
for _, name := range requiredBootstrapServiceAccounts {
_, err := s.dyn.Resource(saGVR).Namespace(ns).Get(ctx, name, metav1.GetOptions{})
status.ServiceAccounts[name] = err == nil
}
rbGVR := schema.GroupVersionResource{Group: "rbac.authorization.k8s.io", Version: "v1", Resource: "rolebindings"}
for _, name := range requiredBootstrapRoleBindings {
_, err := s.dyn.Resource(rbGVR).Namespace(ns).Get(ctx, name, metav1.GetOptions{})
status.RoleBindings[name] = err == nil
}
return status
}
func (s *Server) controlPlaneStatus(ctx context.Context) controlPlaneStatus {
status := controlPlaneStatus{Namespace: fissionSystemNamespace()}
status.Executor = s.serviceStatus(ctx, status.Namespace, "executor")
status.Router = s.serviceStatus(ctx, status.Namespace, "router")
status.Ready = status.Executor.Ready && status.Router.Ready
return status
}
func (s *Server) serviceStatus(ctx context.Context, namespace, service string) controlPlaneServiceStatus {
podGVR := schema.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
podList, err := s.dyn.Resource(podGVR).Namespace(namespace).List(ctx, metav1.ListOptions{
LabelSelector: "svc=" + service,
})
if err != nil {
return controlPlaneServiceStatus{}
}
status := controlPlaneServiceStatus{PodCount: len(podList.Items)}
for _, pod := range podList.Items {
if podReady(&pod) {
status.Ready = true
status.ReadyPods = append(status.ReadyPods, pod.GetName())
}
}
return status
}
func fissionSystemNamespace() string {
ns := os.Getenv("FISSION_SYSTEM_NAMESPACE")
if ns == "" {
return "fission"
}
return ns
}
func podReady(pod *unstructured.Unstructured) bool {
if pod == nil {
return false
}
phase, _, _ := unstructured.NestedString(pod.Object, "status", "phase")
if phase != "Running" {
return false
}
conditions, _, _ := unstructured.NestedSlice(pod.Object, "status", "conditions")
for _, c := range conditions {
cond, ok := c.(map[string]any)
if !ok {
continue
}
envs, _, _ := unstructured.NestedSlice(cont, "env")
for _, e := range envs {
env, ok := e.(map[string]any)
if !ok {
continue
}
if env["name"] == "FISSION_RESOURCE_NAMESPACES" {
if v, ok := env["value"].(string); ok {
for _, p := range strings.Split(v, ",") {
if strings.TrimSpace(p) == ns {
return true
}
}
}
}
if cond["type"] == "Ready" && cond["status"] == "True" {
return true
}
break // только первый контейнер
}
return false
}
}
+2 -2
View File
@@ -90,7 +90,7 @@ func decodeArchiveBytesToSource(decoded []byte) (string, error) {
if len(decoded) == 0 {
return "", io.ErrUnexpectedEOF
}
// Если байты — валидный UTF-8, возвращаем напрямую (python, ruby, perl, php)
// Если байты — валидный UTF-8, возвращаем напрямую (python, ruby, php)
if utf8.Valid(decoded) {
return string(decoded), nil
}
@@ -112,7 +112,7 @@ func decodeZipSource(zipBytes []byte) (string, error) {
}
// Сначала ищем по приоритетным именам
preferred := []string{"main.py", "main.js", "main.go", "handler.go", "handler.js", "handler.py"}
preferred := []string{"main.py", "main.js", "main.go", "main.php", "handler.rb", "handler.pl", "handler.go", "handler.js", "handler.py"}
for _, name := range preferred {
for _, file := range reader.File {
if strings.EqualFold(file.Name, name) {
+1
View File
@@ -140,6 +140,7 @@ func (s *Server) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("/console/api/httptriggers", auth(s.handleList(fission.HTTPTrigGVR)))
mux.HandleFunc("/console/api/timetriggers", auth(s.handleList(fission.TimeTrigGVR)))
mux.HandleFunc("/console/api/ns/status", auth(s.handleNSStatus))
mux.HandleFunc("/console/api/ns/debug", auth(s.handleNSDebug))
mux.HandleFunc("/console/api/ai/check", auth(s.handleAICheck))
// --- ai/ask feature (удалить строку чтобы выкосить роут) ---
mux.HandleFunc("/console/api/ai/ask", auth(s.handleAIAsk))