code refactor (#935)

* code refactor

* update boilerplate.go.txt
This commit is contained in:
Jianbo Sun
2021-01-26 10:26:41 +08:00
committed by GitHub
parent 75ecf2f301
commit 97f45ae859
41 changed files with 366 additions and 362 deletions
@@ -1,7 +1,7 @@
// +build !ignore_autogenerated
/*
Copyright 2020 The KubeVela Authors.
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.
@@ -1,7 +1,7 @@
// +build !ignore_autogenerated
/*
Copyright 2020 The KubeVela Authors.
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.
+1 -1
View File
@@ -33,7 +33,7 @@ import (
oamcore "github.com/oam-dev/kubevela/apis/core.oam.dev"
velacore "github.com/oam-dev/kubevela/apis/standard.oam.dev/v1alpha1"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/driver"
velacontroller "github.com/oam-dev/kubevela/pkg/controller"
oamcontroller "github.com/oam-dev/kubevela/pkg/controller/core.oam.dev"
oamv1alpha2 "github.com/oam-dev/kubevela/pkg/controller/core.oam.dev/v1alpha2"
+1 -1
View File
@@ -1,5 +1,5 @@
/*
Copyright 2020 The KubeVela Authors.
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.
@@ -1,4 +1,4 @@
package appfile
package api
import (
"encoding/json"
@@ -1,4 +1,4 @@
package appfile
package api
import (
"os"
+27
View File
@@ -0,0 +1,27 @@
/*
Copyright 2020 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 api
import (
"github.com/oam-dev/kubevela/pkg/appfile/template"
)
// Application is an implementation level object for Appfile, all vela commands will access AppFile from Appliction struct here.
type Application struct {
*AppFile `json:",inline"`
Tm template.Manager
}
+15
View File
@@ -0,0 +1,15 @@
package api
// Driver is mutli implement interface
type Driver interface {
// List applications
List(envName string) ([]*Application, error)
// Save application
Save(app *Application, envName string) error
// Delete application
Delete(envName, appName string) error
// Get application
Get(envName, appName string) (*Application, error)
// Name of storage driver
Name() string
}
@@ -1,4 +1,4 @@
package appfile
package api
import (
"encoding/json"
@@ -1,4 +1,4 @@
package appfile
package api
import (
"testing"
+53 -25
View File
@@ -1,7 +1,8 @@
package application
package appfile
import (
"context"
"errors"
"fmt"
"reflect"
"sort"
@@ -10,18 +11,45 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/appfile/template"
)
// NewEmptyApplication new empty application, only set tm
func NewEmptyApplication() (*driver.Application, error) {
func NewEmptyApplication() (*api.Application, error) {
tm, err := template.Load()
if err != nil {
return nil, err
}
return driver.NewApplication(nil, tm), nil
return NewApplication(nil, tm), nil
}
// NewApplication will create application object
func NewApplication(f *api.AppFile, tm template.Manager) *api.Application {
if f == nil {
f = api.NewAppFile()
}
return &api.Application{AppFile: f, Tm: tm}
}
// Validate will validate whether an Appfile is valid.
func Validate(app *api.Application) error {
if app.Name == "" {
return errors.New("name is required")
}
if len(app.Services) == 0 {
return errors.New("at least one service is required")
}
for name, svc := range app.Services {
for traitName, traitData := range svc.GetApplicationConfig() {
if app.Tm.IsTrait(traitName) {
if _, ok := traitData.(map[string]interface{}); !ok {
return fmt.Errorf("trait %s in '%s' must be map", traitName, name)
}
}
}
}
return nil
}
// IsNotFound is application not found error
@@ -29,31 +57,31 @@ func IsNotFound(appName string, err error) bool {
return err != nil && err.Error() == fmt.Sprintf(`application "%s" not found`, appName)
}
// Load will load application with env and name from default vela home dir.
func Load(envName, appName string) (*driver.Application, error) {
app, err := storage.GetStorage().Get(envName, appName)
// LoadApplication will load application with env and name from default vela home dir.
func LoadApplication(envName, appName string) (*api.Application, error) {
app, err := GetStorage().Get(envName, appName)
if err != nil {
return nil, err
}
err = app.Validate()
err = Validate(app)
return app, err
}
// Delete will delete an app along with it's appfile.
func Delete(envName, appName string) error {
return storage.GetStorage().Delete(envName, appName)
return GetStorage().Delete(envName, appName)
}
// List will list all apps
func List(envName string) ([]*driver.Application, error) {
respApps, err := storage.GetStorage().List(envName)
func List(envName string) ([]*api.Application, error) {
respApps, err := GetStorage().List(envName)
if err != nil {
return nil, err
}
var apps []*driver.Application
var apps []*api.Application
for _, resp := range respApps {
app := driver.NewApplication(resp.AppFile, resp.Tm)
err := app.Validate()
app := NewApplication(resp.AppFile, resp.Tm)
err := Validate(app)
if err != nil {
return nil, err
}
@@ -63,7 +91,7 @@ func List(envName string) ([]*driver.Application, error) {
}
// MatchAppByComp will get application with componentName without AppName.
func MatchAppByComp(envName, compName string) (*driver.Application, error) {
func MatchAppByComp(envName, compName string) (*api.Application, error) {
apps, err := List(envName)
if err != nil {
return nil, err
@@ -79,12 +107,12 @@ func MatchAppByComp(envName, compName string) (*driver.Application, error) {
}
// Save will save appfile into default dir.
func Save(app *driver.Application, envName string) error {
return storage.GetStorage().Save(app, envName)
func Save(app *api.Application, envName string) error {
return GetStorage().Save(app, envName)
}
// GetComponents will get oam components from Appfile.
func GetComponents(app *driver.Application) []string {
func GetComponents(app *api.Application) []string {
var components []string
for name := range app.Services {
components = append(components, name)
@@ -94,7 +122,7 @@ func GetComponents(app *driver.Application) []string {
}
// GetServiceConfig will get service type and it's configuration
func GetServiceConfig(app *driver.Application, componentName string) (string, map[string]interface{}) {
func GetServiceConfig(app *api.Application, componentName string) (string, map[string]interface{}) {
svc, ok := app.Services[componentName]
if !ok {
return "", make(map[string]interface{})
@@ -103,7 +131,7 @@ func GetServiceConfig(app *driver.Application, componentName string) (string, ma
}
// GetWorkload will get workload type and it's configuration
func GetWorkload(app *driver.Application, componentName string) (string, map[string]interface{}) {
func GetWorkload(app *api.Application, componentName string) (string, map[string]interface{}) {
svcType, config := GetServiceConfig(app, componentName)
if svcType == "" {
return "", make(map[string]interface{})
@@ -119,7 +147,7 @@ func GetWorkload(app *driver.Application, componentName string) (string, map[str
}
// GetTraits will list all traits and it's configurations attached to the specified component.
func GetTraits(app *driver.Application, componentName string) (map[string]map[string]interface{}, error) {
func GetTraits(app *api.Application, componentName string) (map[string]map[string]interface{}, error) {
_, config := GetServiceConfig(app, componentName)
traitsData := make(map[string]map[string]interface{})
for k, v := range config {
@@ -136,7 +164,7 @@ func GetTraits(app *driver.Application, componentName string) (map[string]map[st
}
// GetTraitsByType will get trait configuration with specified component and trait type, we assume one type of trait can only attach to a component once.
func GetTraitsByType(app *driver.Application, componentName, traitType string) (map[string]interface{}, error) {
func GetTraitsByType(app *api.Application, componentName, traitType string) (map[string]interface{}, error) {
service, ok := app.Services[componentName]
if !ok {
return nil, fmt.Errorf("service name (%s) doesn't exist", componentName)
@@ -149,7 +177,7 @@ func GetTraitsByType(app *driver.Application, componentName, traitType string) (
}
// GetAppConfig will get AppConfig from K8s cluster.
func GetAppConfig(ctx context.Context, c client.Client, app *driver.Application, env *types.EnvMeta) (*v1alpha2.ApplicationConfiguration, error) {
func GetAppConfig(ctx context.Context, c client.Client, app *api.Application, env *types.EnvMeta) (*v1alpha2.ApplicationConfiguration, error) {
appConfig := &v1alpha2.ApplicationConfiguration{}
if err := c.Get(ctx, client.ObjectKey{Namespace: env.Namespace, Name: app.Name}, appConfig); err != nil {
return nil, err
@@ -158,7 +186,7 @@ func GetAppConfig(ctx context.Context, c client.Client, app *driver.Application,
}
// GetApplication will get Application from K8s cluster.
func GetApplication(ctx context.Context, c client.Client, app *driver.Application, env *types.EnvMeta) (*v1alpha2.Application, error) {
func GetApplication(ctx context.Context, c client.Client, app *api.Application, env *types.EnvMeta) (*v1alpha2.Application, error) {
appl := &v1alpha2.Application{}
if err := c.Get(ctx, client.ObjectKey{Namespace: env.Namespace, Name: app.Name}, appl); err != nil {
return nil, err
@@ -1,4 +1,4 @@
package application
package appfile
import (
"errors"
@@ -10,7 +10,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/template"
)
@@ -120,10 +119,10 @@ services:
Captype: types.TypeTrait,
}
}
app := driver.NewApplication(nil, tm)
app := NewApplication(nil, tm)
err := yaml.Unmarshal([]byte(c.raw), &app)
assert.NoError(t, err, caseName)
err = app.Validate()
err = Validate(app)
if c.InValid {
assert.Equal(t, c.InvalidReason, err)
continue
@@ -145,7 +144,7 @@ func TestLoadNotExistsApplication(t *testing.T) {
now := time.Now().Unix()
appName := fmt.Sprintf("test-app-%d", now)
app, err := Load(types.DefaultEnvName, appName)
app, err := LoadApplication(types.DefaultEnvName, appName)
assert.Nil(t, app, caseName)
assert.Error(t, err, caseName)
@@ -2,6 +2,8 @@ package driver
import (
"errors"
"github.com/oam-dev/kubevela/pkg/appfile/api"
)
// ConfigMapDriverName is local storage driver name
@@ -9,7 +11,7 @@ const ConfigMapDriverName = "ConfigMap"
// ConfigMap Storage
type ConfigMap struct {
Driver
api.Driver
}
// NewConfigMapStorage get storage client of ConfigMap type
@@ -23,13 +25,13 @@ func (c *ConfigMap) Name() string {
}
// List applications from configmap storage
func (c *ConfigMap) List(envName string) ([]*Application, error) {
func (c *ConfigMap) List(envName string) ([]*api.Application, error) {
// TODO support configmap storage
return nil, errors.New("not implement")
}
// Save applications from configmap storage
func (c *ConfigMap) Save(app *Application, envName string) error {
func (c *ConfigMap) Save(app *api.Application, envName string) error {
// TODO support configmap storage
return errors.New("not implement")
}
@@ -41,7 +43,7 @@ func (c *ConfigMap) Delete(envName, appName string) error {
}
// Get applications from configmap storage
func (c *ConfigMap) Get(envName, appName string) (*Application, error) {
func (c *ConfigMap) Get(envName, appName string) (*api.Application, error) {
// TODO support configmap storage
return nil, errors.New("not implement")
}
@@ -3,6 +3,8 @@ package driver
import (
"reflect"
"testing"
"github.com/oam-dev/kubevela/pkg/appfile/api"
)
func TestConfigMap_Delete(t *testing.T) {
@@ -35,7 +37,7 @@ func TestConfigMap_Get(t *testing.T) {
tests := []struct {
name string
args args
want *Application
want *api.Application
wantErr bool
}{
// TODO: Add test cases.
@@ -62,7 +64,7 @@ func TestConfigMap_List(t *testing.T) {
tests := []struct {
name string
args args
want []*Application
want []*api.Application
wantErr bool
}{
// TODO: Add test cases.
@@ -101,7 +103,7 @@ func TestConfigMap_Name(t *testing.T) {
func TestConfigMap_Save(t *testing.T) {
type args struct {
app *Application
app *api.Application
envName string
}
tests := []struct {
@@ -10,7 +10,7 @@ import (
"github.com/ghodss/yaml"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/appfile/template"
"github.com/oam-dev/kubevela/pkg/utils/env"
"github.com/oam-dev/kubevela/pkg/utils/system"
@@ -21,7 +21,7 @@ const LocalDriverName = "Local"
// Local Storage
type Local struct {
Driver
api.Driver
}
// NewLocalStorage get storage client of Local type
@@ -35,7 +35,7 @@ func (l *Local) Name() string {
}
// List applications from local storage
func (l *Local) List(envName string) ([]*Application, error) {
func (l *Local) List(envName string) ([]*api.Application, error) {
appDir, err := getApplicationDir(envName)
if err != nil {
return nil, err
@@ -44,7 +44,7 @@ func (l *Local) List(envName string) ([]*Application, error) {
if err != nil {
return nil, fmt.Errorf("list apps from %s err %w", appDir, err)
}
var apps []*Application
var apps []*api.Application
for _, f := range files {
if f.IsDir() {
continue
@@ -62,7 +62,7 @@ func (l *Local) List(envName string) ([]*Application, error) {
}
// Save application from local storage
func (l *Local) Save(app *Application, envName string) error {
func (l *Local) Save(app *api.Application, envName string) error {
appDir, err := getApplicationDir(envName)
if err != nil {
return err
@@ -89,7 +89,7 @@ func (l *Local) Delete(envName, appName string) error {
}
// Get application from local storage
func (l *Local) Get(envName, appName string) (*Application, error) {
func (l *Local) Get(envName, appName string) (*api.Application, error) {
appDir, err := getApplicationDir(envName)
if err != nil {
return nil, err
@@ -116,7 +116,7 @@ func getApplicationDir(envName string) (string, error) {
}
// LoadFromFile will load application from file
func loadFromFile(fileName string) (*Application, error) {
func loadFromFile(fileName string) (*api.Application, error) {
tm, err := template.Load()
if err != nil {
return nil, err
@@ -126,10 +126,10 @@ func loadFromFile(fileName string) (*Application, error) {
return nil, err
}
f, err := appfile.LoadFromFile(fileName)
f, err := api.LoadFromFile(fileName)
if err != nil {
return nil, err
}
app := &Application{AppFile: f, Tm: tm}
app := &api.Application{AppFile: f, Tm: tm}
return app, nil
}
@@ -9,22 +9,22 @@ import (
"github.com/ghodss/yaml"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/appfile/template"
)
var dir string
var tm template.Manager
var afile *appfile.AppFile
var afile *api.AppFile
var appName = "testsvc"
var envName = "default"
func init() {
dir, _ = getApplicationDir(envName)
tm, _ = template.Load()
afile = appfile.NewAppFile()
afile = api.NewAppFile()
afile.Name = appName
svcs := make(map[string]appfile.Service, 0)
svcs := make(map[string]api.Service, 0)
svcs["wordpress"] = map[string]interface{}{
"type": "webservice",
"image": "wordpress:php7.4-apache",
@@ -45,10 +45,10 @@ func TestLocal_Get(t *testing.T) {
tests := []struct {
name string
args args
want *Application
want *api.Application
wantErr bool
}{
{"TestLocal_Get1", args{envName: envName, appName: appName}, &Application{AppFile: afile, Tm: tm}, false},
{"TestLocal_Get1", args{envName: envName, appName: appName}, &api.Application{AppFile: afile, Tm: tm}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -90,7 +90,7 @@ func TestLocal_Delete(t *testing.T) {
func TestLocal_Save(t *testing.T) {
type args struct {
app *Application
app *api.Application
envName string
}
tests := []struct {
@@ -98,7 +98,7 @@ func TestLocal_Save(t *testing.T) {
args args
wantErr bool
}{
{"TestLocal_Save1", args{&Application{AppFile: afile, Tm: nil}, envName}, false},
{"TestLocal_Save1", args{&api.Application{AppFile: afile, Tm: nil}, envName}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -114,12 +114,12 @@ func TestLocal_List(t *testing.T) {
type args struct {
envName string
}
want := make([]*Application, 0)
want = append(want, &Application{afile, tm})
want := make([]*api.Application, 0)
want = append(want, &api.Application{AppFile: afile, Tm: tm})
tests := []struct {
name string
args args
want []*Application
want []*api.Application
wantErr bool
}{
{"TestLocal_List1", args{envName}, want, false},
@@ -205,10 +205,10 @@ func Test_loadFromFile(t *testing.T) {
tests := []struct {
name string
args args
want *Application
want *api.Application
wantErr bool
}{
{"testRespApp", args{fileName: filepath.Join(dir, appName+".yaml")}, &Application{AppFile: afile, Tm: tm}, false},
{"testRespApp", args{fileName: filepath.Join(dir, appName+".yaml")}, &api.Application{AppFile: afile, Tm: tm}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -1,32 +1,31 @@
package application
package appfile
import (
"errors"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/api"
)
// SetWorkload will set user workload for Appfile
func SetWorkload(app *driver.Application, componentName, workloadType string, workloadData map[string]interface{}) error {
func SetWorkload(app *api.Application, componentName, workloadType string, workloadData map[string]interface{}) error {
if app == nil {
return errors.New("app is nil pointer")
}
s, ok := app.Services[componentName]
if !ok {
s = appfile.Service{}
s = api.Service{}
}
s["type"] = workloadType
for k, v := range workloadData {
s[k] = v
}
app.Services[componentName] = s
return app.Validate()
return Validate(app)
}
// SetTrait will set user trait for Appfile
func SetTrait(app *driver.Application, componentName, traitType string, traitData map[string]interface{}) error {
func SetTrait(app *api.Application, componentName, traitType string, traitData map[string]interface{}) error {
if app == nil {
return errors.New("app is nil pointer")
}
@@ -36,7 +35,7 @@ func SetTrait(app *driver.Application, componentName, traitType string, traitDat
s, ok := app.Services[componentName]
if !ok {
s = appfile.Service{}
s = api.Service{}
}
t, ok := s[traitType]
@@ -49,11 +48,11 @@ func SetTrait(app *driver.Application, componentName, traitType string, traitDat
}
s[traitType] = t
app.Services[componentName] = s
return app.Validate()
return Validate(app)
}
// RemoveTrait will remove a trait from Appfile
func RemoveTrait(app *driver.Application, componentName, traitType string) error {
func RemoveTrait(app *api.Application, componentName, traitType string) error {
if app == nil {
return errors.New("app is nil pointer")
}
@@ -67,7 +66,7 @@ func RemoveTrait(app *driver.Application, componentName, traitType string) error
}
// RemoveComponent will remove component from Appfile
func RemoveComponent(app *driver.Application, componentName string) error {
func RemoveComponent(app *api.Application, componentName string) error {
if app == nil {
return errors.New("app is nil pointer")
}
@@ -1,23 +1,22 @@
package application
package appfile
import (
"context"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
ctypes "k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/api"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
)
// BuildRun will build application and deploy from Appfile
func BuildRun(ctx context.Context, app *driver.Application, client client.Client, env *types.EnvMeta, io cmdutil.IOStreams) error {
func BuildRun(ctx context.Context, app *api.Application, client client.Client, env *types.EnvMeta, io cmdutil.IOStreams) error {
o, scopes, err := app.BuildOAMApplication(env, io, app.Tm, true)
if err != nil {
return err
@@ -1,9 +1,10 @@
package storage
package appfile
import (
"os"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/appfile/driver"
"github.com/oam-dev/kubevela/pkg/utils/system"
)
@@ -12,7 +13,7 @@ var store *Storage
// Storage is common storage clientuse it to get app and others resource
type Storage struct {
driver.Driver
api.Driver
}
// GetStorage will create storage driver from the system environment of "STORAGE_DRIVER"
@@ -33,12 +34,12 @@ func GetStorage() *Storage {
}
// List applications storage common implement
func (s *Storage) List(envName string) ([]*driver.Application, error) {
func (s *Storage) List(envName string) ([]*api.Application, error) {
return s.Driver.List(envName)
}
// Save application storage common implement
func (s *Storage) Save(app *driver.Application, envName string) error {
func (s *Storage) Save(app *api.Application, envName string) error {
return s.Driver.Save(app, envName)
}
@@ -48,6 +49,6 @@ func (s *Storage) Delete(envName, appName string) error {
}
// Get application storage common implement
func (s *Storage) Get(envName, appName string) (*driver.Application, error) {
func (s *Storage) Get(envName, appName string) (*api.Application, error) {
return s.Driver.Get(envName, appName)
}
-57
View File
@@ -1,57 +0,0 @@
package driver
import (
"errors"
"fmt"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/template"
)
// Application is an implementation level object for Appfile, all vela commands will access AppFile from Appliction struct here.
type Application struct {
*appfile.AppFile `json:",inline"`
Tm template.Manager
}
// NewApplication will create application object
func NewApplication(f *appfile.AppFile, tm template.Manager) *Application {
if f == nil {
f = appfile.NewAppFile()
}
return &Application{AppFile: f, Tm: tm}
}
// Validate will validate whether an Appfile is valid.
func (app *Application) Validate() error {
if app.Name == "" {
return errors.New("name is required")
}
if len(app.Services) == 0 {
return errors.New("at least one service is required")
}
for name, svc := range app.Services {
for traitName, traitData := range svc.GetApplicationConfig() {
if app.Tm.IsTrait(traitName) {
if _, ok := traitData.(map[string]interface{}); !ok {
return fmt.Errorf("trait %s in '%s' must be map", traitName, name)
}
}
}
}
return nil
}
// Driver is mutli implement interface
type Driver interface {
// List applications
List(envName string) ([]*Application, error)
// Save application
Save(app *Application, envName string) error
// Delete application
Delete(envName, appName string) error
// Get application
Get(envName, appName string) (*Application, error)
// Name of storage driver
Name() string
}
@@ -1,10 +1,10 @@
package storage
package appfile
import (
"os"
"testing"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/driver"
"github.com/oam-dev/kubevela/pkg/utils/system"
)
+5 -5
View File
@@ -15,8 +15,8 @@ import (
k8scmdutil "k8s.io/kubectl/pkg/cmd/util"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
velacmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
@@ -40,7 +40,7 @@ type VelaExecOptions struct {
context.Context
VelaC types.Args
Env *types.EnvMeta
App *driver.Application
App *api.Application
f k8scmdutil.Factory
kcExecOptions *cmdexec.ExecOptions
@@ -118,7 +118,7 @@ func (o *VelaExecOptions) Init(ctx context.Context, c *cobra.Command, argsIn []s
return err
}
o.Env = env
app, err := application.Load(env.Name, o.Args[0])
app, err := appfile.LoadApplication(env.Name, o.Args[0])
if err != nil {
return err
}
@@ -169,7 +169,7 @@ func (o *VelaExecOptions) getComponentName() (string, error) {
o.Cmd.Printf("The service name '%s' is not valid\n", svcName)
}
compName, err := util.AskToChooseOneService(application.GetComponents(o.App))
compName, err := util.AskToChooseOneService(appfile.GetComponents(o.App))
if err != nil {
return "", err
}
+8 -8
View File
@@ -6,6 +6,8 @@ import (
"os"
"testing"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
@@ -17,8 +19,6 @@ import (
k8scmdutil "k8s.io/kubectl/pkg/cmd/util"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
)
@@ -52,10 +52,10 @@ func TestExecCommand(t *testing.T) {
err := o.Init(context.Background(), cmd, []string{"fakeApp"})
errString := fmt.Sprintf(`application "%s" not found`, "fakeApp")
assert.EqualError(t, err, errString)
fakeApp := &driver.Application{
AppFile: &appfile.AppFile{
fakeApp := &api.Application{
AppFile: &api.AppFile{
Name: "fakeApp",
Services: map[string]appfile.Service{
Services: map[string]api.Service{
"fakeComp": map[string]interface{}{},
},
},
@@ -78,10 +78,10 @@ func TestExecCommandPersistentPreRunE(t *testing.T) {
func TestGetComponent(t *testing.T) {
o := &VelaExecOptions{
App: &driver.Application{
AppFile: &appfile.AppFile{
App: &api.Application{
AppFile: &api.AppFile{
Name: "fakeApp",
Services: map[string]appfile.Service{
Services: map[string]api.Service{
"fakeComp1": map[string]interface{}{},
"fakeComp2": map[string]interface{}{},
},
+5 -5
View File
@@ -16,8 +16,8 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/plugins"
"github.com/oam-dev/kubevela/pkg/serverlib"
@@ -29,7 +29,7 @@ type appInitOptions struct {
cmdutil.IOStreams
Env *types.EnvMeta
app *driver.Application
app *api.Application
appName string
workloadName string
workloadType string
@@ -73,7 +73,7 @@ func NewInitCommand(c types.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
return err
}
if err := o.app.Validate(); err != nil {
if err := appfile.Validate(o.app); err != nil {
return err
}
@@ -92,7 +92,7 @@ func NewInitCommand(c types.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
}
ctx := context.Background()
err = application.BuildRun(ctx, o.app, o.client, o.Env, o.IOStreams)
err = appfile.BuildRun(ctx, o.app, o.client, o.Env, o.IOStreams)
if err != nil {
return err
}
+5 -5
View File
@@ -16,8 +16,8 @@ import (
"k8s.io/client-go/kubernetes"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
)
@@ -45,7 +45,7 @@ func NewLogsCommand(c types.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
if err != nil {
return err
}
app, err := application.Load(env.Name, args[0])
app, err := appfile.LoadApplication(env.Name, args[0])
if err != nil {
return err
}
@@ -69,7 +69,7 @@ type Args struct {
Output string
Env *types.EnvMeta
C types.Args
App *driver.Application
App *api.Application
}
// Run refer to the implementation at https://github.com/oam-dev/stern/blob/master/stern/main.go
@@ -79,7 +79,7 @@ func (l *Args) Run(ctx context.Context, ioStreams cmdutil.IOStreams) error {
if err != nil {
return err
}
compName, err := util.AskToChooseOneService(application.GetComponents(l.App))
compName, err := util.AskToChooseOneService(appfile.GetComponents(l.App))
if err != nil {
return err
}
+2 -2
View File
@@ -9,7 +9,7 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/server/apis"
"github.com/oam-dev/kubevela/pkg/serverlib"
@@ -78,7 +78,7 @@ func printComponentList(ctx context.Context, c client.Client, appName string, en
}
func mergeStagingComponents(deployed []apis.ComponentMeta, env *types.EnvMeta, ioStreams cmdutil.IOStreams, fetcher func(name string) (*v1alpha2.Application, error)) []apis.ComponentMeta {
localApps, err := application.List(env.Name)
localApps, err := appfile.List(env.Name)
if err != nil {
ioStreams.Error("list application err", err)
return deployed
+7 -7
View File
@@ -24,8 +24,8 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
velacmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
@@ -40,7 +40,7 @@ type VelaPortForwardOptions struct {
context.Context
VelaC types.Args
Env *types.EnvMeta
App *driver.Application
App *api.Application
f k8scmdutil.Factory
kcPortForwardOptions *cmdpf.PortForwardOptions
@@ -114,7 +114,7 @@ func (o *VelaPortForwardOptions) Init(ctx context.Context, cmd *cobra.Command, a
}
o.Env = env
app, err := application.Load(env.Name, o.Args[0])
app, err := appfile.LoadApplication(env.Name, o.Args[0])
if err != nil {
return err
}
@@ -151,12 +151,12 @@ func getRouteServiceName(appconfig *v1alpha2.ApplicationConfiguration, svcName s
// Complete will complete the config of port-forward
func (o *VelaPortForwardOptions) Complete() error {
svcName, err := util.AskToChooseOneService(application.GetComponents(o.App))
svcName, err := util.AskToChooseOneService(appfile.GetComponents(o.App))
if err != nil {
return err
}
if o.routeTrait {
appconfig, err := application.GetAppConfig(o.Context, o.Client, o.App, o.Env)
appconfig, err := appfile.GetAppConfig(o.Context, o.Client, o.App, o.Env)
if err != nil {
return err
}
@@ -191,7 +191,7 @@ func (o *VelaPortForwardOptions) Complete() error {
}
if len(o.Args) < 2 {
var found bool
_, configs := application.GetServiceConfig(o.App, svcName)
_, configs := appfile.GetServiceConfig(o.App, svcName)
for k, v := range configs {
if k == "port" {
var val string
+14 -14
View File
@@ -16,8 +16,8 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
oam2 "github.com/oam-dev/kubevela/pkg/serverlib"
@@ -115,7 +115,7 @@ func NewAppStatusCommand(c types.Args, ioStreams cmdutil.IOStreams) *cobra.Comma
}
func printAppStatus(ctx context.Context, c client.Client, ioStreams cmdutil.IOStreams, appName string, env *types.EnvMeta, cmd *cobra.Command) error {
app, err := application.Load(env.Name, appName)
app, err := appfile.LoadApplication(env.Name, appName)
if err != nil {
return err
}
@@ -189,7 +189,7 @@ func printComponentStatus(ctx context.Context, c client.Client, ioStreams cmduti
return nil
}
func traitCheckLoop(ctx context.Context, c client.Client, reference runtimev1alpha1.TypedReference, compName string, appConfig *v1alpha2.ApplicationConfiguration, app *driver.Application, timeout time.Duration) (string, string, error) {
func traitCheckLoop(ctx context.Context, c client.Client, reference runtimev1alpha1.TypedReference, compName string, appConfig *v1alpha2.ApplicationConfiguration, app *api.Application, timeout time.Duration) (string, string, error) {
tr, err := oam2.GetUnstructured(ctx, c, appConfig.Namespace, reference)
if err != nil {
return "", "", err
@@ -375,38 +375,38 @@ func trackHealthCheckingStatus(ctx context.Context, c client.Client, compName, a
return compStatusHealthCheckDone, HealthStatusNotDiagnosed, statusInfo, nil
}
func getAppConfig(ctx context.Context, c client.Client, compName, appName string, env *types.EnvMeta) (*driver.Application, *v1alpha2.ApplicationConfiguration, error) {
var app *driver.Application
func getAppConfig(ctx context.Context, c client.Client, compName, appName string, env *types.EnvMeta) (*api.Application, *v1alpha2.ApplicationConfiguration, error) {
var app *api.Application
var err error
if appName != "" {
app, err = application.Load(env.Name, appName)
app, err = appfile.LoadApplication(env.Name, appName)
} else {
app, err = application.MatchAppByComp(env.Name, compName)
app, err = appfile.MatchAppByComp(env.Name, compName)
}
if err != nil {
return nil, nil, err
}
appConfig, err := application.GetAppConfig(ctx, c, app, env)
appConfig, err := appfile.GetAppConfig(ctx, c, app, env)
if err != nil {
return nil, nil, err
}
return app, appConfig, nil
}
func getApp(ctx context.Context, c client.Client, compName, appName string, env *types.EnvMeta) (*driver.Application, *v1alpha2.Application, error) {
var app *driver.Application
func getApp(ctx context.Context, c client.Client, compName, appName string, env *types.EnvMeta) (*api.Application, *v1alpha2.Application, error) {
var app *api.Application
var err error
if appName != "" {
app, err = application.Load(env.Name, appName)
app, err = appfile.LoadApplication(env.Name, appName)
} else {
app, err = application.MatchAppByComp(env.Name, compName)
app, err = appfile.MatchAppByComp(env.Name, compName)
}
if err != nil {
return nil, nil, err
}
appObj, err := application.GetApplication(ctx, c, app, env)
appObj, err := appfile.GetApplication(ctx, c, app, env)
if err != nil {
return nil, nil, err
}
+8 -8
View File
@@ -9,8 +9,8 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/plugins"
@@ -25,7 +25,7 @@ type commandOptions struct {
workloadName string
appName string
app *driver.Application
app *api.Application
traitType string
cmdutil.IOStreams
}
@@ -96,16 +96,16 @@ func (o *commandOptions) Prepare(cmd *cobra.Command, args []string) error {
}
o.appName = args[0]
// get application
app, err := application.Load(o.Env.Name, o.appName)
app, err := appfile.LoadApplication(o.Env.Name, o.appName)
if err != nil {
if application.IsNotFound(o.appName, err) {
if appfile.IsNotFound(o.appName, err) {
return fmt.Errorf("the application %s doesn't exist in current env %s", o.appName, o.Env.Name)
}
return err
}
// get service name
serviceNames := application.GetComponents(app)
serviceNames := appfile.GetComponents(app)
if svcName := cmd.Flag(Service).Value.String(); svcName != "" {
for _, v := range serviceNames {
if v == svcName {
@@ -147,10 +147,10 @@ func (o *commandOptions) DetachTrait(cmd *cobra.Command, args []string) error {
return err
}
var traitType = o.Template.Name
if err = application.RemoveTrait(o.app, o.workloadName, traitType); err != nil {
if err = appfile.RemoveTrait(o.app, o.workloadName, traitType); err != nil {
return err
}
return application.Save(o.app, o.Env.Name)
return appfile.Save(o.app, o.Env.Name)
}
// Run executes create/update/detach trait
+10 -11
View File
@@ -19,9 +19,8 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/appfile/template"
"github.com/oam-dev/kubevela/pkg/application"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/utils/common"
@@ -96,13 +95,13 @@ func saveRemoteAppfile(url string) (string, error) {
}
type buildResult struct {
appFile *appfile.AppFile
appFile *api.AppFile
application *v1alpha2.Application
scopes []oam.Object
}
func (o *AppfileOptions) export(filePath string, quiet bool) (*buildResult, []byte, error) {
var app *appfile.AppFile
var app *api.AppFile
var err error
if !quiet {
o.IO.Info("Parsing vela appfile ...")
@@ -114,9 +113,9 @@ func (o *AppfileOptions) export(filePath string, quiet bool) (*buildResult, []by
return nil, nil, err
}
}
app, err = appfile.LoadFromFile(filePath)
app, err = api.LoadFromFile(filePath)
} else {
app, err = appfile.Load()
app, err = api.Load()
}
if err != nil {
return nil, nil, err
@@ -131,7 +130,7 @@ func (o *AppfileOptions) export(filePath string, quiet bool) (*buildResult, []by
return nil, nil, err
}
appHandler := driver.NewApplication(app, tm)
appHandler := appfile.NewApplication(app, tm)
// new
retApplication, scopes, err := appHandler.BuildOAMApplication(o.Env, o.IO, appHandler.Tm, quiet)
@@ -189,9 +188,9 @@ func (o *AppfileOptions) Run(filePath string) error {
return o.ApplyApp(result.application, result.scopes)
}
func (o *AppfileOptions) saveToAppDir(f *appfile.AppFile) error {
app := &driver.Application{AppFile: f}
return application.Save(app, o.Env.Name)
func (o *AppfileOptions) saveToAppDir(f *api.AppFile) error {
app := &api.Application{AppFile: f}
return appfile.Save(app, o.Env.Name)
}
// ApplyApp applys config resources for the app.
@@ -223,7 +222,7 @@ func (o *AppfileOptions) ApplyApp(app *v1alpha2.Application, scopes []oam.Object
}
func (o *AppfileOptions) apply(app *v1alpha2.Application, scopes []oam.Object) error {
if err := application.Run(context.TODO(), o.Kubecli, app, scopes); err != nil {
if err := appfile.Run(context.TODO(), o.Kubecli, app, scopes); err != nil {
return err
}
return nil
@@ -20,11 +20,11 @@ import (
"context"
"fmt"
"github.com/google/go-cmp/cmp"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -230,8 +230,8 @@ var _ = Describe("Test appFile parser", func() {
Expect(len(components)).To(BeEquivalentTo(1))
Expect(components[0].ObjectMeta).To(BeEquivalentTo(expectComponent.ObjectMeta))
Expect(components[0].TypeMeta).To(BeEquivalentTo(expectComponent.TypeMeta))
Expect(assert.ObjectsAreEqual(components[0].Spec.Workload.Object, expectComponent.Spec.Workload.Object)).To(BeEquivalentTo(true))
fmt.Println(cmp.Diff(components[0].Spec.Workload.Object, expectComponent.Spec.Workload.Object))
Expect(assert.ObjectsAreEqual(components[0].Spec.Workload.Object, expectComponent.Spec.Workload.Object)).To(BeEquivalentTo(true))
})
})
-43
View File
@@ -1,7 +1,6 @@
package cue
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
@@ -9,55 +8,13 @@ import (
"strings"
"cuelang.org/go/cue"
cueJson "cuelang.org/go/pkg/encoding/json"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/oam-dev/kubevela/apis/types"
)
// OutputFieldName is the name of the struct contains the CR data
const OutputFieldName = "output"
// para struct contains the parameter
const specValue = "parameter"
// Eval evaluates the spec with the parameter values
func Eval(templatePath string, value map[string]interface{}) (*unstructured.Unstructured, error) {
r := cue.Runtime{}
b, err := ioutil.ReadFile(filepath.Clean(templatePath))
if err != nil {
return nil, err
}
template, err := r.Compile("", string(b)+BaseTemplate)
if err != nil {
return nil, fmt.Errorf("compile %s err %w", templatePath, err)
}
// fill in the parameter values and evaluate
tempValue := template.Value()
appValue, err := tempValue.Fill(value, specValue).Eval().Struct()
if err != nil {
return nil, fmt.Errorf("fill value to template err %w", err)
}
// fetch the spec struct content
final, err := appValue.FieldByName(OutputFieldName, true)
if err != nil {
return nil, fmt.Errorf("get template %s err %w", OutputFieldName, err)
}
if err := final.Value.Validate(cue.Concrete(true), cue.Final()); err != nil {
return nil, err
}
data, err := cueJson.Marshal(final.Value)
if err != nil {
return nil, fmt.Errorf("marshal final value err %w", err)
}
// need to unmarshal it to a map to get rid of the outer spec name
obj := make(map[string]interface{})
if err = json.Unmarshal([]byte(data), &obj); err != nil {
return nil, err
}
return &unstructured.Unstructured{Object: obj}, nil
}
// GetParameters get parameter from cue template
func GetParameters(templatePath string) ([]types.Parameter, error) {
r := cue.Runtime{}
+1 -46
View File
@@ -4,56 +4,11 @@ import (
"testing"
"cuelang.org/go/cue"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"github.com/stretchr/testify/assert"
"github.com/oam-dev/kubevela/apis/types"
"github.com/stretchr/testify/assert"
)
func TestEvalDeployment(t *testing.T) {
name := "myapp"
image := "nginx:v1"
cr, err := Eval("testdata/workloads/deployment.cue", map[string]interface{}{
"image": image,
"port": 8080,
"name": name,
"env": []interface{}{
map[string]interface{}{
"name": "MYDB",
"value": "true",
},
},
})
assert.NoError(t, err)
assert.Equal(t, cr.GetAPIVersion(), "apps/v1")
assert.Equal(t, cr.GetKind(), "Deployment")
assert.Equal(t, cr.GetName(), name)
// get containers
containers, found, err := unstructured.NestedSlice(cr.UnstructuredContent(), "spec", "template", "spec",
"containers")
assert.True(t, found)
assert.Nil(t, err)
// get first container
c, ok := containers[0].(map[string]interface{})
assert.True(t, ok)
// verify image
imageName, found, err := unstructured.NestedString(c, "image")
assert.True(t, found)
assert.Nil(t, err)
assert.Equal(t, imageName, image)
// verify env
envs, found, err := unstructured.NestedSlice(c, "env")
assert.True(t, found)
assert.Nil(t, err)
env, ok := envs[0].(map[string]interface{})
assert.True(t, ok)
envName, found, err := unstructured.NestedString(env, "name")
assert.True(t, found)
assert.Nil(t, err)
assert.Equal(t, envName, "MYDB")
}
func TestGetParameter(t *testing.T) {
params, err := GetParameters("testdata/workloads/metrics.cue")
assert.NoError(t, err)
+15 -7
View File
@@ -5,8 +5,6 @@ import (
"encoding/json"
"fmt"
"github.com/oam-dev/kubevela/pkg/dsl/task"
"cuelang.org/go/cue"
"cuelang.org/go/cue/build"
"github.com/pkg/errors"
@@ -18,9 +16,19 @@ import (
"github.com/oam-dev/kubevela/pkg/dsl/model"
"github.com/oam-dev/kubevela/pkg/dsl/process"
"github.com/oam-dev/kubevela/pkg/dsl/task"
"github.com/oam-dev/kubevela/pkg/oam"
)
const (
// OutputFieldName is the name of the struct contains the CR data
OutputFieldName = "output"
// OutputsFieldName is the name of the struct contains the map[string]CR data
OutputsFieldName = "outputs"
// PatchFieldName is the name of the struct contains the patch of CR data
PatchFieldName = "patch"
)
var (
metadataAccessor = meta.NewAccessor()
)
@@ -85,7 +93,7 @@ func (wd *workloadDef) Complete(ctx process.Context) error {
if err := inst.Value().Err(); err != nil {
return errors.WithMessagef(err, "workloadDef %s eval", wd.name)
}
output := inst.Lookup("output")
output := inst.Lookup(OutputFieldName)
base, err := model.NewBase(output)
if err != nil {
return errors.WithMessagef(err, "workloadDef %s new base", wd.name)
@@ -121,7 +129,7 @@ func (wd *workloadDef) HealthCheck() error {
}
if wd.output != nil {
bt, _ := json.Marshal(wd.output)
if err := bi.AddFile("output", fmt.Sprintf("output: %s", string(bt))); err != nil {
if err := bi.AddFile(OutputFieldName, fmt.Sprintf("output: %s", string(bt))); err != nil {
return err
}
} else {
@@ -195,7 +203,7 @@ func (td *traitDef) Complete(ctx process.Context) error {
}
}
output := inst.Lookup("output")
output := inst.Lookup(OutputFieldName)
if output.Exists() {
other, err := model.NewOther(output)
if err != nil {
@@ -204,7 +212,7 @@ func (td *traitDef) Complete(ctx process.Context) error {
ctx.PutAssistants(process.Assistant{Ins: other, Type: td.name})
}
outputs := inst.Lookup("outputs")
outputs := inst.Lookup(OutputsFieldName)
st, err := outputs.Struct()
if err == nil {
for i := 0; i < st.Len(); i++ {
@@ -220,7 +228,7 @@ func (td *traitDef) Complete(ctx process.Context) error {
}
}
patcher := inst.Lookup("patch")
patcher := inst.Lookup(PatchFieldName)
if patcher.Exists() {
base, _ := ctx.Output()
p, err := model.NewOther(patcher)
+4 -1
View File
@@ -38,7 +38,10 @@ func (inst *instance) compile() ([]byte, error) {
if err != nil {
return nil, err
}
// compiled object should be final and concrete value
if err := cueInst.Value().Validate(cue.Concrete(true), cue.Final()); err != nil {
return nil, err
}
return cueInst.Value().MarshalJSON()
}
+64 -1
View File
@@ -4,7 +4,8 @@ import (
"testing"
"cuelang.org/go/cue"
"github.com/bmizerany/assert"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
)
@@ -61,3 +62,65 @@ metadata: name: "test"
assert.Equal(t, false, other.IsBase())
}
}
func TestIncompleteError(t *testing.T) {
base := `parameter: {
name: string
// +usage=Which image would you like to use for your service
// +short=i
image: string
// +usage=Which port do you want customer traffic sent to
// +short=p
port: *8080 | int
env: [...{
name: string
value: string
}]
cpu?: string
}
output: {
apiVersion: "apps/v1"
kind: "Deployment"
metadata: name: parameter.name
spec: {
selector:
matchLabels:
app: parameter.name
template: {
metadata:
labels:
app: parameter.name
spec: containers: [{
image: parameter.image
name: parameter.name
env: parameter.env
ports: [{
containerPort: parameter.port
protocol: "TCP"
name: "default"
}]
if parameter["cpu"] != _|_ {
resources: {
limits:
cpu: parameter.cpu
requests:
cpu: parameter.cpu
}
}
}]
}
}
}
`
var r cue.Runtime
inst, err := r.Compile("-", base)
assert.NoError(t, err)
newbase, err := NewBase(inst.Value())
assert.NoError(t, err)
data, err := newbase.Unstructured()
assert.Error(t, err)
var expnil *unstructured.Unstructured
assert.Equal(t, expnil, data)
}
+3 -3
View File
@@ -10,7 +10,7 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/appfile/api"
util2 "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/plugins"
"github.com/oam-dev/kubevela/pkg/server/apis"
@@ -91,7 +91,7 @@ func (s *APIServer) DetachTrait(c *gin.Context) {
// DoAttachTrait executes attaching trait operation
func (s *APIServer) DoAttachTrait(c context.Context, body apis.TraitBody) (string, error) {
// Prepare
var appObj *driver.Application
var appObj *api.Application
fs := pflag.NewFlagSet("trait", pflag.ContinueOnError)
for _, f := range body.Flags {
fs.String(f.Name, f.Value, "")
@@ -125,7 +125,7 @@ func (s *APIServer) DoAttachTrait(c context.Context, body apis.TraitBody) (strin
// DoDetachTrait executes detaching trait operation
func (s *APIServer) DoDetachTrait(c context.Context, envName string, traitType string, componentName string, appName string, staging bool) (string, error) {
var appObj *driver.Application
var appObj *api.Application
var err error
if appName == "" {
appName = componentName
+11 -11
View File
@@ -14,8 +14,8 @@ import (
corev1alpha2 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/server/apis"
)
@@ -176,7 +176,7 @@ func RetrieveApplicationStatusByName(ctx context.Context, c client.Client, appli
// DeleteApp will delete app including server side
func (o *DeleteOptions) DeleteApp() (string, error) {
if err := application.Delete(o.Env.Name, o.AppName); err != nil && !os.IsNotExist(err) {
if err := appfile.Delete(o.Env.Name, o.AppName); err != nil && !os.IsNotExist(err) {
return "", err
}
ctx := context.Background()
@@ -200,32 +200,32 @@ func (o *DeleteOptions) DeleteApp() (string, error) {
// DeleteComponent will delete one component including server side.
func (o *DeleteOptions) DeleteComponent(io cmdutil.IOStreams) (string, error) {
var app *driver.Application
var app *api.Application
var err error
if o.AppName != "" {
app, err = application.Load(o.Env.Name, o.AppName)
app, err = appfile.LoadApplication(o.Env.Name, o.AppName)
} else {
app, err = application.MatchAppByComp(o.Env.Name, o.CompName)
app, err = appfile.MatchAppByComp(o.Env.Name, o.CompName)
}
if err != nil {
return "", err
}
if len(application.GetComponents(app)) <= 1 {
if len(appfile.GetComponents(app)) <= 1 {
return o.DeleteApp()
}
// Remove component from local appfile
if err := application.RemoveComponent(app, o.CompName); err != nil {
if err := appfile.RemoveComponent(app, o.CompName); err != nil {
return "", err
}
if err := application.Save(app, o.Env.Name); err != nil {
if err := appfile.Save(app, o.Env.Name); err != nil {
return "", err
}
// Remove component from appConfig in k8s cluster
ctx := context.Background()
if err := application.BuildRun(ctx, app, o.Client, o.Env, io); err != nil {
if err := appfile.BuildRun(ctx, app, o.Client, o.Env, io); err != nil {
return "", err
}
@@ -257,7 +257,7 @@ func chooseSvc(services []string) (string, error) {
}
// GetServicesWhenDescribingApplication gets the target services list either from cli `--svc` flag or from survey
func GetServicesWhenDescribingApplication(cmd *cobra.Command, app *driver.Application) ([]string, error) {
func GetServicesWhenDescribingApplication(cmd *cobra.Command, app *api.Application) ([]string, error) {
var svcFlag string
var svcFlagStatus string
// to store the value of flag `--svc` set in Cli, or selected value in survey
+16 -14
View File
@@ -5,14 +5,16 @@ import (
"fmt"
"strings"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/appfile"
"cuelang.org/go/cue"
plur "github.com/gertd/go-pluralize"
"github.com/spf13/pflag"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/plugins"
)
@@ -147,7 +149,7 @@ func ValidateAndMutateForCore(traitType, workloadName string, flags *pflag.FlagS
}
// AddOrUpdateTrait attach trait to workload
func AddOrUpdateTrait(env *types.EnvMeta, appName string, componentName string, flagSet *pflag.FlagSet, template types.Capability) (*driver.Application, error) {
func AddOrUpdateTrait(env *types.EnvMeta, appName string, componentName string, flagSet *pflag.FlagSet, template types.Capability) (*api.Application, error) {
err := ValidateAndMutateForCore(template.Name, componentName, flagSet, env)
if err != nil {
return nil, err
@@ -155,12 +157,12 @@ func AddOrUpdateTrait(env *types.EnvMeta, appName string, componentName string,
if appName == "" {
appName = componentName
}
app, err := application.Load(env.Name, appName)
app, err := appfile.LoadApplication(env.Name, appName)
if err != nil {
return app, err
}
traitAlias := template.Name
traitData, err := application.GetTraitsByType(app, componentName, traitAlias)
traitData, err := appfile.GetTraitsByType(app, componentName, traitAlias)
if err != nil {
return app, err
}
@@ -188,19 +190,19 @@ func AddOrUpdateTrait(env *types.EnvMeta, appName string, componentName string,
return nil, fmt.Errorf("get flag(s) \"%s\" err %w", name, err)
}
}
if err = application.SetTrait(app, componentName, traitAlias, traitData); err != nil {
if err = appfile.SetTrait(app, componentName, traitAlias, traitData); err != nil {
return app, err
}
return app, application.Save(app, env.Name)
return app, appfile.Save(app, env.Name)
}
// TraitOperationRun will check if it's a stage operation before run
func TraitOperationRun(ctx context.Context, c client.Client, env *types.EnvMeta, appObj *driver.Application,
func TraitOperationRun(ctx context.Context, c client.Client, env *types.EnvMeta, appObj *api.Application,
staging bool, io cmdutil.IOStreams) (string, error) {
if staging {
return "Staging saved", nil
}
err := application.BuildRun(ctx, appObj, c, env, io)
err := appfile.BuildRun(ctx, appObj, c, env, io)
if err != nil {
return "", err
}
@@ -208,18 +210,18 @@ func TraitOperationRun(ctx context.Context, c client.Client, env *types.EnvMeta,
}
// PrepareDetachTrait will detach trait in local AppFile
func PrepareDetachTrait(envName string, traitType string, componentName string, appName string) (*driver.Application, error) {
var appObj *driver.Application
func PrepareDetachTrait(envName string, traitType string, componentName string, appName string) (*api.Application, error) {
var appObj *api.Application
var err error
if appName == "" {
appName = componentName
}
if appObj, err = application.Load(envName, appName); err != nil {
if appObj, err = appfile.LoadApplication(envName, appName); err != nil {
return appObj, err
}
if err = application.RemoveTrait(appObj, componentName, traitType); err != nil {
if err = appfile.RemoveTrait(appObj, componentName, traitType); err != nil {
return appObj, err
}
return appObj, application.Save(appObj, envName)
return appObj, appfile.Save(appObj, envName)
}
+10 -8
View File
@@ -5,6 +5,10 @@ import (
"encoding/json"
"fmt"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/appfile"
runtimev1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
v12 "k8s.io/api/autoscaling/v1"
v1 "k8s.io/api/core/v1"
@@ -14,8 +18,6 @@ import (
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/standard.oam.dev/v1alpha1"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
autoscalers "github.com/oam-dev/kubevela/pkg/controller/standard.oam.dev/v1alpha1/autoscaler"
"github.com/oam-dev/kubevela/pkg/oam"
)
@@ -46,7 +48,7 @@ func GetChecker(traitType string, c client.Client) Checker {
// Checker defines the interface of checker
type Checker interface {
Check(ctx context.Context, reference runtimev1alpha1.TypedReference, compName string, appConfig *v1alpha2.ApplicationConfiguration, app *driver.Application) (CheckStatus, string, error)
Check(ctx context.Context, reference runtimev1alpha1.TypedReference, compName string, appConfig *v1alpha2.ApplicationConfiguration, app *api.Application) (CheckStatus, string, error)
}
// DefaultChecker defines the default checker
@@ -55,7 +57,7 @@ type DefaultChecker struct {
}
// Check default check object if exist and print the configs
func (d *DefaultChecker) Check(ctx context.Context, reference runtimev1alpha1.TypedReference, compName string, appConfig *v1alpha2.ApplicationConfiguration, app *driver.Application) (CheckStatus, string, error) {
func (d *DefaultChecker) Check(ctx context.Context, reference runtimev1alpha1.TypedReference, compName string, appConfig *v1alpha2.ApplicationConfiguration, app *api.Application) (CheckStatus, string, error) {
tr, err := GetUnstructured(ctx, d.c, appConfig.Namespace, reference)
if err != nil {
return StatusChecking, "", err
@@ -65,7 +67,7 @@ func (d *DefaultChecker) Check(ctx context.Context, reference runtimev1alpha1.Ty
message, err := GetStatusFromObject(tr)
return StatusDone, message, err
}
traitData, err := application.GetTraitsByType(app, compName, traitType)
traitData, err := appfile.GetTraitsByType(app, compName, traitType)
if err != nil {
return StatusDone, err.Error(), err
}
@@ -82,7 +84,7 @@ type MetricChecker struct {
}
// Check metrics
func (d *MetricChecker) Check(ctx context.Context, reference runtimev1alpha1.TypedReference, _ string, appConfig *v1alpha2.ApplicationConfiguration, _ *driver.Application) (CheckStatus, string, error) {
func (d *MetricChecker) Check(ctx context.Context, reference runtimev1alpha1.TypedReference, _ string, appConfig *v1alpha2.ApplicationConfiguration, _ *api.Application) (CheckStatus, string, error) {
metric := v1alpha1.MetricsTrait{}
if err := d.c.Get(ctx, client.ObjectKey{Namespace: appConfig.Namespace, Name: reference.Name}, &metric); err != nil {
return StatusChecking, "", err
@@ -109,7 +111,7 @@ type RouteChecker struct {
}
// Check understand route status
func (d *RouteChecker) Check(ctx context.Context, reference runtimev1alpha1.TypedReference, _ string, appConfig *v1alpha2.ApplicationConfiguration, _ *driver.Application) (CheckStatus, string, error) {
func (d *RouteChecker) Check(ctx context.Context, reference runtimev1alpha1.TypedReference, _ string, appConfig *v1alpha2.ApplicationConfiguration, _ *api.Application) (CheckStatus, string, error) {
route := v1alpha1.Route{}
if err := d.c.Get(ctx, client.ObjectKey{Namespace: appConfig.Namespace, Name: reference.Name}, &route); err != nil {
return StatusChecking, "", err
@@ -155,7 +157,7 @@ type AutoscalerChecker struct {
}
// Check should understand autoscale trait status
func (d *AutoscalerChecker) Check(ctx context.Context, ref runtimev1alpha1.TypedReference, _ string, appConfig *v1alpha2.ApplicationConfiguration, _ *driver.Application) (CheckStatus, string, error) {
func (d *AutoscalerChecker) Check(ctx context.Context, ref runtimev1alpha1.TypedReference, _ string, appConfig *v1alpha2.ApplicationConfiguration, _ *api.Application) (CheckStatus, string, error) {
traitName := ref.Name
var scaler v1alpha1.Autoscaler
if err := d.c.Get(ctx, client.ObjectKey{Namespace: appConfig.Namespace, Name: traitName}, &scaler); err != nil {
+13 -13
View File
@@ -11,8 +11,8 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile/storage/driver"
"github.com/oam-dev/kubevela/pkg/application"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/plugins"
@@ -23,30 +23,30 @@ type RunOptions struct {
Env *types.EnvMeta
WorkloadName string
KubeClient client.Client
App *driver.Application
App *api.Application
AppName string
Staging bool
util.IOStreams
}
// LoadIfExist will load Application from local dir
func LoadIfExist(envName string, workloadName string, appGroup string) (*driver.Application, error) {
func LoadIfExist(envName string, workloadName string, appGroup string) (*api.Application, error) {
var appName string
if appGroup != "" {
appName = appGroup
} else {
appName = workloadName
}
app, err := application.Load(envName, appName)
app, err := appfile.LoadApplication(envName, appName)
// can't handle
if err != nil && !application.IsNotFound(appName, err) {
if err != nil && !appfile.IsNotFound(appName, err) {
return nil, err
}
// compatible application not found
if app == nil {
app, err = application.NewEmptyApplication()
app, err = appfile.NewEmptyApplication()
if err != nil {
return nil, err
}
@@ -57,12 +57,12 @@ func LoadIfExist(envName string, workloadName string, appGroup string) (*driver.
}
// BaseComplete will construct an Application from cli parameters.
func BaseComplete(envName string, workloadName string, appName string, flagSet *pflag.FlagSet, workloadType string) (*driver.Application, error) {
func BaseComplete(envName string, workloadName string, appName string, flagSet *pflag.FlagSet, workloadType string) (*api.Application, error) {
app, err := LoadIfExist(envName, workloadName, appName)
if err != nil {
return nil, err
}
tp, workloadData := application.GetWorkload(app, workloadName)
tp, workloadData := appfile.GetWorkload(app, workloadName)
if tp == "" {
if workloadType == "" {
return nil, fmt.Errorf("must specify workload type for application %s", workloadName)
@@ -127,18 +127,18 @@ func BaseComplete(envName string, workloadName string, appName string, flagSet *
return nil, fmt.Errorf("get flag(s) \"%s\" err %w", v.Name, err)
}
}
if err = application.SetWorkload(app, workloadName, tp, workloadData); err != nil {
if err = appfile.SetWorkload(app, workloadName, tp, workloadData); err != nil {
return app, err
}
return app, application.Save(app, envName)
return app, appfile.Save(app, envName)
}
// BaseRun will check if it's a stating operation before run
func BaseRun(staging bool, app *driver.Application, kubeClient client.Client, env *types.EnvMeta, io cmdutil.IOStreams) (string, error) {
func BaseRun(staging bool, app *api.Application, kubeClient client.Client, env *types.EnvMeta, io cmdutil.IOStreams) (string, error) {
if staging {
return "Staging saved", nil
}
if err := application.BuildRun(context.Background(), app, kubeClient, env, io); err != nil {
if err := appfile.BuildRun(context.Background(), app, kubeClient, env, io); err != nil {
err = fmt.Errorf("create app err: %w", err)
return "", err
}