feat: provider audit — builder support, function tuning, source archive

Аудит провайдера vs каноничный Fission. Добавлено:

Environment:
- builder_image, builder_command для Go и языков с build step

Package:
- deploy_type (literal/source) для переключения deployment/source archive
- loadPackageSourceArchive() — zip-упаковка source_dir
- Убран пустой source:{} из literal mode

Function:
- executor_type (poolmgr/newdeploy/container)
- function_timeout, idle_timeout
- min_scale, max_scale для ExecutionStrategy

Все 21 тест пройден. Обратная совместимость проверена.
Документация: doc/AUDIT_PROVIDER_VS_FISSION_2026-06-03.md
This commit is contained in:
Naeel
2026-04-15 17:46:47 +03:00
parent 6d66e5b566
commit fd236d87ea
41 changed files with 1431 additions and 61 deletions
@@ -1,10 +1,13 @@
package resources
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"os"
"path/filepath"
@@ -12,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"
@@ -37,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"`
@@ -86,6 +91,12 @@ func (r *PackageResource) Schema(_ context.Context, _ resource.SchemaRequest, re
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,
@@ -137,7 +148,7 @@ func (r *PackageResource) ModifyPlan(ctx context.Context, req resource.ModifyPla
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
@@ -183,7 +194,7 @@ func (r *PackageResource) Create(ctx context.Context, req resource.CreateRequest
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
@@ -246,7 +257,7 @@ func (r *PackageResource) Update(ctx context.Context, req resource.UpdateRequest
return
}
literalBytes, err := loadPackageLiteral(plan.SourceDir.ValueString(), plan.CodePath.ValueString())
literalBytes, err := loadPackageContent(plan.SourceDir.ValueString(), plan.CodePath.ValueString(), plan.DeployType.ValueString())
if err != nil {
resp.Diagnostics.AddError("Ошибка чтения исходного кода пакета", err.Error())
return
@@ -329,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)
@@ -353,6 +364,57 @@ 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", "main.php", "main.rb", "main.pl"}
@@ -371,6 +433,36 @@ func resolveMainSourceFile(sourceDir string) (string, error) {
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",
@@ -378,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}
@@ -405,6 +483,7 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
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())),
@@ -414,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(),
@@ -433,8 +513,13 @@ func unstructuredToPackageModel(packageObject *unstructured.Unstructured, base p
state.BuildLog = types.StringValue(buildLog)
}
if deploymentLiteral != "" {
if literalBytes, err := base64.StdEncoding.DecodeString(deploymentLiteral); err == nil {
// Определить 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))
}
}