diff --git a/api/api.go b/api/api.go index 6cc06a4f7..9371e7683 100644 --- a/api/api.go +++ b/api/api.go @@ -1,2 +1,2 @@ -// package api contains all api types of KubeVela +// Package api contains all api types of KubeVela package api diff --git a/api/types/capability.go b/api/types/capability.go index 83ad057f4..4ebfa7b9f 100644 --- a/api/types/capability.go +++ b/api/types/capability.go @@ -119,6 +119,7 @@ func SetFlagBy(flags *pflag.FlagSet, v Parameter) { if v.Alias != "" { name = v.Alias } + // nolint:exhaustive switch v.Type { case cue.IntKind: var vv int64 @@ -150,6 +151,8 @@ func SetFlagBy(flags *pflag.FlagSet, v Parameter) { vv = val } flags.Float64P(name, v.Short, vv, v.Usage) + default: + // other types not supported yet } } @@ -160,6 +163,7 @@ var CapabilityCmpOptions = []cmp.Option{ a.Usage != b.Usage || a.Type != b.Type { return false } + // nolint:exhaustive switch a.Type { case cue.IntKind: var va, vb int64 @@ -211,6 +215,8 @@ var CapabilityCmpOptions = []cmp.Option{ vb = valb } return va == vb + default: + // complex type not supported, will regard them as not changed. } return true })} diff --git a/cmd/core/main.go b/cmd/core/main.go index b5bf12be2..3f99d9645 100644 --- a/cmd/core/main.go +++ b/cmd/core/main.go @@ -241,6 +241,7 @@ func waitWebhookSecretVolume(certDir string, timeout, interval time.Duration) er } } +//nolint:unparam func makeSignalHandler(log logr.Logger, kubecli client.Client) (stopCh <-chan struct{}) { stop := make(chan struct{}) c := make(chan os.Signal, 2) diff --git a/pkg/appfile/appfile.go b/pkg/appfile/appfile.go index 3f7fc3b42..d9460f518 100644 --- a/pkg/appfile/appfile.go +++ b/pkg/appfile/appfile.go @@ -18,11 +18,14 @@ import ( ) var ( + //nolint ErrImageNotDefined = errors.New("image not defined") ) +// DefaultAppfilePath defines the default file path that used by `vela up` command const DefaultAppfilePath = "./vela.yaml" +// AppFile defines the spec of KubeVela Appfile type AppFile struct { Name string `json:"name"` CreateTime time.Time `json:"createTime,omitempty"` @@ -33,6 +36,7 @@ type AppFile struct { configGetter configGetter } +// NewAppFile init an empty AppFile struct func NewAppFile() *AppFile { return &AppFile{ Services: make(map[string]Service), @@ -41,10 +45,12 @@ func NewAppFile() *AppFile { } } +// Load will load appfile from default path func Load() (*AppFile, error) { return LoadFromFile(DefaultAppfilePath) } +// LoadFromFile will read the file and load the AppFile struct func LoadFromFile(filename string) (*AppFile, error) { b, err := ioutil.ReadFile(filepath.Clean(filename)) if err != nil { @@ -152,6 +158,8 @@ func addHealthScope(appConfig *v1alpha2.ApplicationConfiguration) *v1alpha2.Heal } return health } + +// FormatDefaultHealthScopeName will create a default health scope name. func FormatDefaultHealthScopeName(appName string) string { return appName + "-default-health" } diff --git a/pkg/appfile/build.go b/pkg/appfile/build.go index e1bdf33d5..cb2230976 100644 --- a/pkg/appfile/build.go +++ b/pkg/appfile/build.go @@ -8,22 +8,25 @@ import ( cmdutil "github.com/oam-dev/kubevela/pkg/commands/util" ) +// Build defines the build section of AppFile type Build struct { Push Push `json:"push,omitempty"` Docker Docker `json:"docker,omitempty"` } +// Docker defines the docker build section type Docker struct { File string `json:"file"` Context string `json:"context"` } +// Push defines where to push your image type Push struct { Local string `json:"local,omitempty"` Registry string `json:"registry,omitempty"` } -func asyncLog(reader io.ReadCloser, stream cmdutil.IOStreams) { +func asyncLog(reader io.Reader, stream cmdutil.IOStreams) { cache := "" buf := make([]byte, 1024) for { @@ -44,6 +47,7 @@ func asyncLog(reader io.ReadCloser, stream cmdutil.IOStreams) { } } +// BuildImage will build a image with name and context. func (b *Build) BuildImage(io cmdutil.IOStreams, image string) error { //nolint:gosec // TODO(hongchaodeng): remove this dependency by using go lib diff --git a/pkg/appfile/service.go b/pkg/appfile/service.go index ea3a07969..577e8a456 100644 --- a/pkg/appfile/service.go +++ b/pkg/appfile/service.go @@ -18,10 +18,13 @@ import ( mycue "github.com/oam-dev/kubevela/pkg/cue" ) +// Service defines the service spec for AppFile, it will contain all information a service realted including OAM component, traits, source to image, etc... type Service map[string]interface{} +// DefaultWorkloadType defines the default service type if no type specified in Appfile const DefaultWorkloadType = "webservice" +// GetType get type from AppFile func (s Service) GetType() string { t, ok := s["type"] if !ok { @@ -30,6 +33,7 @@ func (s Service) GetType() string { return t.(string) } +// GetUserConfigName get user config from AppFile, it will contain config file in it. func (s Service) GetUserConfigName() string { t, ok := s["config"] if !ok { @@ -38,6 +42,7 @@ func (s Service) GetUserConfigName() string { return t.(string) } +// GetConfig will get OAM workload and trait information exclude inner section('build','type' and 'config') func (s Service) GetConfig() map[string]interface{} { config := make(map[string]interface{}) outerLoop: @@ -51,6 +56,7 @@ outerLoop: return config } +// GetBuild will get source to image build info func (s Service) GetBuild() *Build { v, ok := s["build"] if !ok { @@ -137,6 +143,7 @@ func (s Service) RenderService(tm template.Manager, name, ns string, cg configGe return acComp, component, nil } +// GetServices will get all services defined in AppFile func (af *AppFile) GetServices() map[string]Service { return af.Services } diff --git a/pkg/appfile/template/fake.go b/pkg/appfile/template/fake.go index 7eb059a3c..8c4a9987e 100644 --- a/pkg/appfile/template/fake.go +++ b/pkg/appfile/template/fake.go @@ -1,9 +1,11 @@ package template +// FakeTemplateManager defines a fake for test type FakeTemplateManager struct { *manager } +// NewFakeTemplateManager create a fake manager for test func NewFakeTemplateManager() *FakeTemplateManager { return &FakeTemplateManager{ manager: newManager(), diff --git a/pkg/appfile/template/manager.go b/pkg/appfile/template/manager.go index 78b06da7c..91bb8ad8f 100644 --- a/pkg/appfile/template/manager.go +++ b/pkg/appfile/template/manager.go @@ -5,11 +5,13 @@ import ( "github.com/oam-dev/kubevela/pkg/plugins" ) +// Manager defines a manager for template type Manager interface { IsTrait(key string) bool LoadTemplate(key string) (tmpl string) } +// Load will load all installed capabilities and create a manager func Load() (Manager, error) { caps, err := plugins.LoadAllInstalledCapability() if err != nil { @@ -25,6 +27,7 @@ func Load() (Manager, error) { return m, nil } +// Template defines a raw template struct type Template struct { Captype types.CapType Raw string diff --git a/pkg/application/app.go b/pkg/application/app.go index 04a8ecb04..b07ced6cf 100644 --- a/pkg/application/app.go +++ b/pkg/application/app.go @@ -26,6 +26,7 @@ import ( "github.com/oam-dev/kubevela/pkg/utils/system" ) +// 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 @@ -38,6 +39,7 @@ func newApplication(f *appfile.AppFile, tm template.Manager) *Application { return &Application{AppFile: f, tm: tm} } +// LoadFromFile will load application from file func LoadFromFile(fileName string) (*Application, error) { tm, err := template.Load() if err != nil { @@ -59,6 +61,7 @@ func LoadFromFile(fileName string) (*Application, error) { return app, app.Validate() } +// Load will load application with env and name from default vela home dir. func Load(envName, appName string) (*Application, error) { appDir, err := getApplicationDir(envName) if err != nil { @@ -67,6 +70,7 @@ func Load(envName, appName string) (*Application, error) { return LoadFromFile(filepath.Join(appDir, appName+".yaml")) } +// Delete will delete an app along with it's appfile. func Delete(envName, appName string) error { appDir, err := getApplicationDir(envName) if err != nil { @@ -75,6 +79,7 @@ func Delete(envName, appName string) error { return os.Remove(filepath.Join(appDir, appName+".yaml")) } +// List will list all apps func List(envName string) ([]*Application, error) { appDir, err := getApplicationDir(envName) if err != nil { @@ -101,6 +106,7 @@ func List(envName string) ([]*Application, error) { return apps, nil } +// MatchAppByComp will get application with componentName without AppName. func MatchAppByComp(envName, compName string) (*Application, error) { apps, err := List(envName) if err != nil { @@ -116,6 +122,7 @@ func MatchAppByComp(envName, compName string) (*Application, error) { return nil, fmt.Errorf("no app found contains %s in env %s", compName, envName) } +// Save will save appfile into default dir. func (app *Application) Save(envName string) error { appDir, err := getApplicationDir(envName) if err != nil { @@ -133,6 +140,7 @@ func (app *Application) Save(envName string) error { return ioutil.WriteFile(filepath.Join(appDir, app.Name+".yaml"), out, 0644) } +// Validate will validate whether an Appfile is valid. func (app *Application) Validate() error { if app.Name == "" { return errors.New("name is required") @@ -152,6 +160,7 @@ func (app *Application) Validate() error { return nil } +// GetComponents will get oam components from Appfile. func (app *Application) GetComponents() []string { var components []string for name := range app.Services { @@ -161,6 +170,7 @@ func (app *Application) GetComponents() []string { return components } +// GetServiceConfig will get service type and it's configuration func (app *Application) GetServiceConfig(componentName string) (string, map[string]interface{}) { svc, ok := app.Services[componentName] if !ok { @@ -169,6 +179,7 @@ func (app *Application) GetServiceConfig(componentName string) (string, map[stri return svc.GetType(), svc.GetConfig() } +// GetWorkload will get workload type and it's configuration func (app *Application) GetWorkload(componentName string) (string, map[string]interface{}) { svcType, config := app.GetServiceConfig(componentName) if svcType == "" { @@ -184,6 +195,7 @@ func (app *Application) GetWorkload(componentName string) (string, map[string]in return svcType, workloadData } +// GetTraitNames will list all traits attached to the specified component. func (app *Application) GetTraitNames(componentName string) ([]string, error) { tt, err := app.GetTraits(componentName) if err != nil { @@ -196,6 +208,7 @@ func (app *Application) GetTraitNames(componentName string) ([]string, error) { return names, nil } +// GetTraits will list all traits and it's configurations attached to the specified component. func (app *Application) GetTraits(componentName string) (map[string]map[string]interface{}, error) { _, config := app.GetServiceConfig(componentName) traitsData := make(map[string]map[string]interface{}) @@ -212,6 +225,7 @@ func (app *Application) GetTraits(componentName string) (map[string]map[string]i return traitsData, nil } +// 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 (app *Application) GetTraitsByType(componentName, traitType string) (map[string]interface{}, error) { service, ok := app.Services[componentName] if !ok { @@ -224,6 +238,7 @@ func (app *Application) GetTraitsByType(componentName, traitType string) (map[st return t.(map[string]interface{}), nil } +// OAM will convert an AppFile to OAM objects // TODO(wonderflow) add scope support here func (app *Application) OAM(env *types.EnvMeta, io cmdutil.IOStreams, silence bool) ([]*v1alpha2.Component, *v1alpha2.ApplicationConfiguration, []oam.Object, error) { comps, appConfig, scopes, err := app.RenderOAM(env.Namespace, io, app.tm, silence) @@ -239,6 +254,7 @@ func getApplicationDir(envName string) (string, error) { return appDir, err } +// GetAppConfig will get AppConfig from K8s cluster. func GetAppConfig(ctx context.Context, c client.Client, app *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 { diff --git a/pkg/application/modify.go b/pkg/application/modify.go index df01aac39..dc540df0c 100644 --- a/pkg/application/modify.go +++ b/pkg/application/modify.go @@ -6,6 +6,7 @@ import ( "github.com/oam-dev/kubevela/pkg/appfile" ) +// SetWorkload will set user workload for Appfile func (app *Application) SetWorkload(componentName, workloadType string, workloadData map[string]interface{}) error { if app == nil { return errors.New("app is nil pointer") @@ -23,6 +24,7 @@ func (app *Application) SetWorkload(componentName, workloadType string, workload return app.Validate() } +// SetTrait will set user trait for Appfile func (app *Application) SetTrait(componentName, traitType string, traitData map[string]interface{}) error { if app == nil { return errors.New("app is nil pointer") @@ -49,6 +51,7 @@ func (app *Application) SetTrait(componentName, traitType string, traitData map[ return app.Validate() } +// RemoveTrait will remove a trait from Appfile func (app *Application) RemoveTrait(componentName, traitType string) error { if app == nil { return errors.New("app is nil pointer") @@ -62,6 +65,7 @@ func (app *Application) RemoveTrait(componentName, traitType string) error { return nil } +// RemoveComponent will remove component from Appfile func (app *Application) RemoveComponent(componentName string) error { if app == nil { return errors.New("app is nil pointer") diff --git a/pkg/application/run.go b/pkg/application/run.go index 404ec605a..33fe95d4f 100644 --- a/pkg/application/run.go +++ b/pkg/application/run.go @@ -13,6 +13,7 @@ import ( cmdutil "github.com/oam-dev/kubevela/pkg/commands/util" ) +// BuildRun will build OAM and deploy from Appfile func (app *Application) BuildRun(ctx context.Context, client client.Client, env *types.EnvMeta, io cmdutil.IOStreams) error { components, appconfig, scopes, err := app.OAM(env, io, true) if err != nil { @@ -21,6 +22,7 @@ func (app *Application) BuildRun(ctx context.Context, client client.Client, env return app.Run(ctx, client, appconfig, components, scopes) } +// Run will deploy OAM objects. func (app *Application) Run(ctx context.Context, client client.Client, ac *v1alpha2.ApplicationConfiguration, comps []*v1alpha2.Component, scopes []oam.Object) error { for _, comp := range comps { @@ -34,6 +36,7 @@ func (app *Application) Run(ctx context.Context, client client.Client, return CreateOrUpdateAppConfig(ctx, client, ac) } +// CreateOrUpdateComponent will create if not exist and update if exists. func CreateOrUpdateComponent(ctx context.Context, client client.Client, comp *v1alpha2.Component) error { var getc v1alpha2.Component key := ctypes.NamespacedName{Name: comp.Name, Namespace: comp.Namespace} @@ -47,6 +50,7 @@ func CreateOrUpdateComponent(ctx context.Context, client client.Client, comp *v1 return client.Update(ctx, comp) } +// CreateOrUpdateAppConfig will create if not exist and update if exists. func CreateOrUpdateAppConfig(ctx context.Context, client client.Client, appConfig *v1alpha2.ApplicationConfiguration) error { var geta v1alpha2.ApplicationConfiguration key := ctypes.NamespacedName{Name: appConfig.Name, Namespace: appConfig.Namespace} @@ -64,6 +68,7 @@ func CreateOrUpdateAppConfig(ctx context.Context, client client.Client, appConfi return client.Update(ctx, appConfig) } +// CreateScopes will create all scopes func CreateScopes(ctx context.Context, client client.Client, scopes []oam.Object) error { for _, obj := range scopes { key := ctypes.NamespacedName{Name: obj.GetName(), Namespace: obj.GetNamespace()} diff --git a/pkg/commands/init.go b/pkg/commands/init.go index bb8ea9df2..39cc4e467 100644 --- a/pkg/commands/init.go +++ b/pkg/commands/init.go @@ -179,7 +179,8 @@ func (o *appInitOptions) Workload() error { return fmt.Errorf("read workload name err %v", err) } fs := pflag.NewFlagSet("workload", pflag.ContinueOnError) - for _, p := range workload.Parameters { + for _, pp := range workload.Parameters { + p := pp if p.Name == "name" { continue } @@ -197,6 +198,7 @@ func (o *appInitOptions) Workload() error { usage += " (optional): " } } + // nolint:exhaustive switch p.Type { case cue.StringKind: var data string @@ -272,6 +274,8 @@ func (o *appInitOptions) Workload() error { return fmt.Errorf("read param %s err %v", p.Name, err) } fs.Bool(p.Name, data, p.Usage) + default: + // other type not supported } } o.app, err = oam.BaseComplete(o.Env.Name, o.workloadName, o.appName, fs, o.workloadType) diff --git a/pkg/commands/refresh.go b/pkg/commands/refresh.go index ffb3db9c6..87e92d282 100644 --- a/pkg/commands/refresh.go +++ b/pkg/commands/refresh.go @@ -115,6 +115,8 @@ func addStsRow(sts refreshStatus, report map[refreshStatus][]types.Capability, t case deleted: stsIcon = "-" stsColor = red + case unchanged: + // normal color display } for _, cap := range caps { t.AddRow( diff --git a/pkg/commands/status.go b/pkg/commands/status.go index e88659486..ad92c5c22 100644 --- a/pkg/commands/status.go +++ b/pkg/commands/status.go @@ -292,6 +292,7 @@ TrackDeployLoop: if err != nil { return compStatusUnknown, err } + // nolint:exhaustive switch deployStatus { case compStatusDeploying: continue @@ -443,6 +444,7 @@ func applySpinnerNewSuffix(s *spinner.Spinner, suffix string) { func getHealthStatusColor(s HealthStatus) *color.Color { var c *color.Color + // nolint:exhaustive switch s { case HealthStatusHealthy: c = green diff --git a/pkg/commands/up.go b/pkg/commands/up.go index e460df8cd..cd9ff269d 100644 --- a/pkg/commands/up.go +++ b/pkg/commands/up.go @@ -5,11 +5,12 @@ import ( "context" "fmt" "io/ioutil" - "net/http" "os" "path/filepath" "strings" + "github.com/oam-dev/kubevela/pkg/utils/common" + "github.com/crossplane/oam-kubernetes-runtime/apis/core/v1alpha2" "github.com/crossplane/oam-kubernetes-runtime/pkg/oam" "github.com/pkg/errors" @@ -75,19 +76,13 @@ type AppfileOptions struct { } func saveRemoteAppfile(url string) (string, error) { - //nolint:gosec - resp, err := http.Get(url) - if err != nil { - return "", err - } - //nolint:errcheck - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := common.HTTPGet(context.Background(), url) if err != nil { return "", err } dest := "vela.yaml" - return dest, ioutil.WriteFile(dest, body, 0600) + //nolint:gosec + return dest, ioutil.WriteFile(dest, body, 0644) } func (o *AppfileOptions) Run(filePath string) error { diff --git a/pkg/controller/dependency/promethus.go b/pkg/controller/dependency/promethus.go index d3d8ad901..d7ceadacd 100644 --- a/pkg/controller/dependency/promethus.go +++ b/pkg/controller/dependency/promethus.go @@ -13,6 +13,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) +// InstallPromethusInstance will install promethus instance for vela-core func InstallPromethusInstance(kubecli client.Client) error { var promIns = monitoring.Prometheus{} err := kubecli.Get(context.Background(), types.NamespacedName{Namespace: "monitoring", Name: "oam"}, &promIns) diff --git a/pkg/controller/utils/utils.go b/pkg/controller/utils/utils.go index 57fabb4e0..de3292cb4 100644 --- a/pkg/controller/utils/utils.go +++ b/pkg/controller/utils/utils.go @@ -13,8 +13,10 @@ import ( "k8s.io/apimachinery/pkg/util/intstr" ) +// LabelPodSpecable defines whether a workload has podSpec or not. const LabelPodSpecable = "workload.oam.dev/podspecable" +// GetPodSpecPath get podSpec field and label func GetPodSpecPath(workloadDef *v1alpha2.WorkloadDefinition) (string, bool) { if workloadDef.Spec.PodSpecPath != "" { return workloadDef.Spec.PodSpecPath, true @@ -30,6 +32,7 @@ func GetPodSpecPath(workloadDef *v1alpha2.WorkloadDefinition) (string, bool) { return "", ok } +// DiscoveryFromPodSpec will discover pods from podSpec func DiscoveryFromPodSpec(w *unstructured.Unstructured, fieldPath string) ([]intstr.IntOrString, error) { paved := fieldpath.Pave(w.Object) obj, err := paved.GetValue(fieldPath) diff --git a/pkg/controller/v1alpha1/autoscaler/autoscaler_controller.go b/pkg/controller/v1alpha1/autoscaler/autoscaler_controller.go index a14eefcdc..42f1245c8 100644 --- a/pkg/controller/v1alpha1/autoscaler/autoscaler_controller.go +++ b/pkg/controller/v1alpha1/autoscaler/autoscaler_controller.go @@ -61,6 +61,7 @@ type AutoscalerReconciler struct { record event.Recorder } +// Reconcile is the main logic for autoscaler controller // +kubebuilder:rbac:groups=standard.oam.dev,resources=autoscalers,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=standard.oam.dev,resources=autoscalers/status,verbs=get;update;patch func (r *AutoscalerReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) { @@ -139,6 +140,7 @@ func (r *AutoscalerReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) return ctrl.Result{}, nil } +// SetupWithManager will setup with event recorder func (r *AutoscalerReconciler) SetupWithManager(mgr ctrl.Manager) error { r.record = event.NewAPIRecorder(mgr.GetEventRecorderFor("Autoscaler")). WithAnnotations("controller", "Autoscaler") diff --git a/pkg/controller/v1alpha1/autoscaler/keda.go b/pkg/controller/v1alpha1/autoscaler/keda.go index 884853ac5..042a58a07 100644 --- a/pkg/controller/v1alpha1/autoscaler/keda.go +++ b/pkg/controller/v1alpha1/autoscaler/keda.go @@ -99,6 +99,7 @@ func (r *AutoscalerReconciler) scaleByKEDA(scaler v1alpha1.Autoscaler, namespace return nil } +// CronTypeCondition defines the cron type for autoscaler type CronTypeCondition struct { // StartAt is the time when the scaler starts, in format `"HHMM"` for example, "08:00" StartAt string `json:"startAt,omitempty"` @@ -116,6 +117,7 @@ type CronTypeCondition struct { Timezone string `json:"timezone,omitempty"` } +// GetCronTypeCondition will get condition from map func GetCronTypeCondition(condition map[string]string) (*CronTypeCondition, error) { data, err := json.Marshal(condition) if err != nil { diff --git a/pkg/controller/v1alpha1/podspecworkload/podspecworkload_controller.go b/pkg/controller/v1alpha1/podspecworkload/podspecworkload_controller.go index 46335b5be..90be90d58 100644 --- a/pkg/controller/v1alpha1/podspecworkload/podspecworkload_controller.go +++ b/pkg/controller/v1alpha1/podspecworkload/podspecworkload_controller.go @@ -65,6 +65,7 @@ type Reconciler struct { Scheme *runtime.Scheme } +// Reconcile is the main logic for podspecworkload controller // +kubebuilder:rbac:groups=standard.oam.dev,resources=podspecworkloads,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=standard.oam.dev,resources=podspecworkloads/status,verbs=get;update;patch // +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete @@ -266,6 +267,7 @@ func (r *Reconciler) renderService(workload *v1alpha1.PodSpecWorkload) (*corev1. return service, nil } +// SetupWithManager will setup controller for podspecworkload func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { r.record = event.NewAPIRecorder(mgr.GetEventRecorderFor("PodSpecWorkload")). WithAnnotations("controller", "PodSpecWorkload") diff --git a/pkg/controller/v1alpha1/routes/ingress/api.go b/pkg/controller/v1alpha1/routes/ingress/api.go index c1efc9486..109d161b7 100644 --- a/pkg/controller/v1alpha1/routes/ingress/api.go +++ b/pkg/controller/v1alpha1/routes/ingress/api.go @@ -10,8 +10,10 @@ import ( standardv1alpha1 "github.com/oam-dev/kubevela/api/v1alpha1" ) -// TypeNginx is a type of route implementation +// TypeNginx is a type of route implementation using [Nginx-Ingress](https://github.com/kubernetes/ingress-nginx) const TypeNginx = "nginx" + +// TypeContour is a type of route implementation using [contour ingress](https://github.com/projectcontour/contour) const TypeContour = "contour" const ( diff --git a/pkg/cue/convert.go b/pkg/cue/convert.go index af925454a..1f11487b7 100644 --- a/pkg/cue/convert.go +++ b/pkg/cue/convert.go @@ -120,6 +120,7 @@ func GetParameters(templatePath string) ([]types.Parameter, error) { } func getDefaultByKind(k cue.Kind) interface{} { + // nolint:exhaustive switch k { case cue.IntKind: var d int64 @@ -141,6 +142,7 @@ func getDefaultByKind(k cue.Kind) interface{} { // GetDefault evaluate default Go value from CUE func GetDefault(val cue.Value) interface{} { + // nolint:exhaustive switch val.Kind() { case cue.IntKind: if d, err := val.Int64(); err == nil { diff --git a/pkg/oam/application.go b/pkg/oam/application.go index e3cdab523..af35fc1ee 100644 --- a/pkg/oam/application.go +++ b/pkg/oam/application.go @@ -19,6 +19,7 @@ import ( "github.com/oam-dev/kubevela/pkg/server/apis" ) +// nolint:golint const ( DefaultChosenAllSvc = "ALL SERVICES" FlagNotSet = "FlagNotSet" diff --git a/pkg/oam/trait.go b/pkg/oam/trait.go index a360f456e..5da1aeae2 100644 --- a/pkg/oam/trait.go +++ b/pkg/oam/trait.go @@ -175,6 +175,7 @@ func AddOrUpdateTrait(env *types.EnvMeta, appName string, componentName string, if v.Alias != "" { name = v.Alias } + // nolint:exhaustive switch v.Type { case cue.IntKind: traitData[v.Name], err = flagSet.GetInt64(name) diff --git a/pkg/oam/workload.go b/pkg/oam/workload.go index 1588d0005..b1aa10f96 100644 --- a/pkg/oam/workload.go +++ b/pkg/oam/workload.go @@ -77,7 +77,7 @@ func BaseComplete(envName string, workloadName string, appName string, flagSet * } continue } - + // nolint:exhaustive switch v.Type { case cue.IntKind: workloadData[v.Name], err = flagSet.GetInt64(name) @@ -94,6 +94,7 @@ func BaseComplete(envName string, workloadName string, appName string, flagSet * if err != nil { if strings.Contains(err.Error(), "of flag of type string") { data, _ := flagSet.GetString(name) + // nolint:exhaustive switch v.Type { case cue.IntKind: workloadData[v.Name], err = strconv.ParseInt(data, 10, 64) diff --git a/pkg/plugins/cluster.go b/pkg/plugins/cluster.go index fa711a009..266de345c 100644 --- a/pkg/plugins/cluster.go +++ b/pkg/plugins/cluster.go @@ -4,10 +4,11 @@ import ( "context" "fmt" "io/ioutil" - "net/http" "os" "path/filepath" + "github.com/oam-dev/kubevela/pkg/utils/common" + corev1alpha2 "github.com/crossplane/oam-kubernetes-runtime/apis/core/v1alpha2" "github.com/crossplane/oam-kubernetes-runtime/pkg/oam/discoverymapper" "github.com/crossplane/oam-kubernetes-runtime/pkg/oam/util" @@ -167,13 +168,7 @@ func HandleTemplate(in *runtime.RawExtension, name, syncDir string) (types.Capab var cueTemplate string if tmp.CueTemplateURI != "" { - res, err := http.Get(tmp.CueTemplateURI) - if err != nil { - return types.Capability{}, err - } - //nolint:errcheck - defer res.Body.Close() - b, err := ioutil.ReadAll(res.Body) + b, err := common.HTTPGet(context.Background(), tmp.CueTemplateURI) if err != nil { return types.Capability{}, err } diff --git a/pkg/utils/common/common.go b/pkg/utils/common/common.go index b4ca73991..83b60fa46 100644 --- a/pkg/utils/common/common.go +++ b/pkg/utils/common/common.go @@ -1,7 +1,10 @@ package common import ( + "context" "fmt" + "io/ioutil" + "net/http" "os" "github.com/crossplane/oam-kubernetes-runtime/apis/core" @@ -40,3 +43,19 @@ func InitBaseRestConfig() (types.Args, error) { Schema: Scheme, }, nil } + +// HTTPGet will send GET http request with context +func HTTPGet(ctx context.Context, url string) ([]byte, error) { + // Change NewRequest to NewRequestWithContext and pass context it + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return nil, err + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + //nolint:errcheck + defer resp.Body.Close() + return ioutil.ReadAll(resp.Body) +} diff --git a/pkg/utils/env/env.go b/pkg/utils/env/env.go index 7f6f9be39..d64077d1f 100644 --- a/pkg/utils/env/env.go +++ b/pkg/utils/env/env.go @@ -207,7 +207,7 @@ func ListEnvs(envName string) ([]*types.EnvMeta, error) { if !f.IsDir() { continue } - data, err := ioutil.ReadFile(filepath.Join(envDir, f.Name(), system.EnvConfigName)) + data, err := ioutil.ReadFile(filepath.Clean(filepath.Join(envDir, f.Name(), system.EnvConfigName))) if err != nil { continue } diff --git a/pkg/webhook/metrics/validating_handler.go b/pkg/webhook/metrics/validating_handler.go index 193013c67..2bd171a69 100644 --- a/pkg/webhook/metrics/validating_handler.go +++ b/pkg/webhook/metrics/validating_handler.go @@ -56,6 +56,7 @@ func (h *ValidatingHandler) Handle(ctx context.Context, req admission.Request) a return admission.Errored(http.StatusBadRequest, err) } + //nolint:exhaustive switch req.AdmissionRequest.Operation { case admissionv1beta1.Create: if allErrs := ValidateCreate(obj); len(allErrs) > 0 { diff --git a/pkg/webhook/podspecworkload/validating_handler.go b/pkg/webhook/podspecworkload/validating_handler.go index 47e56815a..c54351a8e 100644 --- a/pkg/webhook/podspecworkload/validating_handler.go +++ b/pkg/webhook/podspecworkload/validating_handler.go @@ -55,6 +55,7 @@ func (h *ValidatingHandler) Handle(ctx context.Context, req admission.Request) a return admission.Errored(http.StatusBadRequest, err) } + //nolint:exhaustive switch req.AdmissionRequest.Operation { case admissionv1beta1.Create: if allErrs := ValidateCreate(obj); len(allErrs) > 0 { @@ -69,6 +70,8 @@ func (h *ValidatingHandler) Handle(ctx context.Context, req admission.Request) a if allErrs := ValidateUpdate(obj, oldObj); len(allErrs) > 0 { return admission.Errored(http.StatusUnprocessableEntity, allErrs.ToAggregate()) } + default: + // Do nothing for DELETE and CONNECT } return admission.ValidationResponse(true, "")