Feat: support ui schema (#2647)

* Docs: change swagger api config

* Docs: change swagger api config

* Docs: change swagger api config

* Feat: support ui schema

* Fix: distinguish between structs and arrays

* Feat: support build swagger config

* Feat: support update ui schema

Co-authored-by: barnettZQG <yiyun.pro>
This commit is contained in:
barnettZQG
2021-11-08 14:13:22 +08:00
committed by GitHub
co-authored by lnx01
parent 5590c3d7b5
commit eb258fae66
27 changed files with 6825 additions and 5586 deletions
+3 -1
View File
@@ -172,12 +172,14 @@ e2e-setup:
kubectl wait --for=condition=Ready pod -l app=source-controller -n flux-system --timeout=600s
kubectl wait --for=condition=Ready pod -l app=helm-controller -n flux-system --timeout=600s
build-swagger:
go run ./cmd/apiserver/main.go build-swagger ./docs/apidoc/swagger.json
e2e-api-test:
# Run e2e test
ginkgo -v -skipPackage capability,setup,application -r e2e
ginkgo -v -r e2e/application
e2e-apiserver-test:
e2e-apiserver-test: build-swagger
go test -v -coverpkg=./... -coverprofile=/tmp/e2e_apiserver_test.out ./test/e2e-apiserver-test
@$(OK) tests pass
+2
View File
@@ -79,6 +79,8 @@ const CapabilityConfigMapNamePrefix = "schema-"
const (
// OpenapiV3JSONSchema is the key to store OpenAPI v3 JSON schema in ConfigMap
OpenapiV3JSONSchema string = "openapi-v3-json-schema"
// UISchema is the key to store ui custom schema
UISchema string = "ui-schema"
)
// CapabilityCategory defines the category of a capability
+42
View File
@@ -18,12 +18,16 @@ package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
restfulspec "github.com/emicklei/go-restful-openapi/v2"
"github.com/go-openapi/spec"
"github.com/oam-dev/kubevela/pkg/apiserver/log"
"github.com/oam-dev/kubevela/pkg/apiserver/rest"
"github.com/oam-dev/kubevela/version"
@@ -38,6 +42,34 @@ func main() {
flag.StringVar(&s.restCfg.Datastore.URL, "datastore-url", "", "Metadata storage database url,takes effect when the storage driver is mongodb.")
flag.Parse()
if len(os.Args) > 2 && os.Args[1] == "build-swagger" {
func() {
swagger, err := s.buildSwagger()
if err != nil {
log.Logger.Fatal(err.Error())
}
outData, err := json.MarshalIndent(swagger, "", "\t")
if err != nil {
log.Logger.Fatal(err.Error())
}
swaggerFile, err := os.OpenFile(os.Args[2], os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
log.Logger.Fatal(err.Error())
}
defer func() {
if err := swaggerFile.Close(); err != nil {
log.Logger.Errorf("close swagger file failure %s", err.Error())
}
}()
_, err = swaggerFile.Write(outData)
if err != nil {
log.Logger.Fatal(err.Error())
}
fmt.Println("build swagger config file success")
}()
return
}
srvc := make(chan struct{})
go func() {
@@ -48,6 +80,7 @@ func main() {
}()
var term = make(chan os.Signal, 1)
signal.Notify(term, os.Interrupt, syscall.SIGTERM)
select {
case <-term:
log.Logger.Infof("Received SIGTERM, exiting gracefully...")
@@ -71,5 +104,14 @@ func (s *Server) run() error {
if err != nil {
return fmt.Errorf("create apiserver failed : %w ", err)
}
return server.Run(ctx)
}
func (s *Server) buildSwagger() (*spec.Swagger, error) {
server, err := rest.New(s.restCfg)
if err != nil {
return nil, fmt.Errorf("create apiserver failed : %w ", err)
}
return restfulspec.BuildSwagger(server.RegisterServices()), nil
}
+5360 -5503
View File
File diff suppressed because it is too large Load Diff
+12 -7
View File
@@ -20,9 +20,11 @@ import (
"time"
"github.com/getkin/kin-openapi/openapi3"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/apiserver/model"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils"
"github.com/oam-dev/kubevela/pkg/cloudprovider"
)
@@ -467,7 +469,8 @@ type ListDefinitionResponse struct {
// DetailDefinitionResponse get definition detail
type DetailDefinitionResponse struct {
Schema *openapi3.Schema `json:"schema"`
APISchema *openapi3.Schema `json:"schema"`
UISchema []*utils.UIParameter `json:"uiSchema"`
}
// DefinitionBase is the definition base model
@@ -556,12 +559,14 @@ type UpdateWorkflowPlanRequest struct {
// WorkflowStep workflow step config
type WorkflowStep struct {
// Name is the unique name of the workflow step.
Name string `json:"name" validate:"checkname"`
Type string `json:"type" validate:"checkname"`
DependsOn []string `json:"dependsOn"`
Properties string `json:"properties,omitempty"`
Inputs common.StepInputs `json:"inputs,omitempty"`
Outputs common.StepOutputs `json:"outputs,omitempty"`
Name string `json:"name" validate:"checkname"`
Alias string `json:"alias" validate:"checkalias"`
Type string `json:"type" validate:"checkname"`
Description string `json:"description"`
DependsOn []string `json:"dependsOn"`
Properties string `json:"properties,omitempty"`
Inputs common.StepInputs `json:"inputs,omitempty"`
Outputs common.StepOutputs `json:"outputs,omitempty"`
}
// DetailWorkflowPlanResponse detail workflow response
+6 -8
View File
@@ -48,6 +48,7 @@ type Config struct {
// APIServer interface for call api server
type APIServer interface {
Run(context.Context) error
RegisterServices() restfulspec.Config
}
type restServer struct {
@@ -83,16 +84,13 @@ func New(cfg Config) (a APIServer, err error) {
}
func (s *restServer) Run(ctx context.Context) error {
webservice.Init(ctx, s.dataStore)
err := s.registerServices()
if err != nil {
return err
}
s.RegisterServices()
return s.startHTTP(ctx)
}
func (s *restServer) registerServices() error {
// RegisterServices register web service
func (s *restServer) RegisterServices() restfulspec.Config {
webservice.Init(s.dataStore)
/* ************************************************************** */
/* ************* Open API Route Group ***************** */
/* ************************************************************** */
@@ -119,7 +117,7 @@ func (s *restServer) registerServices() error {
APIPath: "/apidocs.json",
PostBuildSwaggerObjectHandler: enrichSwaggerObject}
s.webContainer.Add(restfulspec.NewOpenAPIService(config))
return nil
return config
}
func enrichSwaggerObject(swo *spec.Swagger) {
+26 -8
View File
@@ -30,8 +30,6 @@ import (
"github.com/oam-dev/kubevela/pkg/apiserver/log"
"github.com/oam-dev/kubevela/pkg/apiserver/model"
apis "github.com/oam-dev/kubevela/pkg/apiserver/rest/apis/v1"
restapis "github.com/oam-dev/kubevela/pkg/apiserver/rest/apis/v1"
restutils "github.com/oam-dev/kubevela/pkg/apiserver/rest/utils"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils/bcode"
cuemodel "github.com/oam-dev/kubevela/pkg/cue/model"
"github.com/oam-dev/kubevela/pkg/cue/model/value"
@@ -107,7 +105,7 @@ func (u *addonUsecaseImpl) StatusAddon(name string) (*apis.AddonStatusResponse,
var app v1beta1.Application
err := u.kubeClient.Get(context.Background(), client.ObjectKey{
Namespace: types.DefaultKubeVelaNS,
Name: restutils.AddonName2AppName(name),
Name: AddonName2AppName(name),
}, &app)
if err != nil {
if errors2.IsNotFound(err) {
@@ -206,19 +204,19 @@ func (u *addonUsecaseImpl) ListAddonRegistries(ctx context.Context) ([]*apis.Add
}
var list []*apis.AddonRegistryMeta
for _, entity := range entities {
list = append(list, restutils.ConvertAddonRegistryModel2AddonRegistryMeta(entity.(*model.AddonRegistry)))
list = append(list, ConvertAddonRegistryModel2AddonRegistryMeta(entity.(*model.AddonRegistry)))
}
return list, nil
}
func renderApplication(addon *restapis.DetailAddonResponse, args *apis.EnableAddonRequest) (*v1beta1.Application, error) {
func renderApplication(addon *apis.DetailAddonResponse, args *apis.EnableAddonRequest) (*v1beta1.Application, error) {
if args == nil {
args = &apis.EnableAddonRequest{Args: map[string]string{}}
}
app := &v1beta1.Application{
TypeMeta: metav1.TypeMeta{APIVersion: "core.oam.dev/v1beta1", Kind: "Application"},
ObjectMeta: metav1.ObjectMeta{
Name: restutils.AddonName2AppName(addon.Name),
Name: AddonName2AppName(addon.Name),
Namespace: types.DefaultKubeVelaNS,
Labels: map[string]string{
oam.LabelAddonName: addon.Name,
@@ -294,7 +292,7 @@ func (u *addonUsecaseImpl) DisableAddon(ctx context.Context, name string) error
app := &v1beta1.Application{
TypeMeta: metav1.TypeMeta{APIVersion: "core.oam.dev/v1beta1", Kind: "Application"},
ObjectMeta: metav1.ObjectMeta{
Name: restutils.AddonName2AppName(name),
Name: AddonName2AppName(name),
Namespace: types.DefaultKubeVelaNS,
},
}
@@ -316,7 +314,7 @@ func renderRawComponent(elem apis.AddonElementFile) (*common2.ApplicationCompone
dec := k8syaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
_, _, err := dec.Decode([]byte(elem.Data), nil, obj)
if err != nil {
fmt.Println(err)
return nil, err
}
baseRawComponent.Properties = util.Object2RawExtension(obj)
return &baseRawComponent, nil
@@ -559,3 +557,23 @@ func readRepo(h *gitHelper) ([]*github.RepositoryContent, error) {
}
return dirs, nil
}
// ConvertAddonRegistryModel2AddonRegistryMeta will convert from model to AddonRegistryMeta
func ConvertAddonRegistryModel2AddonRegistryMeta(r *model.AddonRegistry) *apis.AddonRegistryMeta {
return &apis.AddonRegistryMeta{
Name: r.Name,
Git: r.Git,
}
}
const addonAppPrefix = "addon-"
// AddonName2AppName -
func AddonName2AppName(name string) string {
return addonAppPrefix + name
}
// AppName2addonName -
func AppName2addonName(name string) string {
return strings.TrimPrefix(name, addonAppPrefix)
}
+174 -5
View File
@@ -18,20 +18,26 @@ package usecase
import (
"context"
"encoding/json"
"fmt"
"sort"
"time"
"github.com/getkin/kin-openapi/openapi3"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
k8stypes "k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
"github.com/getkin/kin-openapi/openapi3"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/apiserver/clients"
"github.com/oam-dev/kubevela/pkg/apiserver/log"
apisv1 "github.com/oam-dev/kubevela/pkg/apiserver/rest/apis/v1"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils/bcode"
)
// DefinitionUsecase definition usecase, Implement the management of ComponentDefinition、TraitDefinition and WorkflowStepDefinition.
@@ -40,6 +46,8 @@ type DefinitionUsecase interface {
ListDefinitions(ctx context.Context, envName, defType string) ([]*apisv1.DefinitionBase, error)
// DetailDefinition get definition detail
DetailDefinition(ctx context.Context, name, defType string) (*apisv1.DetailDefinitionResponse, error)
// AddDefinitionUISchema add or update custom definition ui schema
AddDefinitionUISchema(ctx context.Context, name, defType, configRaw string) ([]*utils.UIParameter, error)
}
type definitionUsecaseImpl struct {
@@ -82,7 +90,7 @@ func (d *definitionUsecaseImpl) ListDefinitions(ctx context.Context, envName, de
return d.listDefinitions(ctx, defs, kindWorkflowStepDefinition)
default:
return nil, fmt.Errorf("invalid definition type")
return nil, bcode.ErrDefinitionTypeNotSupport
}
}
@@ -108,23 +116,184 @@ func (d *definitionUsecaseImpl) listDefinitions(ctx context.Context, list *unstr
// DetailDefinition get definition detail
func (d *definitionUsecaseImpl) DetailDefinition(ctx context.Context, name, defType string) (*apisv1.DetailDefinitionResponse, error) {
if !utils.StringsContain([]string{"component", "trait", "workflowstep"}, defType) {
return nil, bcode.ErrDefinitionTypeNotSupport
}
var cm v1.ConfigMap
if err := d.kubeClient.Get(ctx, k8stypes.NamespacedName{
Namespace: types.DefaultKubeVelaNS,
Name: fmt.Sprintf("%s-schema-%s", defType, name),
}, &cm); err != nil {
if apierrors.IsNotFound(err) {
return nil, bcode.ErrDefinitionNoSchema
}
return nil, err
}
data, ok := cm.Data["openapi-v3-json-schema"]
data, ok := cm.Data[types.OpenapiV3JSONSchema]
if !ok {
return nil, fmt.Errorf("failed to get definition schema")
return nil, bcode.ErrDefinitionNoSchema
}
schema := &openapi3.Schema{}
if err := schema.UnmarshalJSON([]byte(data)); err != nil {
return nil, err
}
// render default ui schema
defaultUISchema := renderDefaultUISchema(schema)
// patch from custom ui schema
customUISchema := d.renderCustomUISchema(ctx, name, defType, defaultUISchema)
return &apisv1.DetailDefinitionResponse{
Schema: schema,
APISchema: schema,
UISchema: customUISchema,
}, nil
}
func (d *definitionUsecaseImpl) renderCustomUISchema(ctx context.Context, name, defType string, defaultSchema []*utils.UIParameter) []*utils.UIParameter {
var cm v1.ConfigMap
if err := d.kubeClient.Get(ctx, k8stypes.NamespacedName{
Namespace: types.DefaultKubeVelaNS,
Name: fmt.Sprintf("%s-uischema-%s", defType, name),
}, &cm); err != nil {
if !apierrors.IsNotFound(err) {
log.Logger.Errorf("find uischema configmap from cluster failure %s", err.Error())
}
return defaultSchema
}
data, ok := cm.Data[types.UISchema]
if !ok {
return defaultSchema
}
schema := []*utils.UIParameter{}
if err := json.Unmarshal([]byte(data), &schema); err != nil {
log.Logger.Errorf("unmarshal ui schema failure %s", err.Error())
return defaultSchema
}
return patchSchema(defaultSchema, schema)
}
// AddDefinitionUISchema add definition custom ui schema config
func (d *definitionUsecaseImpl) AddDefinitionUISchema(ctx context.Context, name, defType, configRaw string) ([]*utils.UIParameter, error) {
var uiParameters []*utils.UIParameter
err := yaml.Unmarshal([]byte(configRaw), &uiParameters)
if err != nil {
log.Logger.Errorf("yaml unmarshal failure %s", err.Error())
return nil, bcode.ErrInvalidDefinitionUISchema
}
dataBate, err := json.Marshal(uiParameters)
if err != nil {
log.Logger.Errorf("json marshal failure %s", err.Error())
return nil, bcode.ErrInvalidDefinitionUISchema
}
var cm v1.ConfigMap
if err := d.kubeClient.Get(ctx, k8stypes.NamespacedName{
Namespace: types.DefaultKubeVelaNS,
Name: fmt.Sprintf("%s-uischema-%s", defType, name),
}, &cm); err != nil {
if apierrors.IsNotFound(err) {
err = d.kubeClient.Create(ctx, &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: types.DefaultKubeVelaNS,
Name: fmt.Sprintf("%s-uischema-%s", defType, name),
},
Data: map[string]string{
types.UISchema: string(dataBate),
},
})
}
if err != nil {
return nil, err
}
} else {
cm.Data[types.UISchema] = string(dataBate)
err := d.kubeClient.Update(ctx, &cm)
if err != nil {
return nil, err
}
}
return uiParameters, nil
}
func patchSchema(defaultSchema, customSchema []*utils.UIParameter) []*utils.UIParameter {
var customSchemaMap = make(map[string]*utils.UIParameter, len(customSchema))
for i, custom := range customSchema {
customSchemaMap[custom.JSONKey] = customSchema[i]
}
for i := range defaultSchema {
dSchema := defaultSchema[i]
if cusSchema, exist := customSchemaMap[dSchema.JSONKey]; exist {
if cusSchema.Description != "" {
dSchema.Description = cusSchema.Description
}
if cusSchema.Label != "" {
dSchema.Label = cusSchema.Label
}
if cusSchema.SubParameterGroupOption != nil {
dSchema.SubParameterGroupOption = cusSchema.SubParameterGroupOption
}
if cusSchema.Validate != nil {
dSchema.Validate = cusSchema.Validate
}
if cusSchema.UIType != "" {
dSchema.UIType = cusSchema.UIType
}
if cusSchema.Disable != nil {
dSchema.Disable = cusSchema.Disable
}
if cusSchema.SubParameters != nil {
dSchema.SubParameters = patchSchema(dSchema.SubParameters, cusSchema.SubParameters)
}
if cusSchema.Sort != 0 {
dSchema.Sort = cusSchema.Sort
}
}
}
sort.Slice(defaultSchema, func(i, j int) bool {
return defaultSchema[i].Sort < defaultSchema[j].Sort
})
return defaultSchema
}
func renderDefaultUISchema(apiSchema *openapi3.Schema) []*utils.UIParameter {
if apiSchema == nil {
return nil
}
var params []*utils.UIParameter
for key, property := range apiSchema.Properties {
if property.Value != nil {
param := renderUIParameter(key, utils.FirstUpper(key), property, apiSchema.Required)
params = append(params, param)
}
}
return params
}
func renderUIParameter(key, label string, property *openapi3.SchemaRef, required []string) *utils.UIParameter {
var parameter utils.UIParameter
subType := ""
if property.Value.Items != nil {
if property.Value.Items.Value != nil {
subType = property.Value.Items.Value.Type
}
parameter.SubParameters = renderDefaultUISchema(property.Value.Items.Value)
}
if property.Value.Properties != nil {
parameter.SubParameters = renderDefaultUISchema(property.Value)
}
parameter.Validate = &utils.Validate{}
parameter.Validate.DefaultValue = property.Value.Default
for _, enum := range property.Value.Enum {
parameter.Validate.Options = append(parameter.Validate.Options, utils.Option{Label: utils.RenderLabel(enum), Value: enum})
}
parameter.JSONKey = key
parameter.Description = property.Value.Description
parameter.Label = label
parameter.UIType = utils.GetDefaultUIType(property.Value.Type, len(parameter.Validate.Options) != 0, subType)
parameter.Validate.Max = property.Value.Max
parameter.Validate.MaxLength = property.Value.MaxLength
parameter.Validate.Min = property.Value.Min
parameter.Validate.MinLength = property.Value.MinLength
parameter.Validate.Pattern = property.Value.Pattern
parameter.Validate.Required = utils.StringsContain(required, property.Value.Title)
parameter.Sort = 100
return &parameter
}
+59 -2
View File
@@ -18,7 +18,10 @@ package usecase
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"testing"
"github.com/getkin/kin-openapi/openapi3"
"github.com/google/go-cmp/cmp"
@@ -29,6 +32,8 @@ import (
"sigs.k8s.io/yaml"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
v1 "github.com/oam-dev/kubevela/pkg/apiserver/rest/apis/v1"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils"
"github.com/oam-dev/kubevela/pkg/oam/util"
)
@@ -98,7 +103,7 @@ var _ = Describe("Test namespace usecase functions", func() {
Namespace: "vela-system",
},
Data: map[string]string{
"openapi-v3-json-schema": `{"properties":{"batchPartition":{"title":"batchPartition","type":"integer"},"volumes":{"description":"Specify volume type, options: pvc, configMap, secret, emptyDir","enum":["pvc","configMap","secret","emptyDir"],"title":"volumes","type":"string"}, "rolloutBatches":{"items":{"properties":{"replicas":{"title":"replicas","type":"integer"}},"required":["replicas"],"type":"object"},"title":"rolloutBatches","type":"array"},"targetRevision":{"title":"targetRevision","type":"string"},"targetSize":{"title":"targetSize","type":"integer"}},"required":["targetRevision","targetSize"],"type":"object"}`,
types.OpenapiV3JSONSchema: `{"properties":{"batchPartition":{"title":"batchPartition","type":"integer"},"volumes": {"description":"Specify volume type, options: pvc, configMap, secret, emptyDir","enum":["pvc","configMap","secret","emptyDir"],"title":"volumes","type":"string"}, "rolloutBatches":{"items":{"properties":{"replicas":{"title":"replicas","type":"integer"}},"required":["replicas"],"type":"object"},"title":"rolloutBatches","type":"array"},"targetRevision":{"title":"targetRevision","type":"string"},"targetSize":{"title":"targetSize","type":"integer"}},"required":["targetRevision","targetSize"],"type":"object"}`,
},
}
err := k8sClient.Create(context.Background(), cm)
@@ -110,6 +115,58 @@ var _ = Describe("Test namespace usecase functions", func() {
err = schemaFromCM.UnmarshalJSON([]byte(cm.Data["openapi-v3-json-schema"]))
Expect(err).Should(Succeed())
Expect(schema.Schema).Should(Equal(schemaFromCM))
Expect(schema.APISchema).Should(Equal(schemaFromCM))
})
It("Test renderDefaultUISchema", func() {
schema := &v1.DetailDefinitionResponse{}
data, err := ioutil.ReadFile("./testdata/api-schema.json")
Expect(err).Should(Succeed())
err = json.Unmarshal(data, schema)
Expect(err).Should(Succeed())
Expect(cmp.Diff(len(schema.APISchema.Required), 3)).Should(BeEmpty())
uiSchema := renderDefaultUISchema(schema.APISchema)
Expect(cmp.Diff(len(uiSchema), 12)).Should(BeEmpty())
})
It("Test patchSchema", func() {
ddr := &v1.DetailDefinitionResponse{}
data, err := ioutil.ReadFile("./testdata/api-schema.json")
Expect(err).Should(Succeed())
err = json.Unmarshal(data, ddr)
Expect(err).Should(Succeed())
Expect(cmp.Diff(len(ddr.APISchema.Required), 3)).Should(BeEmpty())
defaultschema := renderDefaultUISchema(ddr.APISchema)
customschema := []*utils.UIParameter{}
cdata, err := ioutil.ReadFile("./testdata/ui-custom-schema.yaml")
Expect(err).Should(Succeed())
err = yaml.Unmarshal(cdata, &customschema)
Expect(err).Should(Succeed())
uiSchema := patchSchema(defaultschema, customschema)
for _, schema := range uiSchema {
fmt.Printf("%s=> %d", schema.JSONKey, schema.Sort)
}
Expect(cmp.Diff(len(uiSchema), 12)).Should(BeEmpty())
Expect(cmp.Diff(uiSchema[3].JSONKey, "readinessProbe")).Should(BeEmpty())
Expect(cmp.Diff(len(uiSchema[3].SubParameters), 8)).Should(BeEmpty())
outdata, err := yaml.Marshal(uiSchema)
Expect(err).Should(Succeed())
err = ioutil.WriteFile("./testdata/ui-schema.yaml", outdata, 0755)
Expect(err).Should(Succeed())
})
})
func TestAddDefinitionUISchema(t *testing.T) {
du := NewDefinitionUsecase()
cdata, err := ioutil.ReadFile("./testdata/ui-custom-schema.yaml")
if err != nil {
t.Fatal(err)
}
_, err = du.AddDefinitionUISchema(context.TODO(), "webservice", "component", string(cdata))
if err != nil {
t.Fatal(err)
}
}
+386
View File
@@ -0,0 +1,386 @@
{
"schema": {
"properties": {
"addRevisionLabel": {
"type": "boolean",
"default": false,
"description": "If addRevisionLabel is true, the appRevision label will be added to the underlying pods",
"title": "addRevisionLabel"
},
"cmd": {
"type": "array",
"items": {
"type": "string"
},
"description": "Commands to run in the container",
"title": "cmd"
},
"cpu": {
"type": "string",
"description": "Number of CPU units for the service, like `0.5` (0.5 CPU core), `1` (1 CPU core)",
"title": "cpu"
},
"env": {
"type": "array",
"items": {
"properties": {
"name": {
"type": "string",
"description": "Environment variable name",
"title": "name"
},
"value": {
"type": "string",
"description": "The value of the environment variable",
"title": "value"
},
"valueFrom": {
"properties": {
"secretKeyRef": {
"properties": {
"key": {
"type": "string",
"description": "The key of the secret to select from. Must be a valid secret key",
"title": "key"
},
"name": {
"type": "string",
"description": "The name of the secret in the pod's namespace to select from",
"title": "name"
}
},
"required": [
"name",
"key"
],
"type": "object",
"description": "Selects a key of a secret in the pod's namespace",
"title": "secretKeyRef"
}
},
"required": [
"secretKeyRef"
],
"type": "object",
"description": "Specifies a source the value of this var should come from",
"title": "valueFrom"
}
},
"required": [
"name"
],
"type": "object"
},
"description": "Define arguments by using environment variables",
"title": "env"
},
"image": {
"type": "string",
"description": "Which image would you like to use for your service",
"title": "image"
},
"imagePullPolicy": {
"type": "string",
"description": "Specify image pull policy for your service",
"title": "imagePullPolicy"
},
"imagePullSecrets": {
"type": "array",
"items": {
"type": "string"
},
"description": "Specify image pull secrets for your service",
"title": "imagePullSecrets"
},
"livenessProbe": {
"properties": {
"exec": {
"properties": {
"command": {
"type": "array",
"items": {
"type": "string"
},
"description": "A command to be executed inside the container to assess its health. Each space delimited token of the command is a separate array element. Commands exiting 0 are considered to be successful probes, whilst all other exit codes are considered failures.",
"title": "command"
}
},
"required": [
"command"
],
"type": "object",
"description": "Instructions for assessing container health by executing a command. Either this attribute or the httpGet attribute or the tcpSocket attribute MUST be specified. This attribute is mutually exclusive with both the httpGet attribute and the tcpSocket attribute.",
"title": "exec"
},
"failureThreshold": {
"type": "integer",
"default": 3,
"description": "Number of consecutive failures required to determine the container is not alive (liveness probe) or not ready (readiness probe).",
"title": "failureThreshold"
},
"httpGet": {
"properties": {
"httpHeaders": {
"type": "array",
"items": {
"properties": {
"name": {
"type": "string",
"title": "name"
},
"value": {
"type": "string",
"title": "value"
}
},
"required": [
"name",
"value"
],
"type": "object"
},
"title": "httpHeaders"
},
"path": {
"type": "string",
"description": "The endpoint, relative to the port, to which the HTTP GET request should be directed.",
"title": "path"
},
"port": {
"type": "integer",
"description": "The TCP socket within the container to which the HTTP GET request should be directed.",
"title": "port"
}
},
"required": [
"path",
"port"
],
"type": "object",
"description": "Instructions for assessing container health by executing an HTTP GET request. Either this attribute or the exec attribute or the tcpSocket attribute MUST be specified. This attribute is mutually exclusive with both the exec attribute and the tcpSocket attribute.",
"title": "httpGet"
},
"initialDelaySeconds": {
"type": "integer",
"default": 0,
"description": "Number of seconds after the container is started before the first probe is initiated.",
"title": "initialDelaySeconds"
},
"periodSeconds": {
"type": "integer",
"default": 10,
"description": "How often, in seconds, to execute the probe.",
"title": "periodSeconds"
},
"successThreshold": {
"type": "integer",
"default": 1,
"description": "Minimum consecutive successes for the probe to be considered successful after having failed.",
"title": "successThreshold"
},
"tcpSocket": {
"properties": {
"port": {
"type": "integer",
"description": "The TCP socket within the container that should be probed to assess container health.",
"title": "port"
}
},
"required": [
"port"
],
"type": "object",
"description": "Instructions for assessing container health by probing a TCP socket. Either this attribute or the exec attribute or the httpGet attribute MUST be specified. This attribute is mutually exclusive with both the exec attribute and the httpGet attribute.",
"title": "tcpSocket"
},
"timeoutSeconds": {
"type": "integer",
"default": 1,
"description": "Number of seconds after which the probe times out.",
"title": "timeoutSeconds"
}
},
"required": [
"initialDelaySeconds",
"periodSeconds",
"timeoutSeconds",
"successThreshold",
"failureThreshold"
],
"type": "object",
"description": "Instructions for assessing whether the container is alive.",
"title": "livenessProbe"
},
"memory": {
"type": "string",
"description": "Specifies the attributes of the memory resource required for the container.",
"title": "memory"
},
"port": {
"type": "integer",
"default": 80,
"description": "Which port do you want customer traffic sent to",
"title": "port"
},
"readinessProbe": {
"properties": {
"exec": {
"properties": {
"command": {
"type": "array",
"items": {
"type": "string"
},
"description": "A command to be executed inside the container to assess its health. Each space delimited token of the command is a separate array element. Commands exiting 0 are considered to be successful probes, whilst all other exit codes are considered failures.",
"title": "command"
}
},
"required": [
"command"
],
"type": "object",
"description": "Instructions for assessing container health by executing a command. Either this attribute or the httpGet attribute or the tcpSocket attribute MUST be specified. This attribute is mutually exclusive with both the httpGet attribute and the tcpSocket attribute.",
"title": "exec"
},
"failureThreshold": {
"type": "integer",
"default": 3,
"description": "Number of consecutive failures required to determine the container is not alive (liveness probe) or not ready (readiness probe).",
"title": "failureThreshold"
},
"httpGet": {
"properties": {
"httpHeaders": {
"type": "array",
"items": {
"properties": {
"name": {
"type": "string",
"title": "name"
},
"value": {
"type": "string",
"title": "value"
}
},
"required": [
"name",
"value"
],
"type": "object"
},
"title": "httpHeaders"
},
"path": {
"type": "string",
"description": "The endpoint, relative to the port, to which the HTTP GET request should be directed.",
"title": "path"
},
"port": {
"type": "integer",
"description": "The TCP socket within the container to which the HTTP GET request should be directed.",
"title": "port"
}
},
"required": [
"path",
"port"
],
"type": "object",
"description": "Instructions for assessing container health by executing an HTTP GET request. Either this attribute or the exec attribute or the tcpSocket attribute MUST be specified. This attribute is mutually exclusive with both the exec attribute and the tcpSocket attribute.",
"title": "httpGet"
},
"initialDelaySeconds": {
"type": "integer",
"default": 0,
"description": "Number of seconds after the container is started before the first probe is initiated.",
"title": "initialDelaySeconds"
},
"periodSeconds": {
"type": "integer",
"default": 10,
"description": "How often, in seconds, to execute the probe.",
"title": "periodSeconds"
},
"successThreshold": {
"type": "integer",
"default": 1,
"description": "Minimum consecutive successes for the probe to be considered successful after having failed.",
"title": "successThreshold"
},
"tcpSocket": {
"properties": {
"port": {
"type": "integer",
"description": "The TCP socket within the container that should be probed to assess container health.",
"title": "port"
}
},
"required": [
"port"
],
"type": "object",
"description": "Instructions for assessing container health by probing a TCP socket. Either this attribute or the exec attribute or the httpGet attribute MUST be specified. This attribute is mutually exclusive with both the exec attribute and the httpGet attribute.",
"title": "tcpSocket"
},
"timeoutSeconds": {
"type": "integer",
"default": 1,
"description": "Number of seconds after which the probe times out.",
"title": "timeoutSeconds"
}
},
"required": [
"initialDelaySeconds",
"periodSeconds",
"timeoutSeconds",
"successThreshold",
"failureThreshold"
],
"type": "object",
"description": "Instructions for assessing whether the container is in a suitable state to serve traffic.",
"title": "readinessProbe"
},
"volumes": {
"type": "array",
"items": {
"properties": {
"mountPath": {
"type": "string",
"title": "mountPath"
},
"name": {
"type": "string",
"title": "name"
},
"type": {
"type": "string",
"enum": [
"pvc",
"configMap",
"secret",
"emptyDir"
],
"description": "Specify volume type, options: \"pvc\",\"configMap\",\"secret\",\"emptyDir\"",
"title": "type"
}
},
"required": [
"name",
"mountPath",
"type"
],
"type": "object"
},
"description": "Declare volumes and volumeMounts",
"title": "volumes"
}
},
"required": [
"addRevisionLabel",
"image",
"port"
],
"type": "object"
}
}
+56
View File
@@ -0,0 +1,56 @@
- description: Specify image pull policy for your service
disable: false
jsonKey: imagePullPolicy
label: 镜像更新策略
uiType: Select
validate:
options:
- label: 镜像不存在时更新
value: IfNotPresent
- label: 总是更新
value: Always
- label: 永不更新
value: Never
sort: 2
- description: Specifies the attributes of the memory resource required for the container.
disable: false
jsonKey: memory
label: Memory
uiType: MemoryNumber
sort: 3
- uiType: CPUNumber
jsonKey: cpu
- description: Define arguments by using environment variables
disable: false
jsonKey: env
label: Env
subParameterGroupOption:
- - name
- value
- - name
- valueFrom
subParameters:
- description: Specifies a source the value of this var should come from
disable: false
jsonKey: valueFrom
label: Secret选择器
uiType: InnerGroup
subParameters:
- jsonKey: secretKeyRef
uiType: Ignore
subParameters:
- jsonKey: name
label: Secret选择
uiType: SecretSelect
- jsonKey: key
label: SecretKey选择
uiType: SecretKeySelect
uiType: Structs
validate: {}
- uiType: ImageInput
jsonKey: image
sort: 1
- jsonKey: readinessProbe
uiType: Group
label: ReadinessProbe检测
sort: 4
+132
View File
@@ -0,0 +1,132 @@
- description: Which image would you like to use for your service
jsonKey: image
label: Image
uiType: Input
validete:
required: true
- description: Specify image pull policy for your service
jsonKey: imagePullPolicy
label: ImagePullPolicy
uiType: Input
validete: {}
- description: Instructions for assessing whether the container is alive.
jsonKey: livenessProbe
label: LivenessProbe
uiType: KV
validete: {}
- description: If addRevisionLabel is true, the appRevision label will be added to
the underlying pods
jsonKey: addRevisionLabel
label: AddRevisionLabel
uiType: Switch
validete:
defaultValue: false
required: true
- description: Number of CPU units for the service, like `0.5` (0.5 CPU core), `1`
(1 CPU core)
jsonKey: cpu
label: Cpu
uiType: Input
validete: {}
- description: Specify image pull secrets for your service
jsonKey: imagePullSecrets
label: ImagePullSecrets
uiType: Structs
validete: {}
- description: Specifies the attributes of the memory resource required for the container.
jsonKey: memory
label: Memory
uiType: Input
validete: {}
- description: Which port do you want customer traffic sent to
jsonKey: port
label: Port
uiType: Number
validete:
defaultValue: 80
required: true
- description: Instructions for assessing whether the container is in a suitable state
to serve traffic.
jsonKey: readinessProbe
label: ReadinessProbe
uiType: KV
validete: {}
- description: Declare volumes and volumeMounts
jsonKey: volumes
label: Volumes
subParameters:
- description: ""
jsonKey: volumes.mountPath
label: MountPath
uiType: Input
validete:
required: true
- description: ""
jsonKey: volumes.name
label: Name
uiType: Input
validete:
required: true
- description: 'Specify volume type, options: "pvc","configMap","secret","emptyDir"'
jsonKey: volumes.type
label: Type
uiType: Select
validete:
options:
- label: Pvc
value: pvc
- label: ConfigMap
value: configMap
- label: Secret
value: secret
- label: EmptyDir
value: emptyDir
required: true
uiType: Structs
validete: {}
- description: Commands to run in the container
jsonKey: cmd
label: Cmd
uiType: Structs
validete: {}
- description: Define arguments by using environment variables
jsonKey: env
label: Env
subParameters:
- description: The value of the environment variable
jsonKey: env.value
label: Value
uiType: Input
validete: {}
- description: Specifies a source the value of this var should come from
jsonKey: env.valueFrom
label: ValueFrom
subParameters:
- description: ""
jsonKey: env.valueFrom.secretKeyRef
label: SecretKeyRef
subParameters:
- description: secret name
jsonKey: env.valueFrom.secretKeyRef.name
label: Name
uiType: Input
validete:
required: true
- description: secret key
jsonKey: env.valueFrom.secretKeyRef.key
label: Key
uiType: Input
validete:
required: true
uiType: KV
validete: {}
uiType: KV
validete: {}
- description: Environment variable name
jsonKey: env.name
label: Name
uiType: Input
validete:
required: true
uiType: Structs
validete: {}
+428
View File
@@ -0,0 +1,428 @@
- description: Instructions for assessing whether the container is in a suitable state
to serve traffic.
jsonKey: readinessProbe
label: ReadinessProbe检测
sort: 1
subParameters:
- description: Number of seconds after the container is started before the first
probe is initiated.
jsonKey: readinessProbe.initialDelaySeconds
label: InitialDelaySeconds
sort: 100
uiType: Number
validete:
defaultValue: 0
required: true
- description: How often, in seconds, to execute the probe.
jsonKey: readinessProbe.periodSeconds
label: PeriodSeconds
sort: 100
uiType: Number
validete:
defaultValue: 10
required: true
- description: Minimum consecutive successes for the probe to be considered successful
after having failed.
jsonKey: readinessProbe.successThreshold
label: SuccessThreshold
sort: 100
uiType: Number
validete:
defaultValue: 1
required: true
- description: Instructions for assessing container health by probing a TCP socket.
Either this attribute or the exec attribute or the httpGet attribute MUST be
specified. This attribute is mutually exclusive with both the exec attribute
and the httpGet attribute.
jsonKey: readinessProbe.tcpSocket
label: TcpSocket
sort: 100
subParameters:
- description: The TCP socket within the container that should be probed to assess
container health.
jsonKey: readinessProbe.tcpSocket.port
label: Port
sort: 100
uiType: Number
validete:
required: true
uiType: KV
validete: {}
- description: Number of seconds after which the probe times out.
jsonKey: readinessProbe.timeoutSeconds
label: TimeoutSeconds
sort: 100
uiType: Number
validete:
defaultValue: 1
required: true
- description: Instructions for assessing container health by executing a command.
Either this attribute or the httpGet attribute or the tcpSocket attribute MUST
be specified. This attribute is mutually exclusive with both the httpGet attribute
and the tcpSocket attribute.
jsonKey: readinessProbe.exec
label: Exec
sort: 100
subParameters:
- description: A command to be executed inside the container to assess its health.
Each space delimited token of the command is a separate array element. Commands
exiting 0 are considered to be successful probes, whilst all other exit codes
are considered failures.
jsonKey: readinessProbe.exec.command
label: Command
sort: 100
uiType: Strings
validete:
required: true
uiType: KV
validete: {}
- description: Number of consecutive failures required to determine the container
is not alive (liveness probe) or not ready (readiness probe).
jsonKey: readinessProbe.failureThreshold
label: FailureThreshold
sort: 100
uiType: Number
validete:
defaultValue: 3
required: true
- description: Instructions for assessing container health by executing an HTTP
GET request. Either this attribute or the exec attribute or the tcpSocket attribute
MUST be specified. This attribute is mutually exclusive with both the exec attribute
and the tcpSocket attribute.
jsonKey: readinessProbe.httpGet
label: HttpGet
sort: 100
subParameters:
- description: ""
jsonKey: readinessProbe.httpGet.httpHeaders
label: HttpHeaders
sort: 100
subParameters:
- description: ""
jsonKey: readinessProbe.httpGet.httpHeaders.[].name
label: Name
sort: 100
uiType: Input
validete:
required: true
- description: ""
jsonKey: readinessProbe.httpGet.httpHeaders.[].value
label: Value
sort: 100
uiType: Input
validete:
required: true
uiType: Structs
validete: {}
- description: The endpoint, relative to the port, to which the HTTP GET request
should be directed.
jsonKey: readinessProbe.httpGet.path
label: Path
sort: 100
uiType: Input
validete:
required: true
- description: The TCP socket within the container to which the HTTP GET request
should be directed.
jsonKey: readinessProbe.httpGet.port
label: Port
sort: 100
uiType: Number
validete:
required: true
uiType: KV
validete: {}
uiType: Group
validete: {}
- description: Which image would you like to use for your service
jsonKey: image
label: Image
sort: 2
uiType: ImageInput
validete:
required: true
- description: Specify image pull policy for your service
disable: false
jsonKey: imagePullPolicy
label: 镜像更新策略
sort: 2
uiType: Select
validete:
options:
- label: 镜像不存在时更新
value: IfNotPresent
- label: 总是更新
value: Always
- label: 永不更新
value: Never
- description: Specifies the attributes of the memory resource required for the container.
disable: false
jsonKey: memory
label: Memory
sort: 3
uiType: MemoryNumber
validete: {}
- description: Commands to run in the container
jsonKey: cmd
label: Cmd
sort: 100
uiType: Strings
validete: {}
- description: Which port do you want customer traffic sent to
jsonKey: port
label: Port
sort: 100
uiType: Number
validete:
defaultValue: 80
required: true
- description: Specify image pull secrets for your service
jsonKey: imagePullSecrets
label: ImagePullSecrets
sort: 100
uiType: Strings
validete: {}
- description: Instructions for assessing whether the container is alive.
jsonKey: livenessProbe
label: LivenessProbe
sort: 100
subParameters:
- description: Number of seconds after which the probe times out.
jsonKey: livenessProbe.timeoutSeconds
label: TimeoutSeconds
sort: 100
uiType: Number
validete:
defaultValue: 1
required: true
- description: Instructions for assessing container health by executing a command.
Either this attribute or the httpGet attribute or the tcpSocket attribute MUST
be specified. This attribute is mutually exclusive with both the httpGet attribute
and the tcpSocket attribute.
jsonKey: livenessProbe.exec
label: Exec
sort: 100
subParameters:
- description: A command to be executed inside the container to assess its health.
Each space delimited token of the command is a separate array element. Commands
exiting 0 are considered to be successful probes, whilst all other exit codes
are considered failures.
jsonKey: livenessProbe.exec.command
label: Command
sort: 100
uiType: Strings
validete:
required: true
uiType: KV
validete: {}
- description: Number of consecutive failures required to determine the container
is not alive (liveness probe) or not ready (readiness probe).
jsonKey: livenessProbe.failureThreshold
label: FailureThreshold
sort: 100
uiType: Number
validete:
defaultValue: 3
required: true
- description: Instructions for assessing container health by executing an HTTP
GET request. Either this attribute or the exec attribute or the tcpSocket attribute
MUST be specified. This attribute is mutually exclusive with both the exec attribute
and the tcpSocket attribute.
jsonKey: livenessProbe.httpGet
label: HttpGet
sort: 100
subParameters:
- description: The TCP socket within the container to which the HTTP GET request
should be directed.
jsonKey: livenessProbe.httpGet.port
label: Port
sort: 100
uiType: Number
validete:
required: true
- description: ""
jsonKey: livenessProbe.httpGet.httpHeaders
label: HttpHeaders
sort: 100
subParameters:
- description: ""
jsonKey: livenessProbe.httpGet.httpHeaders.[].name
label: Name
sort: 100
uiType: Input
validete:
required: true
- description: ""
jsonKey: livenessProbe.httpGet.httpHeaders.[].value
label: Value
sort: 100
uiType: Input
validete:
required: true
uiType: Structs
validete: {}
- description: The endpoint, relative to the port, to which the HTTP GET request
should be directed.
jsonKey: livenessProbe.httpGet.path
label: Path
sort: 100
uiType: Input
validete:
required: true
uiType: KV
validete: {}
- description: Number of seconds after the container is started before the first
probe is initiated.
jsonKey: livenessProbe.initialDelaySeconds
label: InitialDelaySeconds
sort: 100
uiType: Number
validete:
defaultValue: 0
required: true
- description: How often, in seconds, to execute the probe.
jsonKey: livenessProbe.periodSeconds
label: PeriodSeconds
sort: 100
uiType: Number
validete:
defaultValue: 10
required: true
- description: Minimum consecutive successes for the probe to be considered successful
after having failed.
jsonKey: livenessProbe.successThreshold
label: SuccessThreshold
sort: 100
uiType: Number
validete:
defaultValue: 1
required: true
- description: Instructions for assessing container health by probing a TCP socket.
Either this attribute or the exec attribute or the httpGet attribute MUST be
specified. This attribute is mutually exclusive with both the exec attribute
and the httpGet attribute.
jsonKey: livenessProbe.tcpSocket
label: TcpSocket
sort: 100
subParameters:
- description: The TCP socket within the container that should be probed to assess
container health.
jsonKey: livenessProbe.tcpSocket.port
label: Port
sort: 100
uiType: Number
validete:
required: true
uiType: KV
validete: {}
uiType: KV
validete: {}
- description: Declare volumes and volumeMounts
jsonKey: volumes
label: Volumes
sort: 100
subParameters:
- description: ""
jsonKey: volumes.[].mountPath
label: MountPath
sort: 100
uiType: Input
validete:
required: true
- description: ""
jsonKey: volumes.[].name
label: Name
sort: 100
uiType: Input
validete:
required: true
- description: 'Specify volume type, options: "pvc","configMap","secret","emptyDir"'
jsonKey: volumes.[].type
label: Type
sort: 100
uiType: Select
validete:
options:
- label: Pvc
value: pvc
- label: ConfigMap
value: configMap
- label: Secret
value: secret
- label: EmptyDir
value: emptyDir
required: true
uiType: Structs
validete: {}
- description: If addRevisionLabel is true, the appRevision label will be added to
the underlying pods
jsonKey: addRevisionLabel
label: AddRevisionLabel
sort: 100
uiType: Switch
validete:
defaultValue: false
required: true
- description: Number of CPU units for the service, like `0.5` (0.5 CPU core), `1`
(1 CPU core)
jsonKey: cpu
label: Cpu
sort: 100
uiType: CPUNumber
validete: {}
- description: Define arguments by using environment variables
disable: false
jsonKey: env
label: Env
sort: 100
subParameterGroupOption:
- - env.name
- env.value
- - env.name
- env.valueFrom
subParameters:
- description: The value of the environment variable
jsonKey: env.[].value
label: Value
sort: 100
uiType: Input
validete: {}
- description: Specifies a source the value of this var should come from
jsonKey: env.[].valueFrom
label: ValueFrom
sort: 100
subParameters:
- description: Selects a key of a secret in the pod's namespace
jsonKey: env.[].valueFrom.secretKeyRef
label: SecretKeyRef
sort: 100
subParameters:
- description: The key of the secret to select from. Must be a valid secret
key
jsonKey: env.[].valueFrom.secretKeyRef.key
label: Key
sort: 100
uiType: Input
validete:
required: true
- description: The name of the secret in the pod's namespace to select from
jsonKey: env.[].valueFrom.secretKeyRef.name
label: Name
sort: 100
uiType: Input
validete:
required: true
uiType: KV
validete:
required: true
uiType: KV
validete: {}
- description: Environment variable name
jsonKey: env.[].name
label: Name
sort: 100
uiType: Input
validete:
required: true
uiType: Structs
validete: {}
@@ -0,0 +1,29 @@
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bcode
// ErrDefinitionNotFound definition is not exist
var ErrDefinitionNotFound = NewBcode(404, 70001, "definition is not exist")
// ErrDefinitionNoSchema definition not have schema
var ErrDefinitionNoSchema = NewBcode(400, 70002, "definition not have schema")
// ErrDefinitionTypeNotSupport definition type not support
var ErrDefinitionTypeNotSupport = NewBcode(400, 70003, "definition type not support")
// ErrInvalidDefinitionUISchema invalid custom definition ui schema
var ErrInvalidDefinitionUISchema = NewBcode(400, 70004, "invalid custom defnition ui schema")
-24
View File
@@ -1,24 +0,0 @@
package utils
import (
"github.com/oam-dev/kubevela/pkg/apiserver/model"
apisv1 "github.com/oam-dev/kubevela/pkg/apiserver/rest/apis/v1"
"strings"
)
// ConvertAddonRegistryModel2AddonRegistryMeta will convert from model to AddonRegistryMeta
func ConvertAddonRegistryModel2AddonRegistryMeta(r *model.AddonRegistry) *apisv1.AddonRegistryMeta {
return &apisv1.AddonRegistryMeta{
Name: r.Name,
Git: r.Git,
}
}
const addonAppPrefix = "addon-"
func AddonName2AppName(name string) string {
return addonAppPrefix + name
}
func AppName2addonName(name string) string {
return strings.TrimPrefix(name, addonAppPrefix)
}
+85 -11
View File
@@ -16,32 +16,41 @@ limitations under the License.
package utils
import (
"fmt"
"strings"
)
// UIParameter Structured import table simple UI model
type UIParameter struct {
Sort uint `json:"sort"`
Label string `json:"label"`
Description string `json:"description"`
Validate *Validate `json:"validete,omitempty"`
Validate *Validate `json:"validate,omitempty"`
JSONKey string `json:"jsonKey"`
UIType string `json:"uiType"`
// means only can be read.
Disable bool `json:"disable"`
SubParameters []*UIParameter `json:"subParameters,omitempty"`
Disable *bool `json:"disable,omitempty"`
SubParameterGroupOption [][]string `json:"subParameterGroupOption,omitempty"`
SubParameters []*UIParameter `json:"subParameters,omitempty"`
}
// Validate parameter validate rule
type Validate struct {
Required bool `json:"required,omitempty"`
Max int `json:"max,omitempty"`
Min int `json:"min,omitempty"`
Regular string `json:"regular,omitempty"`
Options []*Options `json:"options,omitempty"`
Max *float64 `json:"max,omitempty"`
MaxLength *uint64 `json:"maxLength,omitempty"`
Min *float64 `json:"min,omitempty"`
MinLength uint64 `json:"minLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
Options []Option `json:"options,omitempty"`
DefaultValue interface{} `json:"defaultValue,omitempty"`
}
// Options select option
type Options struct {
Label string `json:"label"`
Value string `json:"value"`
// Option select option
type Option struct {
Label string `json:"label"`
Value interface{} `json:"value"`
}
// ParseUIParameterFromDefinition cue of parameter in Definitions was analyzed to obtain the form description model.
@@ -50,3 +59,68 @@ func ParseUIParameterFromDefinition(definition []byte) ([]*UIParameter, error) {
return params, nil
}
// FirstUpper Sets the first letter of the string to upper.
func FirstUpper(s string) string {
if s == "" {
return ""
}
return strings.ToUpper(s[:1]) + s[1:]
}
// FirstLower Sets the first letter of the string to lowercase.
func FirstLower(s string) string {
if s == "" {
return ""
}
return strings.ToLower(s[:1]) + s[1:]
}
// GetDefaultUIType Set the default mapping for API Schema Type
func GetDefaultUIType(apiType string, haveOptions bool, subType string) string {
switch apiType {
case "string":
if haveOptions {
return "Select"
}
return "Input"
case "number", "integer":
return "Number"
case "boolean":
return "Switch"
case "array":
if subType == "string" {
return "Strings"
}
if subType == "number" || subType == "integer" {
return "Numbers"
}
return "Structs"
case "object":
return "KV"
default:
return "Input"
}
}
// RenderLabel render option label
func RenderLabel(source interface{}) string {
switch v := source.(type) {
case int:
return fmt.Sprintf("%d", v)
case string:
return FirstUpper(v)
default:
return FirstUpper(fmt.Sprintf("%v", v))
}
}
// StringsContain strings contain
func StringsContain(items []string, source string) bool {
for _, item := range items {
if item == source {
return true
}
}
return false
}
@@ -22,7 +22,6 @@ import (
apis "github.com/oam-dev/kubevela/pkg/apiserver/rest/apis/v1"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/usecase"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils"
"github.com/oam-dev/kubevela/pkg/apiserver/rest/utils/bcode"
)
@@ -112,7 +111,7 @@ func (s *addonRegistryWebService) deleteAddonRegistry(req *restful.Request, res
return
}
if err := res.WriteEntity(*utils.ConvertAddonRegistryModel2AddonRegistryMeta(r)); err != nil {
if err := res.WriteEntity(*usecase.ConvertAddonRegistryModel2AddonRegistryMeta(r)); err != nil {
bcode.ReturnError(req, res, err)
return
}
@@ -47,7 +47,7 @@ func (c *applicationPlanWebService) GetWebService() *restful.WebService {
Produces(restful.MIME_JSON, restful.MIME_XML).
Doc("api for application manage")
tags := []string{"application"}
tags := []string{"applicationplan"}
ws.Route(ws.GET("/").To(c.listApplicationPlans).
Doc("list all application plans").
+5 -5
View File
@@ -76,7 +76,7 @@ func (c *ClusterWebService) GetWebService() *restful.WebService {
Doc("modify cluster").
Metadata(restfulspec.KeyOpenAPITags, tags).
Param(ws.PathParameter("clusterName", "identifier of the cluster").DataType("string")).
Reads(&apis.CreateClusterRequest{}).
Reads(apis.CreateClusterRequest{}).
Returns(200, "", apis.ClusterBase{}).
Returns(400, "", bcode.Bcode{}).
Writes(apis.ClusterBase{}))
@@ -95,7 +95,7 @@ func (c *ClusterWebService) GetWebService() *restful.WebService {
Param(ws.PathParameter("provider", "identifier of the cloud provider").DataType("string")).
Param(ws.QueryParameter("page", "Page for paging").DataType("int").DefaultValue("0")).
Param(ws.QueryParameter("pageSize", "PageSize for paging").DataType("int").DefaultValue("20")).
Reads(&apis.AccessKeyRequest{}).
Reads(apis.AccessKeyRequest{}).
Returns(200, "", apis.ListCloudClusterResponse{}).
Returns(400, "", bcode.Bcode{}).
Writes(apis.ListCloudClusterResponse{}))
@@ -104,7 +104,7 @@ func (c *ClusterWebService) GetWebService() *restful.WebService {
Doc("create cluster from cloud cluster").
Metadata(restfulspec.KeyOpenAPITags, tags).
Param(ws.PathParameter("provider", "identifier of the cloud provider").DataType("string")).
Reads(&apis.ConnectCloudClusterRequest{}).
Reads(apis.ConnectCloudClusterRequest{}).
Returns(200, "", apis.ClusterBase{}).
Returns(400, "", bcode.Bcode{}).
Writes(apis.ClusterBase{}))
@@ -112,8 +112,8 @@ func (c *ClusterWebService) GetWebService() *restful.WebService {
ws.Route(ws.POST("/cloud-clusters/{provider}/create").To(c.createCloudCluster).
Doc("create cloud cluster").
Metadata(restfulspec.KeyOpenAPITags, tags).
Param(ws.PathParameter("provider", "identifier of the cloud provider").DataType("string")).
Reads(&apis.CreateCloudClusterRequest{}).
Param(ws.PathParameter("provider", "identifier of the cloud provider").DataType("string").Required(true)).
Reads(apis.CreateCloudClusterRequest{}).
Returns(200, "", apis.CreateCloudClusterResponse{}).
Returns(400, "", bcode.Bcode{}).
Writes(apis.CreateCloudClusterResponse{}))
+1 -1
View File
@@ -41,7 +41,7 @@ func (d *definitionWebservice) GetWebService() *restful.WebService {
ws.Route(ws.GET("/").To(d.listDefinitions).
Doc("list all definitions").
Metadata(restfulspec.KeyOpenAPITags, tags).
Param(ws.QueryParameter("type", "query the definition type").DataType("string")).
Param(ws.QueryParameter("type", "query the definition type").DataType("string").Required(true).AllowableValues(map[string]string{"component": "", "trait": "", "workflowstep": ""})).
Param(ws.QueryParameter("envName", "if specified, query the definition supported by the env.").DataType("string")).
Returns(200, "", apis.ListDefinitionResponse{}).
Writes(apis.ListDefinitionResponse{}).Do(returns200, returns500))
@@ -47,12 +47,14 @@ func (n *namespaceWebService) GetWebService() *restful.WebService {
ws.Route(ws.GET("/").To(n.listNamespaces).
Doc("list all namespaces").
Metadata(restfulspec.KeyOpenAPITags, tags).
Returns(200, "", apis.ListNamespaceResponse{}).
Writes(apis.ListNamespaceResponse{}))
ws.Route(ws.POST("/").To(n.createNamespace).
Doc("create namespace").
Metadata(restfulspec.KeyOpenAPITags, tags).
Reads(apis.CreateNamespaceRequest{}).
Returns(200, "", apis.NamespaceDetailResponse{}).
Writes(apis.NamespaceDetailResponse{}))
return ws
}
@@ -44,13 +44,14 @@ func (c *oamApplicationWebService) GetWebService() *restful.WebService {
Produces(restful.MIME_JSON, restful.MIME_XML).
Doc("api for oam application manage")
tags := []string{"oam"}
tags := []string{"oam-application"}
ws.Route(ws.GET("/namespaces/{namespace}/applications/{appname}").To(c.getApplication).
Doc("get the specified oam application in the specified namespace").
Metadata(restfulspec.KeyOpenAPITags, tags).
Param(ws.PathParameter("namespace", "identifier of the namespace").DataType("string")).
Param(ws.PathParameter("appname", "identifier of the oam application").DataType("string")).
Returns(200, "", apis.ApplicationResponse{}).
Writes(apis.ApplicationResponse{}))
ws.Route(ws.POST("/namespaces/{namespace}/applications/{appname}").To(c.createOrUpdateApplication).
@@ -33,11 +33,12 @@ func (c *policyDefinitionWebservice) GetWebService() *restful.WebService {
Produces(restful.MIME_JSON, restful.MIME_XML).
Doc("api for policydefinition manage")
tags := []string{"policydefinition"}
tags := []string{"definition"}
ws.Route(ws.GET("/").To(noop).
Doc("list all policydefinition").
Metadata(restfulspec.KeyOpenAPITags, tags).
Returns(200, "", apis.ListPolicyDefinitionResponse{}).
Writes(apis.ListPolicyDefinitionResponse{}))
return ws
}
+1 -2
View File
@@ -17,7 +17,6 @@ limitations under the License.
package webservice
import (
"context"
"net/http"
"github.com/emicklei/go-restful/v3"
@@ -58,7 +57,7 @@ func returns500(b *restful.RouteBuilder) {
// Init init all webservice, pass in the required parameter object.
// It can be implemented using the idea of dependency injection.
func Init(ctx context.Context, ds datastore.DataStore) {
func Init(ds datastore.DataStore) {
clusterUsecase := usecase.NewClusterUsecase(ds)
workflowUsecase := usecase.NewWorkflowUsecase(ds)
applicationUsecase := usecase.NewApplicationUsecase(ds, workflowUsecase)
+7 -2
View File
@@ -51,13 +51,14 @@ func (w *workflowWebService) GetWebService() *restful.WebService {
Produces(restful.MIME_JSON, restful.MIME_XML).
Doc("api for cluster manage")
tags := []string{"cluster"}
tags := []string{"workflowplan"}
ws.Route(ws.GET("/").To(w.listApplicationWorkflows).
Doc("list application workflow").
Param(ws.QueryParameter("appName", "identifier of the application.").DataType("string")).
Param(ws.QueryParameter("appName", "identifier of the application.").DataType("string").Required(true)).
Param(ws.QueryParameter("enable", "query based on enable status").DataType("boolean")).
Metadata(restfulspec.KeyOpenAPITags, tags).
Returns(200, "", apis.ListWorkflowPlanResponse{}).
Writes(apis.ListWorkflowPlanResponse{}).Do(returns200, returns500))
ws.Route(ws.POST("/").To(w.createApplicationWorkflow).
@@ -82,6 +83,7 @@ func (w *workflowWebService) GetWebService() *restful.WebService {
Filter(w.workflowCheckFilter).
Param(ws.PathParameter("name", "identifier of the workflow").DataType("string")).
Reads(apis.UpdateWorkflowPlanRequest{}).
Returns(200, "", apis.DetailWorkflowPlanResponse{}).
Writes(apis.DetailWorkflowPlanResponse{}).Do(returns200, returns500))
ws.Route(ws.DELETE("/{name}").To(w.deleteWorkflow).
@@ -89,6 +91,7 @@ func (w *workflowWebService) GetWebService() *restful.WebService {
Metadata(restfulspec.KeyOpenAPITags, tags).
Filter(w.workflowCheckFilter).
Param(ws.PathParameter("name", "identifier of the workflow").DataType("string")).
Returns(200, "", apis.EmptyResponse{}).
Writes(apis.EmptyResponse{}).Do(returns200, returns500))
ws.Route(ws.GET("/{name}/records").To(w.listWorkflowRecords).
@@ -98,6 +101,7 @@ func (w *workflowWebService) GetWebService() *restful.WebService {
Filter(w.workflowCheckFilter).
Param(ws.PathParameter("page", "Query the page number.").DataType("integer")).
Param(ws.PathParameter("pageSize", "Query the page size number.").DataType("integer")).
Returns(200, "", apis.ListWorkflowRecordsResponse{}).
Writes(apis.ListWorkflowRecordsResponse{}).Do(returns200, returns500))
ws.Route(ws.GET("/{name}/records/{record}").To(w.detailWorkflowRecord).
@@ -105,6 +109,7 @@ func (w *workflowWebService) GetWebService() *restful.WebService {
Param(ws.PathParameter("name", "identifier of the workflow").DataType("string")).
Param(ws.PathParameter("record", "identifier of the workflow record").DataType("string")).
Metadata(restfulspec.KeyOpenAPITags, tags).
Returns(200, "", apis.DetailWorkflowRecordResponse{}).
Writes(apis.DetailWorkflowRecordResponse{}).Do(returns200, returns500))
return ws
+1 -1
View File
@@ -378,7 +378,7 @@ var _ = Describe("Test application containing helm module", func() {
if err := k8sClient.Get(ctx, client.ObjectKey{Name: cmName, Namespace: namespace}, cm); err != nil {
return err
}
if cm.Data["openapi-v3-json-schema"] == "" {
if cm.Data[types.OpenapiV3JSONSchema] == "" {
return errors.New("json schema is not found in the ConfigMap")
}
return nil
+2 -1
View File
@@ -32,6 +32,7 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/oam/util"
. "github.com/onsi/ginkgo"
@@ -347,7 +348,7 @@ spec:
if err := k8sClient.Get(ctx, client.ObjectKey{Name: cmName, Namespace: namespace}, cm); err != nil {
return err
}
if cm.Data["openapi-v3-json-schema"] == "" {
if cm.Data[types.OpenapiV3JSONSchema] == "" {
return errors.New("json schema is not found in the ConfigMap")
}
return nil